1

I want to be able to show all post for a given category using my default category template category.php. The problem is the code I'm using sets the specific category ID. So, whenever I click on CAT2... all the post for CAT1 shows. I want it to just show for CAT2 or CAT3... whichever is clicked.

Code:

$args = array (
    'cat'            => 1,
    'orderby'        => rand,
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 1000
);

$my_query = null;
$my_query = new WP_Query($args);

if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) {
        $my_query->the_post();
        // Some code
    }
}
1

You can use the WordPress Template Hierarchy.

Copy your category.php file and rename it.

category-{slug}.php – If the category’s slug is news, WordPress will look for category-news.php.
category-{id}.php – If the category’s ID is 6, WordPress will look for category-6.php.
category.php

You can also use template_include to conditionally display a template

add_filter( 'template_include', 'category_page_template', 99 );

function category_page_template( $template ) {

if ( is_category()  ) {
    $new_template = locate_template( array( 'your-template.php' ) );
    if ( '' != $new_template ) {
        return $new_template;
    }
}

return $template;
}
  • Doing so would mean I have to create a category file for each of my categories, which is a lot. Is this the only option? – alyus Dec 17 '17 at 22:42
  • You can also use template_include. See updated answer. If this works, please click to accept the answer. – Dev Dec 18 '17 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.