【问题标题】:Exclude open post from related posts从相关帖子中排除打开的帖子
【发布时间】:2016-12-15 04:23:02
【问题描述】:

如何排除single.php相关帖子中打开的帖子?

这是我的代码:

<?php
$wp_query = null;
$args = array(
    'post_type' => 'glavna_vijest',
    'numberposts' => 2
);
$wp_query = new WP_Query($args);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<h3><?php the_title(); ?></h3>
<?php endwhile; ?>

【问题讨论】:

  • “公开帖子”是什么意思? = 是否允许评论?
  • 不,我在 single.php 中有其他帖子或相关帖子,我不想在那里显示打开的帖子
  • 我只是添加这部分'post__not_in' => array($post->ID)

标签: php wordpress


【解决方案1】:

您想知道如何不将当前帖子包含在相关帖子中。对吗?

您知道帖子 ID,因为它是一个帖子。这是当前显示的。您可以使用get_the_ID() 并将其存储到名为$current_post_id = get_the_ID(); 的变量中。

当您对相关帖子运行查询时,使用参数post__not_in 并将其指定为当前帖子ID。

如何获取当前帖子ID?

single.php 模板中,您可以使用get_the_ID()。然后,您可以将该帖子 ID 传递给相关内容函数。

代码片段

使用上面的代码,您可以构建一个单独的函数来执行相关内容部分,如下所示:

/**
 * Build and then render the related posts
 * section of the web page.
 *
 * @since 1.0.0
 *
 * @param int $current_post_id
 *
 * @return void
 */
function render_related_posts( $current_post_id ) {
    $args = array(
        'post_type'      => 'glavna_vijest',
        'posts_per_page' => 2,
        'post__not_in'   => array( $current_post_id ),
        'nopaging'       => false,
        // You may want to add a category query too
        // to make it more relatable to the current post
    );

    $related_posts_query = new WP_Query( $args );
    if ( ! $related_posts_query->have_posts() ) {
        return;
    }

    while( $related_posts_query->have_posts() ) {
        $related_posts_query->the_post();

        // do the rendering
    }
}

然后您可以在single.php 模板文件中像这样调用该函数:

render_related_posts( get_the_ID() );

您需要根据您的特定需求调整代码。您可能希望扩展相关内容,以按元数据、类别或其他任何方式对其进行过滤,以缩小潜在帖子的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多