WordPress snippet collection

header image tutorial wordpress snippet collection

WordPress is a wonderfully flexible CMS, you can make almost any kind of site with it. Because I like to build my websites as lean as possible, I like using a bare framework theme. I made my own adaptation of the theme, which I think is an excellent compromise between bare theme and basic functionalities. It also works with SASS, which I prefer over LESS.

For extra functionality, I primarily search for solutions that do not require a plug-in. This page is a collection of WordPress code snippets I have collected. None of them are of my own making, although some I have refined or retuned to my specific need. I have mentioned the original source of the snippet wherever I had it documented.

I created my own custom-functions.php with extra functions, which is called at the bottom of functions.php with the following line of code:

require_once get_template_directory() . '/inc/custom-functions.php';

Each of the snippets here should be added to functions.php (or a custom functions file like I created), unless specifically mentioned otherwise.

In my humble opinion, this is highly preferable over adding plug-ins for all those functions. Plug-ins are a great thing, but require extra maintenance, may pose extra security risk and often come with more functionality than required, making the site unnecessarily bloated. This especially applies for plugins that load extra css or js files.

1.00 WP admin snippets

1.01 Add your own custom logo to the WordPress dashboard

// Add custom dashboard logo
add_action('admin_head', 'my_custom_logo');
 
function my_custom_logo() {
echo '
<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/img/logo.jpg) !important; }
</style>
';
}

1.02 Add your custom favicon to the WordPress login page and WP-admin

Customizing the login page by adding your client’s favicon is a nice gesture toward your customer.

// WP-admin & WP-login favicon
function adminfavicon(){
echo '<link rel="shortcut icon" href="',get_template_directory_uri(),'/adm/img/admin-favicon.png" />',"\n";
}

add_action('admin_head','adminfavicon'); 
add_action('login_head','adminfavicon');

1.03 Add your own custom logo to the WordPress login page

By the same token, you can add your client’s logo to the login page.

// Change login page logo
function my_login_logo() { ?>
    <style type="text/css">
        body.login { background-color:#ef4c23; }
            body.login div#login { padding-top:2%; }
                body.login div#login h1 a {
                    background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/img/logo.jpg);
                    padding-bottom: 30px;
                    width:84px;
                    height:84px;
                }
          body.login #backtoblog, .login #nav { background:#fff; width:274px; text-align:center; border-radius:2px; display:block; }
          body.login #backtoblog a, .login #nav a { width:100%; padding:10px 20px; display:block; color:#ef4c23; }
          body.login #backtoblog a:hover, .login #nav a:hover { color:#522594; text-decoration:underline; }
    </style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );

1.04 Change login page logo URL

You can also change the login page logo URL.

// Change login page logo URL
function my_login_logo_url() {
    return home_url();
}
add_filter( 'login_headerurl', 'my_login_logo_url' );

function my_login_logo_url_title() {
    $site_title = get_bloginfo( 'name');
    return $site_title;
}
add_filter( 'login_headertitle', 'my_login_logo_url_title' );

1.05 Modify the text in the WP-admin footer

Add your own credits if you like!

// Modify text in WP Admin footer
function modify_footer_admin () {  
  echo 'Created by <a href="https://www.yourdomain.com">Your name here</a>. Powered by <a href="https://www.wordpress.org">WordPress</a>';  
}  
  
add_filter('admin_footer_text', 'modify_footer_admin');

1.06 Disable the visual editor

If you think the visual editor is a pain in the ass, you can easily disable it.

// Disable the visual editor
add_filter('user_can_richedit' , create_function('' , 'return false;') , 50);

1.07 Remove widgets from the WP admin dashboard

If you want to keep your installation as clean as possible, you may want to remove any widget areas added by a parent theme. In the parent theme’s functions.php, you can find the exact names of the widget areas. This is a better method than deleting them from the parent theme, because the widget areas would then return after a parent theme update.

// Remove widget areas from WP Admin dashboard
function disable_default_dashboard_widgets() {  
    //   remove_meta_box('dashboard_right_now', 'dashboard', 'core');  
    //   remove_meta_box('dashboard_recent_comments', 'dashboard', 'core');  
    remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');  
    remove_meta_box('dashboard_plugins', 'dashboard', 'core');  
    remove_meta_box('dashboard_quick_press', 'dashboard', 'core');  
    //        remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');  
    remove_meta_box('dashboard_primary', 'dashboard', 'core');  
    remove_meta_box('dashboard_secondary', 'dashboard', 'core');  
}  
add_action('admin_menu', 'disable_default_dashboard_widgets'); 

1.08 Set different background colors for pages/posts with different statuses

A nice snippet from making it easy to spot draft posts and such.

// set different colors for pages/posts in different statuses
add_action('admin_footer','posts_status_color');
function posts_status_color(){
	?>
	<style>
	    .status-draft{background: #FCE3F2 !important;}
	    .status-pending{background: #87C5D6 !important;}
	    .status-publish{/* no background keep wp alternating colors */}
	    .status-future{background: #C6EBF5 !important;}
	    .status-private{background:#F2D46F;}
	</style>
	<?php
}

1.09 Add ID column to posts and pages overview

Another very practical snippet from . Sometimes you need to look up the ID a page or post. With this snippet, a column is added to the posts and pages overviews, making it very easy to retrieve them.

// Add ID's to posts & pages overviews
add_filter('manage_posts_columns', 'posts_columns_id', 5);
add_action('manage_posts_custom_column', 'posts_custom_id_columns', 5, 2);
add_filter('manage_pages_columns', 'posts_columns_id', 5);
add_action('manage_pages_custom_column', 'posts_custom_id_columns', 5, 2);

function posts_columns_id($defaults){
    $defaults['wps_post_id'] = __('ID');
    return $defaults;
}
function posts_custom_id_columns($column_name, $id){
        if($column_name === 'wps_post_id'){
                echo $id;
    }
}

1.10 Add ID column to categories overview

This snippet does the same as the snippet above, but then for the categories overview page.

// Add ID to categories overview
function categoriesColumnsHeader($columns) {
        $columns['catID'] = __('ID');
        return $columns;
}

add_filter( 'manage_categories_columns', 'categoriesColumnsHeader' );

function categoriesColumnsRow($argument, $columnName, $categoryID){
        if($columnName == 'catID'){
                return $categoryID;
        }
}

add_filter( 'manage_categories_custom_column', 'categoriesColumnsRow', 10, 3);

1.11 Determine the ID column width

Adding to the two snippets above, this snippet allows you to set the width of the added column. Also from .

// Determine ID column width
add_action('admin_head', 'custom_admin_styling');
function custom_admin_styling() {
echo '<style type="text/css">';
echo 'th#wps_post_id{width:50px;}';
echo '</style>';
}

1.12 Remove Links from WP-admin menu

I never use the Links function, so I always remove it altogether.

// Remove links item from WP-admin
add_action( 'admin_menu', 'remove_links_menu' );
function remove_links_menu() {
     remove_menu_page('link-manager.php');
}

1.13 Create dashboard widget with most recent posts

Another snippet, this adds a widget to the dashboard containing the most recent posts. In the example it’s set at 5, but you can change the figure to whatever suits you.

// Create dashboard widget of most recent posts
function wps_recent_posts_dw() {
?>
   <ol>
     <?php
          global $post;
          $args = array( 'numberposts' => 5 );

          $myposts = get_posts( $args );
                foreach( $myposts as $post ) :  setup_postdata($post); ?>
                    <li> (<? the_date('Y / n / d'); ?>) <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
          <?php endforeach; ?>
   </ol>
<?php
}

function add_wps_recent_posts_dw() {
       wp_add_dashboard_widget( 'wps_recent_posts_dw', __( 'Recent Posts' ), 'wps_recent_posts_dw' );
}
add_action('wp_dashboard_setup', 'add_wps_recent_posts_dw' );

2.00 Media snippets

2.01 Change default ‘add media’ settings

This WordPress snippet allows you to change the default ‘add media’ settings ‘align’, ‘link type’ and ‘default size’. Very handy!

// Change default add media settings (from wpsnipp.com)
function wps_attachment_display_settings() {
        update_option( 'image_default_align', 'center' ); // left, center, right, none
        update_option( 'image_default_link_type', 'none' );
        update_option( 'image_default_size', 'full size' ); // thumbnail, medium, large, full size
}
add_action( 'after_setup_theme', 'wps_attachment_display_settings' );

2.02 Show media ID in media library

This snippet adds a column to the media library containing each image’s ID.

// Show media ID in media library overview
function column_id($columns) {
    $columns['colID'] = __('ID');
    return $columns;
}
add_filter( 'manage_media_columns', 'column_id' );
function column_id_row($columnName, $columnID){
    if($columnName == 'colID'){
       echo $columnID;
    }
}
add_filter( 'manage_media_custom_column', 'column_id_row', 10, 2 );

2.03 Show image dimensions in media library

A great little snippet, revealing each image’s dimensions in a separate column in the media library.

// Show image dimensions in media library overview
function wh_column( $cols ) {
        $cols["dimensions"] = "Dimensions (w, h)";
        return $cols;
}
add_filter( 'manage_media_columns', 'wh_column' );
function wh_value( $column_name, $id ) {
    if ( $column_name == "dimensions" ):
    $meta = wp_get_attachment_metadata($id);
           if(isset($meta['width']))
           echo $meta['width'].' x '.$meta['height'];
    endif;
}
add_action( 'manage_media_custom_column', 'wh_value', 11, 3 );

2.04 Show full URL in media library

Very handy if you need to copy the image URL. A lot quicker than opening the image in the library, especially if you need to copy more than one.

// Show full URL in media library overview
function muc_column( $cols ) {
        $cols["media_url"] = "URL";
        return $cols;
}
function muc_value( $column_name, $id ) {
        if ( $column_name == "media_url" ) echo '<input type="text" width="100%" onclick="jQuery(this).select();" value="'. wp_get_attachment_url( $id ). '" />';
}
add_filter( 'manage_media_columns', 'muc_column' );
add_action( 'manage_media_custom_column', 'muc_value', 10, 2 );

2.05 Automatically set image Title, Alt-Text, Caption & Description upon upload

For SEO and usability purposes, filling out the extra fields for each image is advisable. It is also a lot of work, or you may forget. With this great snippet from , all fields are filled automatically using the filename. If you do enter your own input, that will ofcourse be saved instead.

// Automatically set the image Title, Alt-Text, Caption & Description upon upload
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {

    // Check if uploaded file is an image, else do nothing

    if ( wp_attachment_is_image( $post_ID ) ) {

        $my_image_title = get_post( $post_ID )->post_title;

        // Sanitize the title:  remove hyphens, underscores & extra spaces:
        $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );

        // Sanitize the title:  capitalize first letter of every word (other letters lower case):
        $my_image_title = ucwords( strtolower( $my_image_title ) );

        // Create an array with the image meta (Title, Caption, Description) to be updated
        // Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
        $my_image_meta = array(
            'ID'        => $post_ID,            // Specify the image (ID) to be updated
            'post_title'    => $my_image_title,     // Set image Title to sanitized title
            'post_excerpt'  => $my_image_title,     // Set image Caption (Excerpt) to sanitized title
            'post_content'  => $my_image_title,     // Set image Description (Content) to sanitized title
        );

        // Set the image Alt-Text
        update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );

        // Set the image meta (e.g. Title, Excerpt, Content)
        wp_update_post( $my_image_meta );

    } 
}

2.06 Allow SVG files in Media Library through uploader

Time to update that Media Library with SVG files. Snippet from

function cc_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

3.00 Security snippets

3.01 Disable theme / plugin text editor

I never use the built-in text editor to edit theme or plug-in files in WP-admin, nor do I want my clients to. It’s also a security risk. Anyone who manages to hack a user account can modify php files and javascripts. Standard code snippet for my sites, courtesy of

// Disable the theme / plugin text editor in Admin
define('DISALLOW_FILE_EDIT', true);

3.02 Remove WP version

Telling hackers which version of WP you are running gives them an easy way to determine which security leaks it contains. Better to hide it and keep them in the dark.

// Remove WP version
function wpbeginner_remove_version() {
return '';
}
add_filter('the_generator', 'wpbeginner_remove_version');

3.03 Hide email address from the markup on your site

Bots with dubious intentions are always scouring the web for email addresses. With this nifty function from , putting the email address between shortcode brackets makes it hashed in the page source code.

// Hide email address from the markup on your site.
// use by putting each email address in shortcode like this: [email]dude@example.com[/email]
function encode_email_shortcode($atts, $content = null) {
    for ($i = 0; $i < strlen($content); $i++) $encodedmail .= "&#" . ord($content[$i]) . ';';
    return '<a class="encoded-email" href="mailto:' . $encodedmail . '">' . $encodedmail . '</a>';
}
add_shortcode('email', 'encode_email_shortcode');

3.04 Remove default user roles

To keep things clean and minimize security risks, you can disable each default user role that remains unused. Another snippet from

// Remove default user roles (from wpsnipp.com)
function wps_remove_role() {
//    remove_role( 'editor' );
    remove_role( 'author' );
    remove_role( 'contributor' );
    remove_role( 'subscriber' );
}
add_action( 'init', 'wps_remove_role' );

3.05 Add user role and capabilities

By the same token, you can add roles and capabilities.

// Add user role & capabilities
function wps_add_role() {
    add_role( 'manager', 'Manager', 
             array(
                  'read',
                  'edit_posts',
                  'delete_posts',
                  )
    );
}
add_action( 'init', 'wps_add_role' );

3.06 Lead failed login away from WP login page

Lead a failed login away from your login page, such as login.php (or something else. I recommend changing this from the default location using the plugin as I have not found a well-working function for this purpose).

// Make sure a failed login does not lead the visitor to the WP-login page
if( ! function_exists( 'custom_login_fail' ) ) {
    function custom_login_fail( $username ) {
        $referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from?
        // if there's a valid referrer, and it's not the default log-in screen
        if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
            if ( !strstr($referrer,'?login=failed') ) { // make sure we don’t append twice
                wp_redirect( $referrer . '?login=failed' ); // append some information (login=failed) to the URL for the theme to use
            } else {
                wp_redirect( $referrer );
            }
            exit;
        }
    }
}
add_action( 'wp_login_failed', 'custom_login_fail' ); // hook failed login
if( ! function_exists( 'custom_login_empty' ) ) {
    function custom_login_empty(){
        $referrer = $_SERVER['HTTP_REFERER'];
        if ( strstr($referrer,get_home_url()) && $user==null ) { // mylogin is the name of the loginpage.
            if ( !strstr($referrer,'?login=empty') ) { // prevent appending twice
                wp_redirect( $referrer . '?login=empty' );
            } else {
                wp_redirect( $referrer );
            }
        }
    }
}
add_action( 'authenticate', 'custom_login_empty');

3.07 Redirect users to previous page upon login

Instead of redirecting all visitors to the homepage upon login, redirect them to the page they were on before logging in.

// Redirect users to previous page upon login
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
        add_filter('login_redirect', 'my_login_redirect', 10, 3);
        function my_login_redirect() {
                $location = $_SERVER['HTTP_REFERER'];
                wp_safe_redirect($location);
                exit();
        }
}

3.08 Redirect to homepage after logout

Speaks for itself.

// redirect to homepage after logout
add_action('wp_logout',create_function('','wp_redirect(home_url());exit();'));

4.00 Frontend snippets

4.01 Set website in maintenance mode

To de-activate maintenance mode, simply comment out the add_action line. And no, it’s not a typo.

// Set website in maintenance mode.
function maintenace_mode() {
      if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {wp_die('Maintenance.');}
}
add_action('get_header', 'maintenace_mode');

4.02 Add login/logout link to main menu

Simply adds a login/logout function to the main navigation menu.

// Add login/logout link to main menu
//add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) { 
        $loginoutlink = wp_loginout('index.php', false); 
        $items .= '<li>'. $loginoutlink .'</li>'; 
    return $items; 
}

4.03 User agent and OS detection and add body class

Thankfully, the need to target specific browsers or operating systems with CSS is more and more a thing of the past. But sometimes, it can still be very handy to circument one of those IE bugs. Or Safari, which seems to have become the new IE.

// User agent and OS detection & add body class
function mv_browser_body_class($classes) {
        global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
        if($is_lynx) $classes[] = 'lynx';
        elseif($is_gecko) $classes[] = 'gecko';
        elseif($is_opera) $classes[] = 'opera';
        elseif($is_NS4) $classes[] = 'ns4';
        elseif($is_safari) $classes[] = 'safari';
        elseif($is_chrome) $classes[] = 'chrome';
        elseif($is_IE) {
            $classes[] = 'ie';
            if(preg_match('/MSIE ([0-9]+)([a-zA-Z0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $browser_version))
            $classes[] = 'ie'.$browser_version[1];
        } else $classes[] = 'unknown';
        if($is_iphone) $classes[] = 'iphone';
        if ( stristr( $_SERVER['HTTP_USER_AGENT'],"mac") ) {
             $classes[] = 'osx';
           } elseif ( stristr( $_SERVER['HTTP_USER_AGENT'],"linux") ) {
             $classes[] = 'linux';
           } elseif ( stristr( $_SERVER['HTTP_USER_AGENT'],"windows") ) {
             $classes[] = 'windows';
           }
        return $classes;
    }
    add_filter('body_class','mv_browser_body_class');

4.04 Force subcategories to use parent category template

To avoid having to create separate templates for each sub-category, this handy code snippet from allows you to force subcategories to use the same template as their parent.

// Force subcategories to use parent category template
function new_subcategory_hierarchy() {  
    $category = get_queried_object();
 
    $parent_id = $category->category_parent;
 
    $templates = array();
     
    if ( $parent_id == 0 ) {
        // Use default values from get_category_template()
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
        $templates[] = 'category.php';      
    } else {
        // Create replacement $templates array
        $parent = get_category( $parent_id );
 
        // Current first
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
 
        // Parent second
        $templates[] = "category-{$parent->slug}.php";
        $templates[] = "category-{$parent->term_id}.php";
        $templates[] = 'category.php';  
    }
    return locate_template( $templates );
}
 
add_filter( 'category_template', 'new_subcategory_hierarchy' );

4.05 Load Google webfonts

Of course you can also load webfonts directly in CSS. There has been a lot of discussion on the web as to the fastest method to load those webfonts. As far as I gathered, this seems to be the cleanest and swiftest method available. Simply paste the complete URL below.

// Add Google webfonts
function load_fonts() {
        wp_register_style('googleFonts', 'https://fonts.googleapis.com/css?family=Comfortaa:400|Fredericka+the+Great|Work+Sans:400,700');
        wp_enqueue_style( 'googleFonts');
    }

add_action('wp_print_styles', 'load_fonts');

4.06 Load FontAwesome icons

The quickest way to load those great FontAwesome icons is via their CDN.

// Load FontAwesome icons
wp_enqueue_style( 'icons', 'https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css', array(), '4.7.0' );

4.07 Add favicon

Yes, you can also add the favicon in the theme’s header.php file. But this way there is only a single location, even if there are different headers for different pages. Make sure to put the favicon in the website’s root folder, not in the theme folder, which does not work.

function favicon() {
    echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.png" />';
}
add_action('wp_head', 'favicon');

4.08 Add an apple touch icon

Same as with the favicon, you can add this in the header directly. But I prefer it this way. Put the icon file in the theme’s img folder.

// add a apple touch icon
add_action( 'wp_head', 'touch_icon', 10); 
function touch_icon () { ?> 
<link rel="apple-touch-icon" href="<?php echo get_stylesheet_directory_uri(); ?>/img/apple-touch-icon.png"> 
<?php }

4.09 Remove empty paragraph tags

Switching the autop function both on or off have their benefits and downsides. But there are several possibilities for disabling it only for specific “page-types”, as you can see in the couple of snippets below.

// Remove empty <p></p> tags
remove_filter('the_content', 'wpautop');

Remove empty paragraph tags on pages (not posts)

remove_filter('the_content', 'wpautop');
function remove_p_on_pages() {
    if ( is_page() ) {
        remove_filter( 'the_content', 'wpautop' );
        remove_filter( 'the_excerpt', 'wpautop' );
    }
}
add_action( 'wp_head', 'remove_p_on_pages' );

4.10 Remove p tags from category description

remove_filter('term_description','wpautop');

4.11 Remove p tags around image

Picked this one up from

// Remove p tags around image
function filter_ptags_on_images($content){
   return preg_replace('https://cdn.css-tricks.com/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

add_filter('the_content', 'filter_ptags_on_images');

4.12 Limit post/page title length

Code snippet from to limit the title length (change from 30 to anything you want) by calling it inbetween PHP brackets like this: short_title(30);

// Limit post/page title length
function short_title($n) {
    $title = get_the_title($post->ID);
    $title = substr($title,0,$n);
    echo $title;
}

4.13 Disable srcset responsive images feature

We should be happy the srcset function has been added to WordPress. However, I have come across situations where for some reasons this function would stubbornly keep on loading very small versions of the image, rendering them in large, unsharp versions. In those cases, this code snippet has been a life-saver! Let me know please, if you know how the srcset issue can be solved without using this snippet, which would obviously be preferable.

// disable srcset responsive images feature
// enable in case of issues with image sharpness
function disable_srcset( $sources ) {
	return false;
}
add_filter( 'wp_calculate_image_srcset', 'disable_srcset' );

4.14 Force pagination beyond page 1 when category base is filtered out

If you are filtering out the category base from your URL’s (wich is an option in, for instance, the ), pagination will cease to work beyond page 1, but instead will generate 404 errors. This snippet from offers a nice solution for that!

// force pagination to work beyond page 1 when the category base is filtered out of the URL's
add_filter( 'category_rewrite_rules', 'vipx_filter_category_rewrite_rules' );
function vipx_filter_category_rewrite_rules( $rules ) {
    $categories = get_categories( array( 'hide_empty' => false ) );

    if ( is_array( $categories ) && ! empty( $categories ) ) {
        $slugs = array();
        foreach ( $categories as $category ) {
            if ( is_object( $category ) && ! is_wp_error( $category ) ) {
                if ( 0 == $category->category_parent ) {
                    $slugs[] = $category->slug;
                } else {
                    $slugs[] = trim( get_category_parents( $category->term_id, false, '/', true ), '/' );
                }
            }
        }

        if ( ! empty( $slugs ) ) {
            $rules = array();

            foreach ( $slugs as $slug ) {
                $rules[ '(' . $slug . ')/feed/(feed|rdf|rss|rss2|atom)?/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
                $rules[ '(' . $slug . ')/(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
                $rules[ '(' . $slug . ')(/page/(\d)+/?)?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[3]';
            }
        }
    }
    return $rules;
}   

4.15 Put post thumbnails into the RSS feed

Make your RSS feed look a lot better by adding post thumbnails. Code snippet from

// Put post thumbnails into rss feed
function wpfme_feed_post_thumbnail($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '' . $content;
    }
    return $content;
}
add_filter('the_excerpt_rss', 'wpfme_feed_post_thumbnail');
add_filter('the_content_feed', 'wpfme_feed_post_thumbnail');

4.16 Add Social media sharing buttons

Social media plugins have one thing in common: they often incurr a lot of scripts and stylesheets, and offer a large range of options. If all you need is a few buttons to enable your visitors to share your page or post, this snippet from suits the bill perfectly! It contains sharing links to Twitter, Facebook, Google Plus, Whatsapp, LinkedIn and Pinterest.

// Social media sharing buttons
function crunchify_social_sharing_buttons($content) {
    global $post;
    if(is_singular() || is_home()){
    
        // Get current page URL 
        $crunchifyURL = urlencode(get_permalink());
 
        // Get current page title
        $crunchifyTitle = str_replace( ' ', '%20', get_the_title());
        
        // Get Post Thumbnail for pinterest
        $crunchifyThumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
 
        // Construct sharing URL without using any script
        $twitterURL = 'https://twitter.com/intent/tweet?text='.$crunchifyTitle.'&amp;url='.$crunchifyURL.'&amp;via=Crunchify';
        $facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$crunchifyURL;
        $googleURL = 'https://plus.google.com/share?url='.$crunchifyURL;
        $whatsappURL = 'whatsapp://send?text='.$crunchifyTitle . ' ' . $crunchifyURL;
        $linkedInURL = 'https://www.linkedin.com/shareArticle?mini=true&url='.$crunchifyURL.'&amp;title='.$crunchifyTitle;
 
        // Based on popular demand added Pinterest too
        $pinterestURL = 'https://pinterest.com/pin/create/button/?url='.$crunchifyURL.'&amp;media='.$crunchifyThumbnail[0].'&amp;description='.$crunchifyTitle;
 
        // Add sharing button at the end of page/page content
        $content .= '<!-- Crunchify.com social sharing. Get your copy here: http://crunchify.me/1VIxAsz -->';
        $content .= '<div class="crunchify-social">';
        $content .= '<a class="crunchify-link crunchify-facebook icon-Facebook-2" href="'.$facebookURL.'" target="_blank" title="Share on Facebook"></a>';
        $content .= '<a class="crunchify-link crunchify-linkedin icon-Linkedin" href="'.$linkedInURL.'" target="_blank" title="Share on LinkedIn"></a>';        
        $content .= '<a class="crunchify-link crunchify-twitter icon-Twitter" href="'. $twitterURL .'" target="_blank" title="Share on Twitter"></a>';
        $content .= '<a class="crunchify-link crunchify-googleplus icon-Google-Plus" href="'.$googleURL.'" target="_blank" title="Share on Google+"></a>';
        $content .= '<a class="crunchify-link crunchify-whatsapp icon-whatsapp" href="'.$whatsappURL.'" target="_blank" title="Share with Whatsapp"></a>';
        $content .= '<a class="crunchify-link crunchify-pinterest icon-Pinterest" href="'.$pinterestURL.'" data-pin-custom="true" target="_blank" title="Pin it!"></a>';
        $content .= '</div>';
        
        return $content;
    }else{
        // if not a post/page then don't include sharing button
        return $content;
    }
};
add_filter( 'the_content', 'crunchify_social_sharing_buttons');

4.17 Show list of all tags anywhere

To show a full list of all tags on the website.

$tags = get_tags();
$html = '<ul>';
foreach ( $tags as $tag ) {
	if($tag->slug != "migliori"){
		$tag_link = get_tag_link( $tag->term_id );
		$html .= "<li><a href='{$tag_link}' class='{$tag->slug}'>";
		$html .= "{$tag->name}</a></li>";
       }
}
$html .= '</ul>';
echo $html; 

5.00 Performance snippets

5.01 Caching downloaded files

For caching, I would generally advise to use a good caching plugin, such as . But there are some caching functions you can implement yourself easily, such as this snippet from , which caches downloaded files.

/**
* Downloads a URL, or returns it from the cache
* The function tries to act intelligently:
*   (1) The file will be cached for the time specified in $cache_time, which defaults to the time given by the 'Cache-control:' header.
*   (2) If cache-control time is overridden, the 'cache-control' and 'expires' headers will be modified before being returned/cached, so that you can easily output appropriate headers if you need to.
* @param string $url - the URL to be downloaded or returned
* @param integer $suggested_cache_time - the time to cache the file for (in seconds). If the time given by the 'Cache-control:' header is longer, this value will be overridden. If no time is provided by this variable or by the header, then the time will be set to 1 day
* @param boolean $also_return_headers
* @return mixed - if an error occurs, returns WP_ERROR. Otherwise, if $also_return_headers is true, returns an array with the keys 'body', 'headers', 'response' and 'cookies', otherwise returns the body as a string. See the documentation for wp_remote_get for examples.
*/
function emw_get_cached_url ($url, $suggested_cache_time = 0, $also_return_headers = false) {
    $name = 'egcu-'.md5($url); // A short, unique name for the file to be cached
    // Return from the cache if possible
    if ($item = get_transient ($name)) {
        $v = unserialize(base64_decode($item));
        if ($also_return_headers)
            return unserialize(base64_decode($item));
        else
            return $v['body'];
    } else {
        // Download the file
        $download = wp_remote_get ($url, array ('timeout' => 30, 'sslverify' => false));
        // Check for error
        if (is_wp_error ($download))
            return $download;
        else {
            // Calculate the cache time from the headers
            $actual_cache_time = $suggested_cache_time;
            if (isset($download['headers']['cache-control']) && ($start = strpos($download['headers']['cache-control'], 'max-age=')+8) !== FALSE) {
                $headers_cache_time = substr($download['headers']['cache-control'], $start);
                if (($a = strpos($headers_cache_time, ',')) !== FALSE)
                    $headers_cache_time = substr($headers_cache_time, 0, $a);
                if ($headers_cache_time > $suggested_cache_time)
                    $actual_cache_time = $headers_cache_time;
            }
            // If no cache time is specified in the headers or the $suggested_cache_time variable, set the cache to 1 day
            if ($actual_cache_time == 0)
                $actual_cache_time = 86400;
            // Modify the headers to take account of the new cache time
            if (!isset($download['headers']['date']))
                $download['headers']['date'] = gmdate('D, d M Y H:i:s \G\M\T', $t = time());
            $download['headers']['cache-control'] = "public, max-age=".round($actual_cache_time*1.01);  // Multiplying by 1.01 ensures the browser will cache the file for slightly longer than the server. This ensures that by the time the browser requests the file again, it will have definitely been refreshed.
            $download['headers']['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $t+(round($actual_cache_time*1.01)));
            // Cache the download
            set_transient ($name, base64_encode(serialize($download)), $actual_cache_time);
            // Return what was requested
            if ($also_return_headers)
                return $download;
            else
                return $download['body'];
        }
    }
}

6.00 SEO snippets

6.01 Add itemprop image markup to img tags

Very handy code snippet by , which adds itemprop image markup to all img tags automatically. Smart to comply with Google’s rules.
The second part is my own adapation to apply the same principle to links.

// Add itemprop image markup to img tags
add_filter('the_content', 'vmf_add_itemprop_image_markup', 2);
function vmf_add_itemprop_image_markup($content)
{
    //Replace the instance with the itemprop image markup.
    $string = '<img';
    $replace = '<img itemprop="image"';
    $content = str_replace( $string, $replace, $content );
    return $content;
}

6.02 Add itemprop url markup to links

My own adaption of ‘s code, to add the “url” itemprop to each link.

add_filter('the_content', 'add_itemprop_url_markup', 2);
function add_itemprop_url_markup($content)
{
    //Replace the instance with the itemprop image markup.
    $string = '<a';
    $replace = '<a itemprop="url"';
    $content = str_replace( $string, $replace, $content );
    return $content;
}

6.03 Add itemprop url markup to links, except on AMP pages

AMP pages have their own set of restrictions when it comes to tag properties, sometimes resulting in errors in Google Search Console.
If, for example, you want to add itemprop=”url” to all links on all pages, but not on AMP pages, adjust the script as below:

function add_itemprop_url_markup($content)
{
    //Replace the instance with the itemprop image markup.
    $string = '<a';
    $replace = '<a itemprop="url"';
    $content = str_replace( $string, $replace, $content );
    return $content;
}

// But do not at the itemprop on /amp/ pages
if (strpos($_SERVER['REQUEST_URI'], "/amp/") == false){
    add_filter('the_content', 'add_itemprop_url_markup', 2);
}

7.00 Plugin-related snippets

7.01 Remove WooCommerce featured image from gallery

Maybe you just don’t want to use the featured product image displayed on the shop pages in the image gallery of the product page. This snippet from shows you how to remove it (add to functions.php in your theme):

add_filter('woocommerce_single_product_image_thumbnail_html', 'remove_featured_image', 10, 2);
function remove_featured_image($html, $attachment_id ) {
    global $post, $product;

    $featured_image = get_post_thumbnail_id( $post->ID );

    if ( $attachment_id == $featured_image )
        $html = '';

    return $html;
}

7.02 Optimize WooCommerce scripts

/**
 * Remove WooCommerce Generator tag, styles, and scripts from non WooCommerce pages.
 */
add_action( 'wp_enqueue_scripts', 'child_manage_woocommerce_styles', 99 );
 
function child_manage_woocommerce_styles() {
  //remove generator meta tag
  remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
 
  //first check that woo exists to prevent fatal errors
  if ( function_exists( 'is_woocommerce' ) ) {
    //dequeue scripts and styles
    if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
      wp_dequeue_style( 'woocommerce_frontend_styles' );
      wp_dequeue_style( 'woocommerce_fancybox_styles' );
      wp_dequeue_style( 'woocommerce_chosen_styles' );
      wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
      wp_dequeue_script( 'wc_price_slider' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-add-to-cart' );
      wp_dequeue_script( 'wc-cart-fragments' );
      wp_dequeue_script( 'wc-checkout' );
      wp_dequeue_script( 'wc-add-to-cart-variation' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-cart' );
      wp_dequeue_script( 'wc-chosen' );
      wp_dequeue_script( 'woocommerce' );
      wp_dequeue_script( 'prettyPhoto' );
      wp_dequeue_script( 'prettyPhoto-init' );
      wp_dequeue_script( 'jquery-blockui' );
      wp_dequeue_script( 'jquery-placeholder' );
      wp_dequeue_script( 'fancybox' );
      wp_dequeue_script( 'jqueryui' );
    }
  }
}

7.03 Load ContactForm 7 scripts and SCSS only on a specific page

I like to load scripts and stylesheets only where they are actually used. Disabling scripts and stylesheets for certain pages is not always so straightforward, as it is dependent on how clear the plugin author’s code is written. The CF7 author has made this very easy for us.

// Load ContactForm7 scripts & CSS only on page called "Contact"
add_action( 'wp_print_scripts', 'my_deregister_CF7_javascript', 100 );
function my_deregister_CF7_javascript() {
  if ( !is_page('CONTACT') ) {
    wp_deregister_script( 'contact-form-7' );
  }
}

add_action( 'wp_print_styles', 'my_deregister_CF7_styles', 100 );
function my_deregister_CF7_styles() {
  if ( !is_page('CONTACT') ) {
    wp_deregister_style( 'contact-form-7' );
  }
}

7.04 Load ContactForm 7 scripts and SCSS only on a specific pages

If you are using CF7 on more than one page, you will ned to make an array of the page ID’s. In this example, CF7 is loaded only on the pages with ID’s 8 and 10. Another nice snippet from .

// Same as above, but for multiple pages (from wpsnipp.com)
// Load CF7 scripts & CSS only on page id's mentioned in array
add_action( 'wp_print_scripts', 'deregister_cf7_javascript', 100 );
function deregister_cf7_javascript() {
    if ( !is_page(array(8,10)) ) {
        wp_deregister_script( 'contact-form-7' );
    }
}
add_action( 'wp_print_styles', 'deregister_cf7_styles', 100 );
function deregister_cf7_styles() {
    if ( !is_page(array(8,10)) ) {
        wp_deregister_style( 'contact-form-7' );
    }
}

7.05 Force Meta Slider plugin to use SSL

is a very popular slideshow plugin, and with good reason. It’s simple to configure and manage, even for users without technical knowledge. Unfortunately, it does not comply with SSL out of the box (probably will be in a near-future update). Until then, you can add this snippet.

// Force Meta Slider plugin to use SSL
function metaslider_protocol_relative_urls($cropped_url, $orig_url) {
    return str_replace('http://', '//', $cropped_url);
}
//add_filter('metaslider_resized_image_url', 'metaslider_protocol_relative_urls', 10, 2);

7.06 Bring back “Custom Fields” block to page editor when using Advanced Custom Fields

ACF removes “Custom Fields” block from page editing view. This brings it back. Required for setting the disable autop setting on some pages.

// source: https://wpbeaches.com/wordpress-custom-fields-missing-acf-active/
add_filter('acf/settings/remove_wp_meta_box', '__return_false');

// Run do shortcode on all textarea values
function my_acf_format_value( $value, $post_id, $field ) {
    
    // run do_shortcode on all textarea values
    $value = do_shortcode($value);
    
    // return
    return $value;
}

add_filter('acf/format_value/type=textarea', 'my_acf_format_value', 10, 3);

7.07 Allow ACF repeater fields to be indexed by the Ajax Search Pro plugin

add_filter('asp_index_cf_contents_before_tokenize', 'asp_post_content_before_add_acf_relationship', 10, 2);
function asp_post_content_before_add_acf_relationship($content, $post) {
    $field_names = 'dagelijks, rvt, contact_adres, contact_telefoon, contact_mobiel, links_alg, links_rc'; // Comma separated list of field names
    $index_title = true;      // To index the related post title
    $index_content = true;    // To index the related post content

    if ( function_exists('get_field') ) {
       $fn_arr = explode(',', $field_names);
       foreach ($fn_array as $field_name) {
           $field_name = trim($field_name);
           if ( empty($field_name) )
               continue;
           $items = get_field($field_name, $post->ID);
           if ( is_array($items) ) {
               foreach ($items as $item) {
                  if ( isset($item->ID) ) {
                      if ( $index_title ) {
                          $content .= ' ' . get_the_title($item->ID);
                      }
                      if ( $index_content ) {
                          $content .= ' ' . apply_filters('the_content', get_post_field('post_content', $item->ID));
                      }
                  } else if ( is_array($item) || is_string($item) ) {
                    $content .= ' ' . wd_array_to_string($item);
                  }
               }
           } else if ( is_string($items) ) {
               $content .= ' ' . $items;
           }
       }
    }
    return $content;
}

Be sure to check back, as I will continue to add new snippets!


foto Boris Hoekmeijer
My name is Boris Hoekmeijer, I'm a webdesigner and graphic designer.
I sometimes run into a problem for which I have to find my own solution because Google just won't tell me. That's when I climb behind my mechanical keyboard, and fire away until a tutorial materializes. One of the great things about the web: we can all help each other!
If this article has helped you, or if you have anything to add or ask, please leave a comment or share the post.
Cheers!

© 2017 ★ Published: July 9, 2017
7 Comments

  • Rodney says:

    Hello my friend,I have a website in 2 languaje,1 website for each languaje, I already add a languaje icon with link to the respective languaje version, the issue is that all the links in each page have the same link(the home url of each version) I would to have the respective link to each page, per example, the about us page with the languaje icon linked to her respective page(not home page), the contact page to the contacto page (the 2 languajes are english and spanish) which will be the snippet for fix this.. Thanks

    • Boris Hoekmeijer says:

      Hi Rodney,
      I have no idea. It totally depends on the way the website is set up to translate. Is it manual? WPML? Some other plugin? I can tell you this: if the pages were translated manually (i.e. WordPress does not know there are multiple languages on the website), there is no way except to hard-code. If you’re using WPML, this is automatic behaviour. If you’re using another translation plugin I cannot help you as I’m not familiar with them.

  • Boris Hoekmeijer says:

    Added “Allow SVG’s in Media Library through uploader”.

  • Boris Hoekmeijer says:

    Added “Add itemprop url markup to links, except on AMP pages” snippet.

  • Boris Hoekmeijer says:

    Added “Remove WooCommerce featured image from gallery” snippet.

  • Michael Polombo says:

    Dear Boris,
    can you help me. I am looking actually for two generated shortcodes.
    1. Show any Page title from ID
    2. Display and Category title from ID
    3. Category list (no posts, parent and child categories) from ID
    I do not want to do it by plugins, better to use php code and generate the shortcodes from there.
    Can you help here ?
    Thank you so much.
    – Michael

    • Boris Hoekmeijer says:

      Hi Michael,

      I’ve searched a bit, and found these:
      Get page title by ID

      <?php echo get_the_title(post->$ID); ?> 
      

      Get category name by ID

      <?php get_cat_name( $cat_id ) ?>
      

      or:
      Get category name by ID

      function get_the_category_by_ID( $cat_ID ) {
          $cat_ID = (int) $cat_ID;
          $category = get_term( $cat_ID, 'category' );
       
          if ( is_wp_error( $category ) )
              return $category;
       
          return ( $category ) ? $category->name : '';
      }
      

      The third one you’re looking for I don’t understand. What list are you looking for, without posts, parent and child categories?

Leave a Reply

Your email address will not be published. Required fields are marked *