【问题标题】:Wordpress is_single() always return true in custom WP_QueryWordpress is_single() 在自定义 WP_Query 中始终返回 true
【发布时间】:2018-06-16 15:17:46
【问题描述】:

我在单个帖子页面上使用自定义 WP_Query(它显示最近帖子的列表):

$recent = new WP_Query($args);
while ($recent->have_posts()) {
    $recent->the_post();
    get_template_part('template-parts/content', get_post_format());
}

问题是:在模板中我检查 is_single() 条件,它总是返回 true(没有传递参数)。当我尝试 is_single($post) 时,有时它返回 true,有时返回 false。

UPD 1:

我在我的主题文件夹中使用 template-parts/content.php 模板。代码是这样的:

    if ( is_single($post) ) :
        the_title( '<h1 class="entry-title pb-1 '.ta_content_paragraphs_paddings().'">', '</h1>' );
    else :
        the_title( '<h2 class="entry-title pb-1 '.ta_content_paragraphs_paddings().'"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
    endif; ?>

UPD 2: 我发现为什么它有时会以 $post 作为参数返回 true,当我的单个帖子标题与最近的帖子标题相同时会发生这种情况。 class-wp-query中的这部分代码,函数is_single:

} elseif ( in_array( $post_obj->post_title, $post ) ) { // returns here
            return true;

查看帖子标题告诉我它是一个页面是否正常?

【问题讨论】:

  • 您在哪里以及如何使用 is_single?也提供该代码。
  • 用这部分代码更新你的问题。你的'$post'是什么?你在哪里定义的?
  • $post 是一个全局变量,它包含一个 post 对象(在我当前所在的页面上)

标签: wordpress wordpress-theming


【解决方案1】:

我能够通过向 is_single 提供不是 $post 而是 $post->ID 来解决此问题:

is_single($post->ID);

我不认为在 wordpress 的核心中匹配 $post->post_title 来告诉它一个单独的帖子页面是一个好主意。也许我错了,误解了这一点。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2013-03-02
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多