DEV Community

Cover image for Wordpress development - configure a theme template by using a plugin
Raymundo CH
Raymundo CH

Posted on • Edited on

Wordpress development - configure a theme template by using a plugin

When you are developing a plugin you might come across a situatuion where you have to update a theme template or create a new one from scratch.

Under the previous circumstances the solution I've implemented is the use of the template_include filter.

I'm going to explain how this filter works and it's quite interesting and useful.

First call the add_filter() function as shown below and pass in the filter name as parameter:

Ad - Managed WordPress Hosting from SiteGround - Powerful, yet simple to use. Click to learn more.

<?php


function rch_add_custom_post_type_template($template){


    return $template;


}

add_filter("template_include","rch_add_custom_post_type_template");
Enter fullscreen mode Exit fullscreen mode

Note how the function receives the $template variable which holds the path to the php file which contains the HTML markup and the php code.

Then let's add the logic to filter the web pages and locate the one we want to modify:

function rch_add_custom_post_type_template($template){

    if(is_singular("mycars")){


    }

    return $template;


}

add_filter("template_include","rch_add_custom_post_type_template");
Enter fullscreen mode Exit fullscreen mode

Note how the is_singular() function was implemented to find the publication which contains content related to the custom post type called mycars.

Then the path to the template must be saved into a variable and returned as the result of the function:

 if(is_singular("mycars")){

    $template_path = WP_PLUGIN_DIR."/carsplugin/frontend/carsTemplate.php";

        if(file_exists($template_path)){

            return $template_path;
        }

    }
Enter fullscreen mode Exit fullscreen mode

Remember that the constant called WP_PLUGIN_DIR holds the path to the plugins folder; it's important to note the difference between path and URL.

Ad - Managed WordPress Hosting from SiteGround - Powerful, yet simple to use. Click to learn more.

Top comments (0)