Developing WordPress Themes - Dynamic Content in Page

We might have a static page that we want show some dynamic content in. For example, we might want to display the six most recent blog posts on the 'News' page.

To get the most recent posts, we can use wp_get_recent_posts, or for more general uses, get_posts.

So we can create a new template specific for this page. But wouldn't it be great if we can insert into our page content on the GUI using the content editor?

Of course we cannot (and should not) put PHP code directly into our content; instead, we will utilize Shortcodes.

Shortcodes

WordPress 2.5 introduced the Shortcode API. Prior to this, to add dynamic content onto the page, you'd have to do it by editing / creating a new template.

Shortcodes are macros you can insert into the content section of your pages and post. By default, WordPress provides the following shortcodes:

  • [audio]
  • [caption]
  • [embed]
  • [gallery]
  • [playlist]
  • [video]

For example, if we want to embed a video (including a player) into the template, we can use the shortcode [video src="video-source.mp4"]

To test things out, you can get some sample videos from http://sample-videos.com/

Creating our own shortcode

If you're hosting your site on WordPress.com, WordPress.com provides you with the [display-posts] shortcode. But this is not available if you run your own installation.

So we need to create our own shortcode. It's simple! This is all that's required to create our own shortcode:

functions.php

function posts_func( $atts ){
    return "Here lies your posts";
}
add_shortcode( 'posts', 'posts_func' );

This will create the posts shortcode.

The functions.php file provides all the functions and hooks you'd need in your theme. It acts like a plugin that is specific to the theme. If the functions can apply to other themes, put the functions in a plugin instead.

Using Shortcodes

We can print Here lies your posts into our content by including [posts] inside our content (posts or pages).

Here are the latest posts:
[posts]

If you want to use your shortcodes inside your template, you must wrap them with the do_shortcode() function. and then echo the results.

<?php echo do_shortcode('[posts]') ?>

Shortcode Arguments

Shortcode can take arguments (or attributes). For example:

[posts posts_per_page=6]

And to deal with this new argument:

function return_posts( $atts ) {
    $posts_array = get_posts( $atts );

    $returnString = "<ul>";

    foreach ($posts_array as $post) {
        setup_postdata( $post );
        $returnString .= "<li><a href=" . $post->guid . ">" . $post->post_title . "</a></li>";
    }

    wp_reset_postdata();
    $returnString .= "</ul>";
    return $returnString;
}
add_shortcode( 'posts', 'return_posts' );

If we add this into our page, we can get the last 6 entries:

Default Values

We will use the shortcode_atts() method to provide default values. shortcode_atts() is similar to array_merge in PHP, or _.extend in lodash.

shortcode_atts( $defaults_array, $atts );

shortcode_atts() will replace any keys that exists in $defaults_array with the value found in $atts, but only if they key already exists in the $defaults_array array. So this:

$posts_array = get_posts( $atts );

Becomes:

$a = shortcode_atts( array(
    'posts_per_page' => 6,
    'orderby' => 'date',
    'order' => 'DESC'
), $atts );

$posts_array = get_posts( $a );

Lastly, we need to run the add_shortcode() methods after the init action; so we need to use a hook.

function register_shortcodes() {
    add_shortcode( 'posts', 'return_posts' );
}

add_action( 'init', 'register_shortcodes');

Now we can use the shortcode [posts] or [posts count=6] and they will both display 6 of the most recent posts.

For more uses for shortcodes, refer to the Shortcode API.

Altogether now:

function return_posts( $atts ) {
    $a = shortcode_atts( array(
        'posts_per_page' => 6,
        'orderby' => 'date',
        'order' => 'DESC'
    ), $atts );

    $posts_array = get_posts( $a );

    $returnString = "<ul>";

    foreach ($posts_array as $post) {
        setup_postdata( $post );
        $returnString .= "<li><a href=" . $post->guid . ">" . $post->post_title . "</a></li>";
    }

    wp_reset_postdata();
    $returnString .= "</ul>";
    return $returnString;
}
function register_shortcodes() {
    add_shortcode( 'posts', 'return_posts' );
}We can print `Here lies your posts` into our content by including `[posts]` inside our content.

Here are the latest posts:
[posts]


add_action( 'init', 'register_shortcodes');

Note on Hooks

The add_shortcode() function takes the name of the shortcode, and the function to run when the shortcode is used.

The add_action() function works with hooks. Hooks are like EventListener in JavaScript, where we wait for the init 'event', and when fired, will run the register_shortcodes function.

Output Buffering

If you have a lot of posts to return, or the markup for each post is substansive, you might want to consider making use of the Output Buffering Control functions such as ob_start() and ob_flush()

If you enjoyed this article, why not take a look at the rest of the series on Developing WordPress Themes!

comments powered by Disqus