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

WordPress自定义短码无法在指定位置显示求助

WordPress短码内容显示位置错误的解决方法

问题核心在于你的短码函数是直接输出内容,而非返回内容。WordPress短码的运行机制是收集函数返回的内容,再插入到短码所在的位置;如果直接输出内容,会在页面渲染流程的早期被输出,自然就跑到页面顶部了。

修改方案:把所有要输出的内容收集到一个变量中,最后返回这个变量,同时将直接输出的模板函数替换为返回值版本:

<?php
function portfolio_posts(){
    $output = '';
    $args = array(
      'numberposts' => '8',
      'post_type'    => 'portfolio'
     );

    // 执行查询
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :
        // 分页代码可在此添加

        // 循环输出内容
        while ( $the_query->have_posts() ) :
            $the_query->the_post();
            // 拼接缩略图、标题和按钮的HTML到变量
            $output .= '<p>' . get_the_post_thumbnail('full', array('class' => 'img-fluid')) . '</p>';
            $output .= '<h2 class="post-title"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h2>';
            $output .= '<a class="btn" href="' . get_the_permalink() . '">View</a>';
        endwhile;

        wp_reset_postdata();

    else :
        $output .= '<p>' . esc_html__( 'Sorry, no posts matched your criteria.' ) . '</p>';
    endif;

    return $output;
}
add_shortcode('latest_projects', 'portfolio_posts');

关键修改点

  • 新增$output变量存储所有要输出的内容
  • 将the_post_thumbnail()替换为get_the_post_thumbnail(),后者返回图片HTML而非直接输出
  • 将the_title()、the_permalink()分别替换为get_the_title()、get_the_permalink(),同理返回内容而非直接输出
  • 所有HTML内容通过.追加到$output中
  • 函数最后返回$output,让WordPress将内容插入到短码所在的正确位置

内容的提问来源于stack exchange,提问作者Cheryl Ju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:52:31