avatar

Andres Jaimes

WordPress Snippets

By Andres Jaimes

As a WordPress developer I have collected / created / curated many snippets that I’ve used in my projects. I hope you find them useful.

 

General HTML / WordPress tags

Get your template’s directory

<link href="<?php echo get_template_directory_uri(); ?>/style.css" rel="stylesheet" media="screen">

Check if this is the home page

<?php if (is_home()) { ... } ?>

 

Remove the wp_generator tag in the Head section of your HTML

I recommend you to add this line for security reasons.

remove_action('wp_head', 'wp_generator');

 

Enable post and comment RSS feed links to head

add_theme_support( 'automatic-feed-links' );

 

Contents and Excerpts

Set the default excerpt length (in number of words)

function my_excerpt_length($length) {
    return 20; // number of words
}

add_filter( 'excerpt_length', 'my_excerpt_length', 100 );

 

Add a ShortCode that doesn’t require attributes

function get_my_shortcut() {
    global $post;
    return "This is My Shortcut"; // you can add extra HTML here
}

add_shortcode('my_shortcut', 'get_my_shortcut');

How to use it:

[my_shortcut]

 

Add a ShortCode that uses attributes

function get_my_shortcut($atts) {
    global $post;

    // get the attributes
    extract(shortcode_atts(array(
    'attribute1' => '1', // '1' is the default value for this attribute
    'attribute2' => '2'), $atts));

    return "Some values here: <strong>".$attribute1." and ".$attribute2."</strong>";
}

add_shortcode('my_shortcut', 'get_my_shortcut');

How to use it:

[my_shortcut attribute1="10" attribute2="20"]

 

Add a shortcut that has text

function quote($atts, $content = null) {
    if (empty($content)) {
        return "You are awesome!";
    }
    else return $content;
}

add_shortcode('quote', 'quote');

How to use it:

[quote]Have a great day![/quote]

 

function my_widgets_init() {

    register_sidebar( array(
        'name' => 'Footer Sidebar 1',
        'id' => 'footer-sidebar-1',
        'description' => 'Appears in the left footer area',
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => '</aside>',
        'before_title' => '<h3>',
        'after_title' => '</h3>'
    ) );

}

add_action('widgets_init', 'my_widgets_init');

Somewhere in your HTML:

<div class="col-md-4">
    <?php
    if(is_active_sidebar('footer-sidebar-1')) {
        dynamic_sidebar('footer-sidebar-1');
    }
    ?>
</div>

 

Register a “Menu” for your theme.

You can place a menu anywhere in your HTML.

function register_my_main_menu() {
    register_nav_menu('main-menu', __( 'Main Menu' ));
}

add_action('init', 'register_my_main_menu');

Somewhere in your HTML:

<div role="navigation">
    <?php wp_nav_menu( array( 
    'theme_location' => 'main-menu', 
    'menu_class' => 'nav navbar-nav', // Use your own CSS classes
    'container' => false ) ); ?> // Should it include an extra container?
</div>

 

Add a CSS class to the current item in a Navigation Menu

function my_active_menu_item($classes) {
    if(in_array('current-menu-item', $classes)) {
        $classes[] = 'active'; // Add your CSS class
    }
    return $classes;
}

add_filter('nav_menu_css_class', 'my_active_menu_item');

 

Images

Add Post Thumbnails support for a Theme

You have to add this line in order to enable the functions in this section.

add_theme_support( 'post-thumbnails' );

 

Register a new custom image size

WordPress will create a copy of the Featured Image with the specified dimensions when you upload a new image.

Important: this will not make it available in media menus, please check the following point.

add_image_size('homepage-blog-thumb', 400, 280, true);

Parameters are: image size name, width, height and ‘should crop?’. There are some predefined names you should not use. Check docs.

 

Make a custom sized image available for selection in media menus

Check previous points for this to work.

function my_image_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'homepage-blog-thumb' => __('Home Page Blog Thumb'),
    ) );
}

add_filter( 'image_size_names_choose', 'my_image_sizes' );

 

Sometimes you don’t want to show all the thumbnails in the loop. Maybe 2? Maybe 4?  This snippet will help you.

From: http://www.webgurus.biz/how-to-limit-wordpress-gallery-thumbnails-in-the-loop/

function get_random_gallery_images() {
    global $wpdb,$post;
    $ids = "";
    $counter = 0;
    $number_of_posts = 4; // change this to limit the number of thumbnails

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => 4,
        'post_status' => null,
        'orderby' => 'rand',
        'post_parent' => $post->ID
    );

    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            if ($counter != 0) {
                $ids .= ','.$attachment->ID;
            }
            else {
                $ids .= $attachment->ID;
            }
            $counter++;
        }
    }

    return $ids;
}

$attachment_ids = get_random_gallery_images();
echo do_shortcode('[gallery columns="4" include="'.$attachment_ids.'"]');

 

Administration

 

Add a custom column to show a Custom Field in the admin Posts list screen

function my_column_header($defaults) {
    $defaults['product_key'] = __('Code'); // the column name
    return $defaults;
}

function my_column_contents($column_name, $post_id) {
    if ($column_name == 'product_key') {
        $product_key = get_post_meta($post_id, 'Code', true); // Read the custom 'Code' field
        echo $product_key; // this line may include extra HTML
    }
}

add_filter('manage_posts_columns', 'my_column_header');
add_action('manage_posts_custom_column', 'my_column_contents', 10, 2);

 

function my_column_header($defaults){
    $defaults['the_post_thumbs'] = __('Thumbs'); // the column name
    return $defaults;
}

function my_column_contents($column_name, $post_id){
    if ($column_name === 'the_post_thumbs') {
        echo the_post_thumbnail( array(64, 64) ); // select the image size
    }
}

add_filter('manage_posts_columns', 'my_column_header');
add_action('manage_posts_custom_column', 'my_column_contents', 10, 2);

 

Plugins & Widgets

Basic plugin structure

<?php
/*
 * Plugin Name: My Plugin's Name
 * Description: My Plugin's Description
 * author: Andres Jaimes Jaimes
 * Author URI: https://andres.jaimes.net/
 * Version: 1.0
 * License: Choose a license.
*/

function my_plugin_contents($content) {
    return $content . '<p>My Plugin's Content.</p>';
}

add_filter('the_content', 'my_plugin_contents');

 

Basic Widget Structure

<?php
/*
 * Plugin Name: My Plugin's Name
 * Description: My Plugin's Description.
 * author: Andres Jaimes Jaimes
 * Author URI: https://andres.jaimes.net/
 * Version: 1.0
 * License: Choose a license.
*/

class MyPlugin extends WP_Widget {

    // constructor
    function MyPlugin() {
        parent::WP_Widget(false, $name = 'Plugin's Name',
            array('description' => 'This is my wonderful plugin.'),
            array('width' => '400px')
        );
    }

    // widget form creation: what you see when you add a widget to a section in Appearance > Widgets
    function form($instance) {
        $defaults = array(
            'title' => '',
            'anumber' => 5,
            'amessage' => ''
        );
        $values = wp_parse_args( $instance, $defaults ); ?>
        <p>
            <label for='<?php echo $this->get_field_id( 'title' ); ?>>
            <?php _e( 'Title:', 'mytextdomain' ); ?>
            <input class='widefat' id='<?php echo $this->get_field_id( 'title' ); ?>' name='<?php echo $this->get_field_name( 'title' ); ?>' type='text' value='<?php echo $values['title']; ?>' />
            </label>
        </p>

        <p>
            <label for='<?php echo $this->get_field_id( 'anumber' ); ?>'>
            <?php _e( 'Type a Number:', 'mytextdomain' ); ?>
            <input class='widefat' id='<?php echo $this->get_field_id( 'anumber' ); ?>' name='<?php echo $this->get_field_name( 'anumber' ); ?>' type='text' value='<?php echo $values['anumber']; ?>' />
            </label>
        </p>

        <p>
            <label for='<?php echo $this->get_field_id( 'amessage' ); ?>'>
            <?php _e( 'Type a Message:', 'mytextdomain' ); ?>
            <input class='widefat' id='<?php echo $this->get_field_id( 'amessage' ); ?>' name='<?php echo $this->get_field_name( 'amessage' ); ?>' type='text' value='<?php echo $values['amessage']; ?>' />
            </label>
        </p><?php
    }

    // widget update: a chance to perform validations after you click Save when in Appearance > Widgets
    function update($new_instance, $old_instance) {
        return $new_instance;
    }

    // widget display: the way a final user will see your widget in your running website
    function widget($args, $instance) {
        echo $args['before_widget'];
        echo $args['before_title'] . $instance['title'] . $args['after_title'];
        echo '<div>You typed a number: '.$instance['anumber'].'and a message: '.$instance['amessage'].'</div>';
        echo $args['after_widget'];
    }

} // End of class

// register widget
add_action('widgets_init',
    create_function('', 'return register_widget("MyPlugin");'));

?>

 

I’ll keep adding snippets to this page.

Please share it if you find useful.