简体   繁体   中英

WordPress; Display different content template based on category

I want to take the basic WordPress loop and in the place where it makes the call for the content template, I want to run an if else statement that pulls in a different template part based on the category. I know I can make a bunch of copies of archive.php, but why do that for each and every single category you want to use?

So I tried this code, but it just pulled in the archive template in each case:

while ( have_posts() ) :
            the_post();

        if ( is_category( 'my-category-slug' )) {
            get_template_part( 'template-parts/content', 'single' );
        } else {
            get_template_part( 'template-parts/content', 'archive' );
        }

endwhile;

So can I even run an if else statement like this within the loop?

Wordpress has a template hierarchy , you need to make sure that your code is in the right php file. Check up this link . In your case you need to modify category.php, you can use archive.php for this if you delete all category*.php files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM