Including a file in a WordPress template

If you want to call a file within a temple in WordPress, it is recommend to use get_template_part() instead of the PHP include() function. get_template_part() provides a simple mechanism for child themes to overload reusable sections of code in the theme.

Use get_template_part() to include a file in a template

Syntax

get_template_part( $slug, $name = null );

It first loads the template “{slug}-{name}.php” if $name is not empty. If $name is empty or the template “{slug}-{name}.php” does not exist, it loads “{slug}.php”. If “{slug}.php” still does not exist, no file will be included. Note you won’t get warnings if it fails to find any matching file.

Examples

Below example includes a navigation bar in the header.php template file.

get_template_part( 'template-parts/navigation/navigation', 'nav-bar' );

In the case of a child theme is being used, assuming that the parent theme is twentynineteen, and the child theme is twentynineteen-child, the code above includes the first existing file among these files in this priority:

  1. wp-content/themes/twentynineteen-child/template-parts/navigation/navigation/nav-bar.php
  2. wp-content/themes/twentynineteen/template-parts/navigation/navigation/nav-bar.php
  3. wp-content/themes/twentynineteen-child/template-parts/navigation/navigation/nav-bar.php
  4. wp-content/themes/twentynineteen/template-parts/navigation/navigation/nav-bar.php

Using include() to include a file in a template

If you still want to directly include a file using include_once() or require_once(), see below examples.

Example 1: Include a file from the parent theme

If a child theme is being used, get_template_directory() returns the absolute path of the parent theme.

require_once( get_template_directory() . '/inc/my-functions.php' );

Example 2: Include a file from the child theme

If a child theme is being used, get_stylesheet_directory() returns the absolute path of the child theme.

require_once( get_stylesheet_directory() . '/inc/my-functions.php' );

Parsing shortcodes in WordPress template files

To include a known shortcode in a custom page/post template file as part of the content, you need to use do_shortcode() :

echo do_shortcode( "[a-registered-shortcode-name]" );

The function do_shortcode() parses shortcodes with their registered hooks in the content and return the content with the parsed shortcodes output. Below example use do_shortcode() to parse multiple shortcodes in a piece of content.

echo do_shortcode( "<p>Shortcode example 1: ['shortcode-name1']</p><p>Shortcode example 2:['shortcode-name2']</p>" );

If you write the shortcode string in the article content just like you what you do in WordPress edit page, it will not be parsed.

<!-- The shortcode below is just a plain text in the page/post template -->
<p>
    ["a-registered-shortcode-name"]
</p>

When editing a page/post in WordPress, the shortcode string works because it will be processed by the the_content() in a template file when it is displayed. the_content() will call do_shortcode() to process the shortcodes inside the content.

Custom title tags in WordPress

How to change the meta title tag without a plugin in WordPress. It also gives an an example of adding category to the title tag for single post and page.

Custom the title tag with a filter

WordPress use get_document_title() to generate the content for the meta title tag. There are two filters to custom it. You may choose one for your purpose.

  • pre_get_document_title, this filter does not accept any parameters, it’s return value will be used as the title. If you want to completely control the title, this one will be your choice. It’s up to you to generate the title. Make sure you take care of all kinds of pages, like home, single post or page, 404, etc.
  • document_title_parts, an array of parts of the title has been generated, like “title”(page title) and “site”(site name). This filter can be used to further custom each part. Finally, each part in the array return by the filter will be joined together with a separator to form a complete title in get_document_title(). If you don’t need deep customization, this one will meet your needs.

What you do is simply define a filter of your chose, and put them in functions.php of your theme.

Change the title

function my_meta_title() {
    return 'My page title';
}
add_filter( 'pre_get_document_title', 'my_meta_title' );

Change the title parts

function change_title_part( $title ) {
    if ( array_key_exists(  $title ) ) {
        $title['title'] = "[$title['title']]"; // wrap title in "[]"
    }

    return $title;
}
add_filter( 'document_title_parts', 'change_title_part' );

Change separator in the title

You can also change the default separator in the title. Use document_title_separator filter to do it.

function change_title_separator( $separator ) {
    return '|';
}
add_filter( 'document_title_separator', 'change_title_separator' );

Example: Add category to the title tag

Below example adds category in the meta title tag for single post and page.

Add below code to your theme’s functions.php file

function add_category_to_meta_title( $title ) {
    if ( is_singular() ) {
        $new_title = array();

        if ( array_key_exists( 'title', $title ) ) {
            $new_title['title'] = $title['title'];
            unset( $title['title'] );
        }

        // add category
        $categories = get_the_category();
        if ( ! empty( $categories ) ) {
            $new_title['category'] = esc_html( $categories[0]->name );  
        }

        foreach( $title as $k => $v) {
            $new_title[$k] = $v;
        }

        return $new_title;
    }

    return $title;
}
add_filter( 'document_title_parts', 'add_category_to_meta_title' );

If you are using an SEO plugin, like Yoast, the above code may do not work for code conflictions. To solve that, define pre_get_document_title filter, so the above code will take effect.

function cust_document_title() {
    return '';
}
add_filter( 'pre_get_document_title', 'cust_document_title', 99 );

Conditional Headers, Sidebars and Footers

WordPress’s get_header() accepts a parameter to specify a specialized header to be included. Therefore, if you want to include headers according to conditions in a template file, simply pass a parameter specifying which header to be included to get_header() .

For example, below code includes header-home.php for the front page but normal header.php for the others in a template file.

if ( is_front_page() ) :
    get_header( 'home' );
else:
    get_header();
endif;

get_sidebar and get_footer() also accept such a parameter. They can be used to include a specialized sidebar or footer according to conditions.

Adding categories navigation to WordPress header

To show categories in the header part of your website, create a new division in the header where you want them to display.

Before you start, you’d better create a child theme to make customization instead of directly modifying a theme. Take the default “twentyseventeen” theme for example, add below code to file templates-parts/header/site-branding.php of the theme:

       <div id="category-list">
            <ul>
                <li><a title="Home Page" href="index.php">home</a></li>
                <?php wp_list_categories(array('title_li' => '', 'echo' => 1)); ?>
            </ul>
        </div><!-- .category-list -->

wp_list_categories is used to display the categories list. You can use many parameters to control its result, below are some of them:

  • title_li, text for the list title <li> element

  • echo, display markup marks.

  • separator, separator between links.
  • exclude, array of strings to exclude.

Add below code in style.css to style the categories:

/* category list in header */
#category-list {
    margin: 0;
    display: inline-block;
    float: right;
    vertical-align: middle;
    font-size: 14px;
    font-style: normal;
    text-transform: capitalize;
}
#category-list li {
    display: inline;
    list-style-type: none;
    padding: 0px 5px;
}
#category-list a:link, #category-list a:visited {
    color: #eee;
}
#category-list a:hover {
    opacity: 0.7;
}

The display and list-style-type make the list a horizontal layout.

Here is the header with categories:

categories in header