【问题标题】:Wordpress how to use two variables for Post__not_in argument in a wp_queryWordpress 如何在 wp_query 中为 Post__not_in 参数使用两个变量
【发布时间】:2022-01-21 13:06:41
【问题描述】:

我怎样才能像这样在post__not_in 中放入两个变量:

'post__not_in' => $excludeHome, $excludePostSlide

当我这样做时,只有来自第一个变量的帖子不会从其他变量中显示出来。

我可以使用下面的数组推送来做到这一点,但有什么不同的方法吗?

  @php
    wp_reset_postdata();
    global $excludeHome;
    global $excludePostSlide;
    array_push($excludeHome, $excludePostSlide[0], $excludePostSlide[1], $excludePostSlide[2], $excludePostSlide[3], $excludePostSlide[4], $excludePostSlide[5]);
    $args = [
        'post_type' => 'post',
        'orderby' => 'date',
        'category_name' => 'auto',
        'posts_per_page' => 6,
        'no_found_rows' => true,
        'post__not_in' => $excludeHome,
    ];
    $querySlider = new WP_Query($args);
  @endphp

【问题讨论】:

    标签: php wordpress wordpress-theming custom-wordpress-pages


    【解决方案1】:

    根据wp_queryDocspost__not_in 接受一个帖子 ID 数组。

    • 尚不清楚您的全局$excludeHome$excludePostSlide 变量实际上是数组。所以请确保它们是数组。
    • 要使用array_push 函数,最好在$excludePostSlide 数组上使用foreach 循环,而不是尝试按索引号推送它们!
    global $excludeHome;
    global $excludePostSlide;
    
    $excludeHome = is_array($excludeHome)
        ? $excludeHome
        : (array)$excludeHome;
    
    $excludePostSlide = is_array($excludePostSlide)
        ? $excludePostSlide
        : (array)$excludePostSlide;
    
    foreach ($excludePostSlide as $excludeSlide) {
        array_push($excludeHome, $excludeSlide);
    }
    
    $args = [
        'post_type'      => 'post',
        'orderby'        => 'date',
        'category_name'  => 'auto',
        'posts_per_page' => 6,
        'no_found_rows'  => true,
        'post__not_in'   => $excludeHome,
    ];
    
    $querySlider = new WP_Query($args);
    

    【讨论】:

    • 感谢这项工作,我使用了roots-sage,为了使用roots sage,我使用了用laravel 刀片构建的基岩,root-sage 主题也是用laravel 刀片构建的
    【解决方案2】:

    尝试将参数传递为array

    $args = [
        'post_type' => 'post',
        'orderby' => 'date',
        'category_name' => 'auto',
        'posts_per_page' => 6,
        'no_found_rows' => true,
        'post__not_in' => array(
              $excludeHome, 
              $excludePostSlide
         )
    ];
    $querySlider = new WP_Query($args);
    

    【讨论】:

    • 我试过了,但它不起作用,没有一个帖子被排除在外
    • 它没有显示任何错误或任何内容,只是它不排除帖子
    • 变量是类别ID吗?如果是这样,那应该可以。我参考这个查询列表来在一个地方找到所有不同的部分。 github.com/luetkemj/wp-query-ref
    • 是的,它们是帖子的 ID,如您所见 array_push($excludeHome, $excludePostSlide[0], $excludePostSlide[1], $excludePostSlide[2], $excludePostSlide[3], $excludePostSlide[4], $excludePostSlide[5]); 如果我使用数组推送,这段代码可以工作,但我不知道这是否是最佳做法
    猜你喜欢
    • 2014-07-29
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多