0

Actually this private function in my function.php works, BUT: i often get Error 500 by the Server on the first load, often it renders AFTER reloading the page.

## change the sorting order on archive pages: order archive by title
add_action( 'pre_get_posts', 'gpsp_change_sort_order');
function gpsp_change_sort_order($query) {
  if(is_archive() && $query->is_main_query()) :
    $query->set( 
      'meta_query',
      array(
        'relation' => 'OR',
        array( 'key' => 'ausgabe',  'value' => '', 'compare' => 'EXISTS', 'type' => 'NUMERIC' ),
        array( 'key' => 'position', 'value' => '', 'compare' => 'EXISTS', 'type' => 'NUMERIC' )
      ));
    $query->set( 'orderby', 'meta_value position' );
    $query->set( 'meta_key', 'ausgabe' );
    $query->set( 'order', 'ASC' );
  endif;    
};

Is anyone expert enought to explain me that error?

1 Answer 1

1

I am not an expert, but you have a couple of issues here

Firstly, is_archive() should be an object of $query. You should also just target the front end with your function. Remember, pre_get_posts alters all instances of WP_Query, front end and backend.

So this line

if(is_archive() && $query->is_main_query()) :

should look something like this

if( !is_admin() && $query->is_archive() && $query->is_main_query()) :

I can't figure out your logic with your meta_query and your ordering. I'm really not to sure if your ordering will really work. You should have a real look at that as you are specifying one key and sorting by another

One other possible issue I can see here is, you are using the OR relation in your meta_query. You are retrieving post which have one meta_key or the other meta_key. What happens when there are no posts having one or the other meta_key. How will this influence your ordering and what errors if any will be triggered. Frankly I have not tested scenarions like this yet, so this might be a grab at nothing, but still useful to keep in mind

You might need to work in some check to make sure that a key exists before you try to orderby by it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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