How to make a conditional loop in Wordpress depending on the category?

Asked

Viewed 292 times

1

I need to formulate this code to respond to the requirements of a specific category where within it the posts will be presented randomly. For that I made this code on category.php of the template Storyline.

if(is_category(48)){        
    $args = array(
        'cat' => 48,
        'orderby' => 'rand'
    );
    $cp = new WP_Query($args);      
} else {        
    if(of_get_option('order-posts') == "ll" ){
    global $query_string;
        query_posts( $query_string . '&order=ASC' );
    }   
}

..., condition that is already working but need to apply the following condition in another part of the code and no error appears, simply does not perform:

 if(is_category(48)){
      if(have_posts()) : while ( have_posts() ) : the_post();
 } else {
      if($cp->have_posts()) : while ( $cp->have_posts() ) : $cp->the_post();
 }

This code allows in the category 48 i apply a 'orderby'='rand'. In short, what I need is to get this if/else work.

The difference between the ifs is that the second applies conditions of new Wp_query that the former does not apply.

  • What template are you using this code on? That global $ha has something to do with the problem? What error does it make when running?

  • The global $ha is not related to the problem presented. I am using Category.php of the template Storyline. No error appears, simply does not execute.

1 answer

3


As a general rule, stay away from query_posts, this is the main query and when modifying it is almost certain to create more problems than solutions, see When should you use Wp_query vs query_posts() vs get_posts()?. To filter it without causing new calls to the database we use the pre_get_posts in functions.php, in your case:

add_action( 'pre_get_posts', 'random_cat_sopt_33765' );

function random_cat_sopt_33765( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $get_cat = get_query_var( 'category_name' );
        if( $get_cat === 'uncategorized' ) {
            $query->set( 'orderby', 'rand' );
        }
    }
}

Put Slug of your category 48 in place of uncategorized.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.