【问题标题】:Exclude current post in a loop using *__in (exlude without 'post__not_in')使用 *__in 在循环中排除当前帖子(不使用 'post__not_in' 排除)
【发布时间】:2020-02-10 02:29:51
【问题描述】:

我想从使用'tag__in'argument 的循环中排除当前帖子,这会造成问题,因为post__not_in 和前者是互斥的

注意:您不能在同一个查询中组合 post__in 和 post__not_in。

http://codex.wordpress.org/Class_Reference/WP_Query

如何从这个循环中删除当前帖子?

    <?php
    global $post;
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    $tag_ids = array();
    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    $args=array(
    'tag__in' => $tag_ids,
    'post__not_in' => array($post->ID),
    'posts_per_page'=>2 // Number of related posts that will be shown.
    );
    $my_query = new wp_query( $args );
    if( $my_query->have_posts() ) {
    while( $my_query->have_posts() ) {
    $my_query->the_post();
    HTML HERE }}
    else { HTML HERE }}

谢谢

【问题讨论】:

    标签: php wordpress loops foreach


    【解决方案1】:

    事实上,这些默认情况下是不兼容的,但您可以绕过它直接使用 tax_query 参数来发挥您的优势。

    另一个提示是,当您在 WP 中进行开发时,您应该打开 wp-config.php 上的 WP_DEBUG 常量。它标记了 caller_get_posts 已弃用。

    $query = new WP_Query( [
        'tax_query'        => [
            [
                'taxonomy' => 'post_tag',
                'terms'    => $tag_ids,
                'operator' => 'IN',
            ],
        ],
        'post__not_in'     => [ $post->ID ],
        'posts_per_page'   => 2, // Number of related posts that will be shown.
        // 'caller_get_posts' => 1 // Removing since this was deprecated.
    ] );
    

    让我知道该代码是否有效。

    最好的问候,

    【讨论】:

    • 感谢您的回答,但它似乎并没有获取具有相似标签的帖子。我页面上的结果回退到显示 No Post 相关的 else 参数。 (对不起,缺乏适当的技术词汇,我是自学的)
    • 我在原始问题中添加了代码的末尾,以便更清晰
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多