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
相关产品推荐
相关产品推荐

