dpt62283 2015-11-25 06:12
浏览 43
已采纳

Wordpress嵌套循环,无法从查询中删除meta_key

I have two custom posts types A and B, linked together with a same custom taxonomy. While looping through A posts with the "default" loop, I want for each A to get all B with the same taxonomy.

The code looks like this:

<?php if(have_posts()): while(have_posts()): the_post(); ?>
    <?php 
        $A_Bs=get_the_terms( $post->ID, 'A_B');
    ?>

    <?php if($A_Bs!=false && count($A_Bs)>0):?>

        <?php

            $A_B=$A_Bs[0];
            $args = array(
                'post_type'      => 'B',
                'tax_query' => array(
                  array(
                    'taxonomy' => 'A_B',
                    'field' => 'term_id',
                    'terms' => $A_B->term_id,
                  ),
                ),
            );

            $loop = new WP_Query($args);
            $saved_post=$post;
        ?>

        <?php while ($loop->have_posts()) : $loop->the_post();?>
            blabla
        <?php endwhile;?>
        <?php $post=$saved_post;?>

    <?php endif;?>
<?php endwhile; endif;?>

But the sub-loop is always empty. The reason is, in the query_vars I have these two guys:

  'meta_key' => string 'position' (length=8)
  'orderby' => string 'meta_value_num' (length=14)

and I can't get rid of them. I never specified this ordering anywhere and my B posts don't have this custom field.

It's generating this line in the SQL query:

aaaa_postmeta.meta_key = 'position'

and prevent me to list the posts. I tried to play with the $args, removing the tax_query and changing the post_type but it's always the same.

Thank you for your time !

  • 写回答

1条回答 默认 最新

  • douxiluan6555 2015-11-25 06:27
    关注

    Sorry I just realized after hours that I have the following thing in functions.php

    function order_by_position($query){
    
        if(is_post_type_archive( 'A')||is_post_type_archive( 'C')||is_post_type_archive( 'D')){
            $query->query_vars['meta_key']="position";
            $query->query_vars['orderby']="meta_value_num";
        }
        return $query;
    }
    add_action( 'pre_get_posts', 'order_by_position' );
    

    It's much more logical now. Sorry for disturbing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?