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

WordPress循环中get_permalink()返回重复URL问题排查

问题原因

遍历文章列表的循环中,获取固定链接、作者ID时错误使用了全局$post变量,没有传入当前循环对应的文章对象$post_item。全局$post存储的是页面主查询的当前文章数据,不会随自定义foreach循环更新,因此所有轮播项都会输出同一个固定链接。
另外原代码中输出特色图的PHP语句缺少闭合标签,存在语法隐患。

修复后代码

直接将循环内所有调用文章数据的参数替换为当前循环项$post_item即可:

$recent_posts = get_posts(array(
    'posts_per_page' => '6',
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));
foreach ($recent_posts as $post_item) : ?>
    <?php $author_id = $post_item->post_author; ?>
    <a href="<?= get_permalink($post_item) ?>" class="special-slide">
        <?php echo get_the_post_thumbnail($post_item, 'full'); ?>
    </a>
<?php endforeach; ?>
可选优化

如果后续需要在循环中使用the_title()、the_excerpt()这类不支持直接传入文章对象的模板标签,可以参考以下写法避免逻辑异常:

  • 循环开头调用setup_postdata($post_item)配置全局文章数据
  • 循环结束后调用wp_reset_postdata()还原全局变量,避免干扰页面其他循环逻辑
    参考代码如下:
foreach ($recent_posts as $post_item) :
    setup_postdata($post_item);
    $author_id = $post_item->post_author; ?>
    <a href="<?= get_permalink($post_item) ?>" class="special-slide">
        <?php echo get_the_post_thumbnail($post_item, 'full'); ?>
    </a>
<?php endforeach;
wp_reset_postdata(); ?>

内容的提问来源于stack exchange,提问作者Ahmad Beyranvand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 19:45:58