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

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

Check if this is the home page

1<?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.

1remove_action('wp_head', 'wp_generator');

 

Enable post and comment RSS feed links to head

1add_theme_support( 'automatic-feed-links' );

 

Contents and Excerpts

Set the default excerpt length (in number of words)

1function my_excerpt_length($length) {
2    return 20; // number of words
3}
4
5add_filter( 'excerpt_length', 'my_excerpt_length', 100 );

 

Add a ShortCode that doesn’t require attributes

1function get_my_shortcut() {
2    global $post;
3    return "This is My Shortcut"; // you can add extra HTML here
4}
5
6add_shortcode('my_shortcut', 'get_my_shortcut');

How to use it:

1[my_shortcut]

 

Add a ShortCode that uses attributes

 1function get_my_shortcut($atts) {
 2    global $post;
 3
 4    // get the attributes
 5    extract(shortcode_atts(array(
 6    'attribute1' => '1', // '1' is the default value for this attribute
 7    'attribute2' => '2'), $atts));
 8
 9    return "Some values here: <strong>".$attribute1." and ".$attribute2."</strong>";
10}
11
12add_shortcode('my_shortcut', 'get_my_shortcut');

How to use it:

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

 

Add a shortcut that has text

1function quote($atts, $content = null) {
2    if (empty($content)) {
3        return "You are awesome!";
4    }
5    else return $content;
6}
7
8add_shortcode('quote', 'quote');

How to use it:

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

 

 1function my_widgets_init() {
 2
 3    register_sidebar( array(
 4        'name' => 'Footer Sidebar 1',
 5        'id' => 'footer-sidebar-1',
 6        'description' => 'Appears in the left footer area',
 7        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
 8        'after_widget' => '</aside>',
 9        'before_title' => '<h3>',
10        'after_title' => '</h3>'
11    ) );
12
13}
14
15add_action('widgets_init', 'my_widgets_init');

Somewhere in your HTML:

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

 

Register a “Menu” for your theme.

You can place a menu anywhere in your HTML.

1function register_my_main_menu() {
2    register_nav_menu('main-menu', __( 'Main Menu' ));
3}
4
5add_action('init', 'register_my_main_menu');

Somewhere in your HTML:

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

 

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

1function my_active_menu_item($classes) {
2    if(in_array('current-menu-item', $classes)) {
3        $classes[] = 'active'; // Add your CSS class
4    }
5    return $classes;
6}
7
8add_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.

1add_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.

1add_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.

1function my_image_sizes( $sizes ) {
2    return array_merge( $sizes, array(
3        'homepage-blog-thumb' => __('Home Page Blog Thumb'),
4    ) );
5}
6
7add_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/

 1function get_random_gallery_images() {
 2    global $wpdb,$post;
 3    $ids = "";
 4    $counter = 0;
 5    $number_of_posts = 4; // change this to limit the number of thumbnails
 6
 7    $args = array(
 8        'post_type' => 'attachment',
 9        'numberposts' => 4,
10        'post_status' => null,
11        'orderby' => 'rand',
12        'post_parent' => $post->ID
13    );
14
15    $attachments = get_posts($args);
16    if ($attachments) {
17        foreach ($attachments as $attachment) {
18            if ($counter != 0) {
19                $ids .= ','.$attachment->ID;
20            }
21            else {
22                $ids .= $attachment->ID;
23            }
24            $counter++;
25        }
26    }
27
28    return $ids;
29}
30
31$attachment_ids = get_random_gallery_images();
32echo do_shortcode('[gallery columns="4" include="'.$attachment_ids.'"]');

 

Administration

 

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

 1function my_column_header($defaults) {
 2    $defaults['product_key'] = __('Code'); // the column name
 3    return $defaults;
 4}
 5
 6function my_column_contents($column_name, $post_id) {
 7    if ($column_name == 'product_key') {
 8        $product_key = get_post_meta($post_id, 'Code', true); // Read the custom 'Code' field
 9        echo $product_key; // this line may include extra HTML
10    }
11}
12
13add_filter('manage_posts_columns', 'my_column_header');
14add_action('manage_posts_custom_column', 'my_column_contents', 10, 2);

 

 1function my_column_header($defaults){
 2    $defaults['the_post_thumbs'] = __('Thumbs'); // the column name
 3    return $defaults;
 4}
 5
 6function my_column_contents($column_name, $post_id){
 7    if ($column_name === 'the_post_thumbs') {
 8        echo the_post_thumbnail( array(64, 64) ); // select the image size
 9    }
10}
11
12add_filter('manage_posts_columns', 'my_column_header');
13add_action('manage_posts_custom_column', 'my_column_contents', 10, 2);

 

Plugins & Widgets

Basic plugin structure

 1<?php
 2/*
 3 * Plugin Name: My Plugin's Name
 4 * Description: My Plugin's Description
 5 * author: Andres Jaimes Jaimes
 6 * Author URI: https://andres.jaimes.net/
 7 * Version: 1.0
 8 * License: Choose a license.
 9*/
10
11function my_plugin_contents($content) {
12    return $content . '<p>My Plugin's Content.</p>';
13}
14
15add_filter('the_content', 'my_plugin_contents');

 

Basic Widget Structure

 1<?php
 2/*
 3 * Plugin Name: My Plugin's Name
 4 * Description: My Plugin's Description.
 5 * author: Andres Jaimes Jaimes
 6 * Author URI: https://andres.jaimes.net/
 7 * Version: 1.0
 8 * License: Choose a license.
 9*/
10
11class MyPlugin extends WP_Widget {
12
13    // constructor
14    function MyPlugin() {
15        parent::WP_Widget(false, $name = 'Plugin's Name',
16            array('description' => 'This is my wonderful plugin.'),
17            array('width' => '400px')
18        );
19    }
20
21    // widget form creation: what you see when you add a widget to a section in Appearance > Widgets
22    function form($instance) {
23        $defaults = array(
24            'title' => '',
25            'anumber' => 5,
26            'amessage' => ''
27        );
28        $values = wp_parse_args( $instance, $defaults ); ?>
29        <p>
30            <label for='<?php echo $this->get_field_id( 'title' ); ?>>
31            <?php _e( 'Title:', 'mytextdomain' ); ?>
32            <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']; ?>' />
33            </label>
34        </p>
35
36        <p>
37            <label for='<?php echo $this->get_field_id( 'anumber' ); ?>'>
38            <?php _e( 'Type a Number:', 'mytextdomain' ); ?>
39            <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']; ?>' />
40            </label>
41        </p>
42
43        <p>
44            <label for='<?php echo $this->get_field_id( 'amessage' ); ?>'>
45            <?php _e( 'Type a Message:', 'mytextdomain' ); ?>
46            <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']; ?>' />
47            </label>
48        </p><?php
49    }
50
51    // widget update: a chance to perform validations after you click Save when in Appearance > Widgets
52    function update($new_instance, $old_instance) {
53        return $new_instance;
54    }
55
56    // widget display: the way a final user will see your widget in your running website
57    function widget($args, $instance) {
58        echo $args['before_widget'];
59        echo $args['before_title'] . $instance['title'] . $args['after_title'];
60        echo '<div>You typed a number: '.$instance['anumber'].'and a message: '.$instance['amessage'].'</div>';
61        echo $args['after_widget'];
62    }
63
64} // End of class
65
66// register widget
67add_action('widgets_init',
68    create_function('', 'return register_widget("MyPlugin");'));
69
70?>

 

I’ll keep adding snippets to this page.

Please share it if you find useful.