Home > Blockchain >  Add Custom Templates to Custom Post Type Taxonomies
Add Custom Templates to Custom Post Type Taxonomies

Time:01-13

I created a Custom Post Type, and it has some categories in it. I created forms with User Frontend Pro for CPT categories.

I’m looking for a solution for assigning the custom templates to that records to show them on the website. For example; Assume that I have a CPT named Project. The project post type has two categories; “Business” and “Ideas” Users can post their entries with forms to these categories and their posts listed under the account dashboard.

The issue is that; Business categories should be shown with the category-business.php custom template, and in a similar way, the Ideas category should be shown with category-ideas.php.

How can I add custom template to CPT categories?

P.S. I tried the template hierarchy solution that is in the WP documents, but it's not working. Because there is a custom view function for content. I looking for a code snippet that adds the template page attributes to custom posts automatically, if it is possible.

CodePudding user response:

Assuming that you are just using the default WordPress category you can the pre_get_posts Hook to include the project as part of the category page if they are not showing by default

 function include_project_to_cat_pages( $query ) {
        if ( $query->is_category() && $query->is_main_query() ) {
            $query->set( 'post_type', array( 'post', 'project' ) );
        }
    }
    add_action( 'pre_get_posts', 'include_project_to_cat_pages' );

CodePudding user response:

I solved that issue with a filter.

add_filter( 'single_template', function( $template ) {
global $post;
$cat = get_the_category()[0];
if ( $post->post_type === 'project' && $cat->slug === 'business') {
    $locate_template = locate_template( "custom-business-template.php" );
    if ( ! empty( $locate_template ) ) {
        $template = $locate_template;
    }
}
return $template;
} );

Thank you to all contributors and the community.

  • Related