Duane Blake

Front end developer

Useful snippets for working with templates in WordPress

There is a couple of pieces of code snippets which I find useful when working with templates inside WordPress. Here is a couple I use on a regular basis

Useful snippets for working with templates in WordPress

Showing a different message / template base if a user is logged into the site

if ( is_user_logged_in() ) {
    echo 'Please see the link below to download this months assets';
} else {
    echo 'Sign up to download this month assets';

What the code does above is uses the is_user_logged_in() function to checks if the current visitor is currently signed in. If so it displays a string text for the logged in user and another piece of text if they are not logged in.

More information on the is_user_logged_in() function – https://developer.wordpress.org/reference/functions/is_user_logged_in/

Display current template being used


function display_template_name() 
	global $template;
	echo basename($template);

add_action('wp_head', 'display_template_name');

This snippet is useful when working with a WordPress theme that you’ve not built yourself. If you want to know the name of the template which is currently being used this snippet of code displays the template name in the website header.

Create a custom templates


    Template Name: Full Width

The template name is used when building pages or custom post types. At the top of the template place the following above. Template name is for the name of the template. Then from within WordPress where you editing or creating a page you will see the option which will say template. Select the one just created.

Passing data to another template when using the get_template_part


get_template_part('template-parts/content', 'single', ['arbitrary_data' => ['showSidebar' => true]]);
        if ($args['arbitrary_data']['noSidebar']) {

When building WordPress themes they may be situations where you are using the get_template_part function you may need to pass a variable to the template for example you may want to show a sidebar based on the variable value. We do this by using the third parameter when using the get_template_part the third parameter set up an array and call it arbitrary_data then then assign a variable to the parameter.

When displaying the variable in the template use the following $args[‘arbitrary_data’][‘variableName’]. This will then add the variable to the template. For more information how the template works please see the code below.

Leave a comment

Your email address will not be published.