Search code examples
phpwordpresstemplatescustom-post-typecustom-wordpress-pages

Add Custom Templates to Custom Post Type Taxonomies


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.


Solution

  • 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.