New theme in development and is currently live on BuddyCore.com - Please check back often for updates (11/12/16).

Tutorials · WordPress

Create a Sticky Posts Template

·

1) Rewrite Rule

We’re going to set a rewrite rule, this is slightly optional in our sticky posts template however it’s useful to know this function is available to you and becomes even more useful when Custom Post Types are used in which there may be further requirements of the url structure in your WordPress powered website.

So, we need a wrapper function and a hook in order to make a rewrite rule “stick” as it were.

function sc_sticky_rewrite_rule() {
    
}
add_action('init', 'sc_sticky_rewrite_rule');

The function above runs when the “init” hook is made available, in other words when WordPress has loaded the required files.

Now we’re going to add the rewrite rule, which in turn is executed after WordPress files are available. Makes sense, doesn’t it?

function sc_sticky_rewrite_rule() {
    add_rewrite_rule('sticky', 'index.php?sticky=$matches[1]', 'top');
}
add_action('init', 'sc_sticky_rewrite_rule');

The $matches[] array is returned in PHP when we use a regular expression (which, somewhere down the line add_rewrite_rule() most certainly does, we can search this array starting at the index of 1. We’ll have an all-be-it general but still required value here, e.g. http://site.com/?sticky=true which could later be utilised for sticky posts in a particular custom taxonomy e.g. http://site.com/?sticky=true&cpt=games

Register Query Variables

We’re going to make a particular query string available to get_query_var(), a WordPress function which keeps things tidy. We could simply use PHPs $_GET super global to retrieve the required query string values but let’s keep it the WordPress way for now and think about future-proofing the build.

function sc_set_query_vars($vars) {
    $vars[] = 'sticky';
    return $vars;
}
add_action('query_vars', 'sc_set_query_vars');

Above we’re using add_action() again, we could also use add_filter() which makes more laymans sense, but essentially these functions do the same thing.

Using query_vars as our hook, the sc_set_query_vars() function is executed. Our function takes its $vars parameters from the hook query_vars and simply defines another value (“sticky”) then returns an updated array.

To see what’s going on in this function we could do the following;

function sc_set_query_vars($vars) {
    print_r($vars);
    $vars[] = 'sticky';
    print_r($vars);
    return $vars;
}

Looking at the output rendered on the front-end, there are 49 values in the first print_r() and 50 with the second. The second now has the “sticky” value defined earlier.

2) Assign a Template File

Next we’ll include a template file to be used for rendering the sticky posts when the query string is matched. We’ll include all of the code above in the theme functions.php file or abstract it further for organisational reasons, it’s your choice.

We’ll need another hook and call back function so let’s prepare that;

function sc_sticky_template() {

}
add_action('template_redirect', 'sc_sticky_template');

template_redirect is the hook we’re looking for here, it runs just before WordPress has defined its template hierarchy. Since we’re adding a custom template it makes good sense to do it at this stage but let’s make sure we only add it when a request comes through for “sticky”.

function sc_sticky_template() {
    if(get_query_var('sticky')) :
        
    endif;
}
add_action('template_redirect', 'sc_sticky_template');

Query vars are used to build a particular query in WordPress, there are two types of queries – Public and Private. Public are those available to the query string, and Private are those that are available to the query string but being used in-line with a custom query to render results.

We added “sticky” to the query_vars hook and whenever this is now requested publicly (or privately?) we can handle the request articulately.

I digress, let’s add our template in now;

function sc_sticky_template() {
    if(get_query_var('sticky')) :
        add_action('template_include', function() {
            return locate_template('page-templates/page-template-sticky.php');
        });
    endif;
}
add_action('template_redirect', 'sc_sticky_template');

We’re using a closure function this time round when looking for the template_include hook, as of PHP 5.4 this syntax is available to us.

With locate_template working from our theme root we pass the relative path to the file we wish to use as our template. It’s a good practice to keep your WordPress template files in a folder called “page-templates”. We use the default parameters for locate_template() which is to simply require this template one time only.

3) Rendered Template File

Finally, we need to present the sticky posts. We’ve come a long way for such a small requirement.

$stickies = get_option('sticky_posts');

get_option() allows us to retrieve a specific option from the ‘options’ table in WordPress. We know that this option has a serialized array of values associated with it if posts have been marked as sticky. This is exactly what we need, and will allow us to build a query searching for specific post IDs in conjunction with with a custom WP_Query().

$stickies = get_option('sticky_posts');
$args = array(
    'posts_per_page'    => -1,
    'post__in'          => $stickies 
);
$sc_query = new WP_Query($args);

Provided there are sticky values, the query above will return the results as an object which we can iterate over in an atypical fashion and display our sticky posts.

The final file will look something like below, inside the loop you can make use of all the usual WordPress template tags found in the Codex such as the_title() and the_content().

$stickies = get_option('sticky_posts');
$args = array(
    'posts_per_page'    => -1,
    'post__in'          => $stickies 
);
$sc_query = new WP_Query($args);

if($sc_query->have_posts()) : while($sc_query->have_posts()) : $sc_query->the_post();
// Your post layout
endwhile; else :
// No posts found
endif;

That’s it, we’re now loading the custom template on demand without nesting conditional logic to retrieve specific files. If you decided to opt for the latter option read on to the TLDR.

4) TLDR

This part of the tutorial can work in a stand-alone fashion and you could utilise this file by assigning it to a page in WP-Admin.

Create a new file, let’s say “sticky-posts-template.php” and place it inside a “page-templates” folder in your theme.

Inside that file add the following on the first line of the file.

/* TEMPLATE NAME: Sticky posts */

Now place your WordPress loop with the custom query as outlined in the section Rendered Template File above and make sure you call both get_header() and get_footer() in this file also.

Once created, navigate to your WP-Admin and create a new page then assign this newly created template to the page.

Last but not least, go ahead and make sure you have some posts marked as “sticky” and view that page on the front-end. You should see a list of sticky posts.

Leave a Reply

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

Loading more content...
Minimum Requirements

Your device does not meet the minimum requirements to view this site, please considering increasing your device width to more than 300px.