0

I am trying to modify the main query on a taxonomy term page by using pre_get_posts action and post__in field. To add IDs to post__in field I have to run a query. When I call this query I run into a "Fatal error: Allowed memory size..." issue. If I call the same query in a template file that works great. I think I should use some different method to achieve my goal. How could I run a query inside pre_get_posts? I would like to only modify main query instead of replace with a custom query, or create a custom page.

function custom_loops($query) {
if (is_tax( 'service_photo_location' )){
    $ids = get_nearby_partners_by_area(50000, 'service_photo');
    $query->set( 'post__in', $ids);
    $query->set( 'posts_per_page', 10);
    $query->set( 'meta_key', 'custom_meta_partner_subscription_level');
    $query->set( 'orderby', 'meta_value title');
    $query->set( 'order', 'ASC');
}
remove_action( 'pre_get_posts', 'custom_loops' );
}
add_action('pre_get_posts', 'custom_loops');

function get_nearby_partners_by_area($distance, $post_type){
    $post_ids = array();
    $args = array( 'posts_per_page' => 10, 'post_type'=> 'wedding_dress', 'post_status' => 'publish', 'fields' => 'ids' );
    $all_partners = get_posts( $args ); //at tis point i get memory error
    foreach ( $all_partners as $post ) : setup_postdata( $post );
        // this point I calculate some things
        $post_ids = $post->ID;
    endforeach;
    wp_reset_postdata();
    return $post_ids;
}
2

Remove the action before you run the internal query, and always verify main query with is_main_query:

function custom_loops($query) {
    if ( $query->is_tax( 'service_photo_location' ) && $query->is_main_query() ){
        remove_action( 'pre_get_posts', 'custom_loops' );
        $ids = get_nearby_partners_by_area(50000, 'service_photo');
        // ...
    }
}
add_action('pre_get_posts', 'custom_loops');
  • 1
    Ohh. $query->is_main_query() solved my issue. Thank you. – user9909 Mar 11 '15 at 9:29

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.