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

1

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

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 does not appear error, simply does not execute:

 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 the 48 category to apply a 'orderby'='rand' . In short, what I need is to make this if/else work.

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

    
asked by anonymous 24.09.2014 / 20:34

1 answer

3

As a general rule, stay away from query_posts , this is the main query and 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 database calls we use 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 the slug of your category 48 in place of uncategorized .

    
25.09.2014 / 01:24