Support

Account

Home Forums General Issues Issue getting options from pre_get_posts filter

Solving

Issue getting options from pre_get_posts filter

  • Hi,

    Im trying to retrieve a option field from within the pre_get_posts filter, it doesnt work and gives me a error 500 each time, I tried retrieving the option field from regular template files ie. single.php and it returns the value there.

    Sample code looks like:

    add_action('pre_get_posts', function($query) {
    
     if(is_single()){
      $option_a = get_field('my_option_field', 'option'); //post object , array of post ids
      $query->set('post__in', $option_a);
    }
    
    }

    Thanks in advance!

  • I updated my field to be on each post from options, so from options to post meta.

    I tried using get_field inside pre_get_posts and it didnt work, what worked though is when I used get_post_meta, using the global $post->ID as my reference. Is using get_post_meta okay? Just want to make sure this doesnt create any issues in the future.

  • Exactly what error are you getting? 500 means nothing. https://codex.wordpress.org/WP_DEBUG.

    Get field should work in pre_get_fields.

    More than likely the format of the value you are getting is not correct for “post__in”. What type of field is it and what is it returning?

  • its pre_get_posts, it doesnt return or log anything on the error logs because it gives an error 500 each time I use it. I used the same code on a template file(ie. single.php) and the same code returns an array of post ids. Its only on pre_get_posts on functions.php that the code behaves differently.

    FYI

    I updated this to fetch a custom field on the post and not the options, get_field still doesnt function properly inside pre_get_posts, I used get_post_meta instead and it worked. Maybe get_field doesnt work around the time pre_get_posts is being called?

  • Add this line:

    if( !$query->is_main_query() ) return;

    at the beginning of you filter, solved it for me

  • @ryancb you never really answered my questions.

    Turn in debugging so that you can see what error is produced instead of getting WOD. Then let me know what the error is.

    What do you have this field set to return? “Posts Object” or “Post ID”?
    Does this field allow multiple selections?

    
    $option_a = get_field('my_option_field', 'option'); //post object , array of post ids
    
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.