I code snippets sono delle porzioni di codice php pronte all’uso che servono per estendere le funzionalità del nostro amato WordPress (con WordPress si può fare di tutto), copiandoli ed incollandoli nel file functions.php del tuo tema (prima del tag “?>” ), oppure nel file wp-config.php o ancora nel file .htaccess (questi ultimi due si trovano nella root).
Quindi, trovi quello che ti serve, lo copi, lo incolli ed aggiorni il file. Nient’altro. Figo, no?
Per semplificarti la vita e la gestione dei code snippets, puoi anche dare un’occhiata all’omonimo plugin.
In ogni caso, prima di qualsiasi modifica, consiglio di fare un backup dei 3 file (scaricali sul computer).
Aggiungi questi codici nel file functions.php del tuo tema.
function ri_php_text($text) { if (strpos($text, '<' . '?') !== false) { ob_start(); eval('?' . '>' . $text); $text = ob_get_contents(); ob_end_clean(); } return $text; } add_filter('widget_text', 'ri_php_text', 99);
[fonte]
function minWord($content){ global $post; $num = 100; //imposta il numero minimo di parole $content = $post->post_content; if (str_word_count($content) < $num) wp_die( __('Errore: l'articolo è troppo breve.') ); } add_action('publish_post', 'minWord');
[fonte]
function add_post_content($content) { if(!is_feed() && !is_home()) { $content .= '<p>This article is copyright © '.date('Y').' '.bloginfo('name').'</p>'; } return $content; } add_filter('the_content', 'add_post_content');
[fonte]
Gestire i commenti richede molto tempo e spesso bisogna farlo dal pannello di amministrazione, rendendo le cose ancora più lente. Con questo code snippet puoi aggiungere i link per cancellare, segnare come spam o approvare direttamente nella pagina dell’articolo.
if ( ! function_exists( 't5_comment_mod_links' ) ) { add_filter( 'edit_comment_link', 't5_comment_mod_links', 10, 2 ); /** * Adds Spam and Delete links to the Sdit link. * * @wp-hook edit_comment_link * @param string $link Edit link markup * @param int $id Comment ID * @return string */ function t5_comment_mod_links( $link, $id ) { $template = ' <a class="comment-edit-link" href="%1$s%2$s">%3$s</a>'; $admin_url = admin_url( "comment.php?c=$id&action=" ); // Mark as Spam. $link .= sprintf( $template, $admin_url, 'cdc&dt=spam', __( 'Spam' ) ); // Delete. $link .= sprintf( $template, $admin_url, 'cdc', __( 'Delete' ) ); // Approve or unapprove. $comment = get_comment( $id ); if ( '0' === $comment->comment_approved ) { $link .= sprintf( $template, $admin_url, 'approvecomment', __( 'Approve' ) ); } else { $link .= sprintf( $template, $admin_url, 'unapprovecomment', __( 'Unapprove' ) ); } return $link; } }
[fonte]
function __my_registration_redirect(){ return home_url( '/my-page' ); } add_filter( 'registration_redirect', '__my_registration_redirect' );
[fonte]
function the_breadcrumb() { echo '<ul id="crumbs">'; if (!is_home()) { echo '<li><a href="'; echo get_option('home'); echo '">'; echo 'Home'; echo "</a></li>"; if (is_category() || is_single()) { echo '<li>'; the_category(' </li><li> '); if (is_single()) { echo "</li><li>"; the_title(); echo '</li>'; } } elseif (is_page()) { echo '<li>'; echo the_title(); echo '</li>'; } } elseif (is_tag()) {single_tag_title();} elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';} elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';} elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';} elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';} elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';} elseif (is_search()) {echo"<li>Search Results"; echo'</li>';} echo '</ul>'; }
Dopodichè inserire il seguente codice dove si vuole mostrare le breadcrumbs (ad esempio nel file header.php appena dopo il <div class=”wrapper” id=”main”>):
<?php the_breadcrumb(); ?>
[fonte]
// This will occur when the comment is posted function plc_comment_post( $incoming_comment ) { // convert everything in a comment to display literally $incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']); // the one exception is single quotes, which cannot be #039; because WordPress marks it as spam $incoming_comment['comment_content'] = str_replace( "'", ''', $incoming_comment['comment_content'] ); return( $incoming_comment ); } // This will occur before a comment is displayed function plc_comment_display( $comment_to_display ) { // Put the single quotes back in $comment_to_display = str_replace( ''', "'", $comment_to_display ); return $comment_to_display; } add_filter( 'preprocess_comment', 'plc_comment_post', '', 1 ); add_filter( 'comment_text', 'plc_comment_display', '', 1 ); add_filter( 'comment_text_rss', 'plc_comment_display', '', 1 ); add_filter( 'comment_excerpt', 'plc_comment_display', '', 1 ); // This stops WordPress from trying to automatically make hyperlinks on text: remove_filter( 'comment_text', 'make_clickable', 9 );
[fonte]
Di default, quando qualcuno lascia un link nei commenti, questo diventa cliccabile. Per rendere il link inattivo (l’utente non lo può cliccare), aggiungi questo code snippet.
remove_filter('comment_text', 'make_clickable', 9);
[fonte]
/* Codice per modificare la lunghezza dell'excerpt by Roberto Iacono di robertoiacono.it */ function ri_excerpt_length($length) { return 100; } add_filter('excerpt_length', 'ri_excerpt_length');
[fonte]
/* Codice per impostare come termina l'excerpt by Roberto Iacono di robertoiacono.it */ function ri_new_excerpt_more($more) { return ' ...'; } add_filter('excerpt_more', 'ri_new_excerpt_more');
[fonte]
function remove_comment_fields($fields) { unset($fields['url']); return $fields; } add_filter('comment_form_default_fields','remove_comment_fields');
[fonte]
Per comodità esiste il plugin apposito per redirigere i feed rss di WordPress a quelli creati con Feedburner, ma se si vuole presentare un lavoro leggero e senza troppi plugin, ecco un’ottima soluzione:
function custom_feed_link($output, $feed) { $feed_url = 'http://feeds.feedburner.com/robertoiacono'; $feed_array = array('rss' => $feed_url, 'rss2' => $feed_url, 'atom' => $feed_url, 'rdf' => $feed_url, 'comments_rss2' => ''); $feed_array[$feed] = $feed_url; $output = $feed_array[$feed]; return $output; } function other_feed_links($link) { $link = 'http://feeds.feedburner.com/robertoiacono'; return $link; } //Add our functions to the specific filters add_filter('feed_link','custom_feed_link', 1, 2); add_filter('category_feed_link', 'other_feed_links'); add_filter('author_feed_link', 'other_feed_links'); add_filter('tag_feed_link','other_feed_links'); add_filter('search_feed_link','other_feed_links');
[fonte]
function exclude_category_home( $query ) { if ( $query->is_home ) { $query->set( 'cat', '-5, -34'); // change category IDs } return $query; } add_filter( 'pre_get_posts', 'exclude_category_home' );
[fonte]
function wps_login_message( $message ) { if ( empty($message) ){ return "<p class='message'>Welcome to this site. Please log in to continue</p>"; } else { return $message; } } add_filter( 'login_message', 'wps_login_message' );
[fonte]
function filter_search($query) { if ($query->is_search) { $query->set('post_type', 'page'); } return $query; } add_filter('pre_get_posts', 'filter_search');
[fonte]
Mette il blog in modalità manutenzione, impedirai momentaneamente agli utenti di accedervi.
function maintenace_mode() { if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) { die('Maintenance.'); } } add_action('get_header', 'maintenace_mode');
[fonte]
function my_theme_add_editor_styles() { add_editor_style( 'custom-editor-style.css' ); } add_action( 'init', 'my_theme_add_editor_styles' );
[fonte]
function my_admin_theme_style() { wp_enqueue_style('my-admin-theme', get_template_directory_uri() . '/wp-admin.css'); } add_action('admin_enqueue_scripts', 'my_admin_theme_style'); add_action('login_enqueue_scripts', 'my_admin_theme_style');
[fonte]
Nasconde la versione di WordPress dal sorgente HTML del blog.
remove_action('wp_head', 'wp_generator');
[fonte]
function remove_menus () { global $menu; $restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins')); end ($menu); while (prev($menu)){ $value = explode(' ',$menu[key($menu)][0]); if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);} } } add_action('admin_menu', 'remove_menus');
[fonte]
add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets'); function my_custom_dashboard_widgets() { global $wp_meta_boxes; wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help'); } function custom_dashboard_help() { echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials visit: <a href="http://www.wpbeginner.com" target="_blank">WPBeginner</a></p>'; }
[fonte]
function unregister_default_wp_widgets() { unregister_widget('WP_Widget_Calendar'); unregister_widget('WP_Widget_Search'); unregister_widget('WP_Widget_Recent_Comments'); } add_action('widgets_init', 'unregister_default_wp_widgets', 1);
[fonte]
function extra_contact_info($contactmethods) { unset($contactmethods['aim']); unset($contactmethods['yim']); unset($contactmethods['jabber']); $contactmethods['facebook'] = 'Facebook'; $contactmethods['twitter'] = 'Twitter'; $contactmethods['linkedin'] = 'LinkedIn'; return $contactmethods; } add_filter('user_contactmethods', 'extra_contact_info');
Codici da aggiungere al file wp-config.php (si trova nella root).
define('WP_MEMORY_LIMIT', '128M');
define( 'AUTOMATIC_UPDATER_DISABLED', true );
[fonte]
Codici da aggiungere al file .htaccess (si trova nella root).
# BEGIN Cache-Control Headers - add expiry dates or max-age for images or css <ifmodule mod_headers.c> <filesmatch ".(flv|gif|jpg|jpeg|png|ico|swf)$"> Header set Cache-Control "max-age=2592000" </filesmatch> <filesmatch ".(css|pdf)$"> Header set Cache-Control "max-age=2592000" </filesmatch> <filesmatch ".(js)$"> Header set Cache-Control "max-age=2592000, private" </filesmatch> </ifmodule>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css <FilesMatch ".(js|css|html|htm|php|xml|ttf|eot|svg)$"> SetOutputFilter DEFLATE </FilesMatch>
Buon smanettamento a tutti!
Puoi ripubblicare i contenuti di questo articolo solo in parte e fornendo un link all’articolo originale.
Link al post originale: 25+ WordPress Code Snippets.
Copyright © Roberto Iacono.
Powered by WPeMatico