You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章类型Single页current_post返回-1问题求助

问题原因与修复方案

核心问题

你调用$the_query->current_post返回-1的直接原因是:你创建了WP_Query实例,但从未启动它的循环(没有执行while($the_query->have_posts()) : $the_query->the_post();)。current_post是WP_Query内部用于追踪循环迭代位置的属性,刚初始化的查询对象默认值就是-1,只有当你调用循环方法迭代时,它才会从0开始递增。

除此之外,你的代码还有几个关键错误:

  • $args2里的meta_key为空,meta_value使用get_the_ID($the_query)完全无效(此时$the_query还未定义,且get_the_ID()不需要传参,直接调用就能获取当前文章ID)。
  • $term_ID变量未定义,你需要从当前文章的awardtype分类中获取对应的term值。
  • 逻辑冗余:在single页面的主循环里,没必要重新查询包含当前文章的集合,应该直接查询同分类的所有文章,再定位当前文章的索引。

修复后的代码示例

替换你原代码中while ( have_posts() ) : the_post();之后到$terms=get_the_terms(...)之前的部分:

<?php
$counter = 0;
$total = 0;
while ( have_posts() ) :
    the_post();

// 获取当前文章所属的awardtype分类
$terms = get_the_terms( $post->ID, 'awardtype' );
$current_term = !empty($terms) ? reset($terms) : null;

if($current_term){
    // 查询同分类下的所有award文章
    $args2 = array(
        'post_type' => 'award',
        'posts_per_page' => -1, // 获取所有文章
        'tax_query' => array(
            array (
                'taxonomy' => 'awardtype',
                'field' => 'term_id',
                'terms' => $current_term->term_id,
            )
        ),
        'orderby' => 'date', // 可根据需求调整排序规则
        'order' => 'DESC'
    );
    $the_query = new WP_Query( $args2 );
    $total = $the_query->post_count;
    
    // 遍历查询结果,找到当前文章的索引
    $current_index = -1;
    if($the_query->have_posts()){
        $index = 0;
        while($the_query->have_posts()) : $the_query->the_post();
            if(get_the_ID() == $post->ID){
                $current_index = $index;
                break;
            }
            $index++;
        endwhile;
        // 重置主查询,避免影响后续内容
        wp_reset_postdata();
    }
    echo "Current Post: " . $current_index;
}

// 继续获取自定义字段
$designation = get_post_meta( $post->ID, 'designation', true);
$winner_team = get_post_meta( $post->ID, 'winner_team', true);
$feedback_provider_name = get_post_meta( $post->ID, 'feedback_provider_name', true);
$year = get_post_meta( $post->ID, 'year', true);
?>

额外说明

  • 使用wp_reset_postdata()重置查询,避免自定义查询影响后续的主循环内容。
  • 你可以根据需求调整$args2里的orderby和order参数,确保索引的排序符合你的需求。
  • 原代码中$counter和$total的逻辑可以结合修复后的$current_index和$total来使用。

内容的提问来源于stack exchange,提问作者Hybrid Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:22:01