0

I want to change the default ordering for posts, to last modified date, but only for certain categories pages (when visiting certain category pages)

I have this function code, which is working, but I do not know how to make it apply only to the categories in my array. I tried with in_category but it's not working

  function wpse10691_alter_query( $query )
{

    if ( $query->is_main_query() && is_category(array('573,1060,1061,1062,1063,1065,1066,1064') ) ) 
    {
        $query->set( 'orderby', 'modified' );
        $query->set( 'order', 'desc' );
    }
}
add_action( 'pre_get_posts', 'wpse10691_alter_query' );

any help would be much appreciated. thank you

1 Answer 1

1

Problem 1

$foo = is_category( ... );

Is the same as:

global $wp_query; // the main query
$foo = $wp_query->is_category(....);

So when filtering the query, don't check the main query, check the query you're filtering instead:

$query->is_main_query() && $query->is_category( ....

Problem 2

Look at this:

array('573,1060,1061,1062,1063,1065,1066,1064')

You might think this is a list of 8 things, but no. It's a list of 1 thing:

array(
    '573,1060,1061,1062,1063,1065,1066,1064'
)

That array contains a single item, a string with a comma separated list in it. Because there is no category with a single ID that is equal to "573,1060,1061,1062,1063,1065,1066,1064" it is never true.

This is incorrect, and does not match any of the docs, and is not how arrays normally work in PHP. There should not be quotes wrapping all the values into a single string.

Instead of:

[ "1,2,3,4,5" ]

It should be:

[ 1,2,3,4,5 ]

Notice the syntax highlighting recognises each number as separate, but paints the entire string in green. I'd strongly suggest using a code editor to edit code that has syntax highlighting and auto-indenting. Programs such as VS Code or Sublime Text will do this for free as well as other things.

1
  • it totally makes and easy to understand even for a beginner like me. many thanks for the help and useful explanations, I actually learned something!
    – vyperlook
    Jul 31 at 19:39

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.