Seperate template for custom post type author archive. WordPress code example

Seperate template for custom post type author archive. WordPress code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Let’s imagine that we have a new type of post – portfolio. A template will be used for these entries – archive.php. We can see a list of all these post on the page site.com/portfolio. But what if we want to connect a separate template for the author archive pages of the custom portfolio type?

The function below will help us with this:

//Template for custom post type author archive
function custom_template_include($template) { //This is a function declaration that takes the current template as an argument and returns the modified template.
    global $wp_query; //This is a global WordPress variable containing basic information about the current request. We use it to check some query conditions.

    
    if (is_author() && isset($wp_query->query_vars['author_name']) && $wp_query->query_vars['post_type'] == 'portfolio') {
        
        $template = locate_template('your-custom-template.php');

        
        if (empty($template)) {
            $template = get_template_directory() . '/single-portfolio.php';
        }
    }

    return $template;
}
add_filter('template_include', 'custom_template_include');

if (is_author() && isset($wp_query->query_vars[‘author_name’]) && $wp_query->query_vars[‘post_type’] == ‘portfolio’) – this condition checks whether the current query is a query for the author and matches whether he is your rule. In this case, the condition checks that the request is for an author and has an author_name parameter, and that the post_type is ‘portfolio‘.

$template = locate_template(‘your-custom-template.php’) – if the condition is true, this line replaces the current template with a custom template named ‘your-custom-template.php‘ using the locate_template() function. This custom template must be located in the active WordPress theme.

0

More

Leave a Reply

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

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation