I code snippets sono delle porzioni di codice php pronte all’uso che servono per estendere le funzionalità del nostro amato WordPress.
Basta copiarli ed incollarli nel file functions.php del tuo tema, oppure usarli in un plugin personalizzato (plugin VS functions.php).
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).
Indice
- Code snippets per functions.php
- Permettere l’esecuzione del codice php nei widget
- Impostare la lunghezza minima degli articoli
- Aggiungere del codice personalizzato sotto ogni articolo
- Aggiungere link cancella, spam, approva ai commenti
- Redirect degli utenti ad un URL specifico dopo la registrazione
- Aggiungere le breadcrumbs senza plugin
- Non eseguire l’HTML nei commenti
- Rimuovere gli auto-link nei commenti
- Imposta una lunghezza personalizzata per l’excerpt (il riassunto)
- Imposta come terminare l’excerpt (il riassunto)
- Rimuovere il campo SITO WEB/URL dalla sezione commenti
- Cambia l’URL dei feed rss senza .htaccess
- Escludere i post di una o più categorie dalla homepage
- Aggiungere del testo alla pagina di login
- Escludere le pagine dalla ricerca
- Attivare la Maintenance Mode (modalità manutenzione)
- Visual Editor CSS
- CSS per il pannello di amministrazione
- Nascondere la versione di WordPress
- Rimuovere i menù dal pannello di amministrazione
- Aggiungere Widget personalizzato alla bacheca
- Disabilitare i widget di default
- Aggiungere/rimuovere informazioni utente
- Code snippets da aggiungere al file wp-config.php
- Code snippets per .htaccess
- Altre risorse interessanti
Code snippets per functions.php
Aggiungi questi codici nel file functions.php del tuo tema.
Permettere l’esecuzione del codice php nei widget
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]
Impostare la lunghezza minima degli articoli
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]
Aggiungere del codice personalizzato sotto ogni articolo
function add_post_content($content) {
if(!is_feed() && !is_home()) {
$content .= '
This article is copyright © '.date('Y').' '.bloginfo('name').'
';
}
return $content;
}
add_filter('the_content', 'add_post_content');
[fonte]
Aggiungere link cancella, spam, approva ai commenti
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 = ' %3$s';
$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]
Redirect degli utenti ad un URL specifico dopo la registrazione
function __my_registration_redirect(){
return home_url( '/my-page' );
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
[fonte]
function the_breadcrumb() {
echo '
';
if (!is_home()) {
echo '
';
echo 'Home';
echo "
";
if (is_category() || is_single()) {
echo '
';
the_category('
');
if (is_single()) {
echo "
";
the_title();
echo '
';
}
} elseif (is_page()) {
echo '
';
echo the_title();
echo '
';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"
Archive for "; the_time('F jS, Y'); echo'
';}
elseif (is_month()) {echo"
Archive for "; the_time('F, Y'); echo'
';}
elseif (is_year()) {echo"
Archive for "; the_time('Y'); echo'
';}
elseif (is_author()) {echo"
Author Archive"; echo'
';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "
Blog Archives"; echo'
';}
elseif (is_search()) {echo"
Search Results"; echo'
';}
echo '
';
}
Dopodichè inserire il seguente codice dove si vuole mostrare le breadcrumbs (ad esempio nel file header.php appena dopo il
<?php the_breadcrumb(); ?>
[fonte]
Non eseguire l’HTML nei commenti
// 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]
Rimuovere gli auto-link nei commenti
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]
Imposta una lunghezza personalizzata per l’excerpt (il riassunto)
/* 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]
Imposta come terminare l’excerpt (il riassunto)
/* 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]
Rimuovere il campo SITO WEB/URL dalla sezione commenti
function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');
[fonte]
Cambia l’URL dei feed rss senza .htaccess
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]
Escludere i post di una o più categorie dalla homepage
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]
Aggiungere del testo alla pagina di login
function wps_login_message( $message ) {
if ( empty($message) ){
return "
Welcome to this site. Please log in to continue
";
} else {
return $message;
}
}
add_filter( 'login_message', 'wps_login_message' );
[fonte]
Escludere le pagine dalla ricerca
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts', 'filter_search');
[fonte]
Attivare la Maintenance Mode (modalità manutenzione)
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]
Visual Editor CSS
function my_theme_add_editor_styles() {
add_editor_style( 'custom-editor-style.css' );
}
add_action( 'init', 'my_theme_add_editor_styles' );
[fonte]
CSS per il pannello di amministrazione
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]
Nascondere la versione di WordPress
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]
Aggiungere Widget personalizzato alla bacheca
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 '
Welcome to Custom Blog Theme! Need help? Contact the developer here. For WordPress Tutorials visit: WPBeginner
';
}
[fonte]
Disabilitare i widget di default
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]
Aggiungere/rimuovere informazioni utente
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');
Code snippets da aggiungere al file wp-config.php
Codici da aggiungere al file wp-config.php (si trova nella root).
Aumentare il limite della memoria
define('WP_MEMORY_LIMIT', '128M');
Disabilitare gli aggiornamenti automatici di WP
define( 'AUTOMATIC_UPDATER_DISABLED', true );
[fonte]
Code snippets per .htaccess
Codici da aggiungere al file .htaccess (si trova nella root).
Imposta la cache del browser
# 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>
Abilita la compressione
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
<FilesMatch ".(js|css|html|htm|php|xml|ttf|eot|svg)$">
SetOutputFilter DEFLATE
</FilesMatch>
Altre risorse interessanti
- Shun the Plugin: 100 WordPress Code Snippets from Across the Net
- 25+ Extremely Useful Tricks for the WordPress Functions File
Buon smanettamento a tutti!


