嗨,我的代码如下,用于在帖子中添加快捷代码。当我添加两次短代码时,它显示了我在代码“最近的帖子”中添加的两次标题,有没有办法只显示这个标题一次?
/*shortcode start*/
add_shortcode( 'recent-posts', 'PL_recent_posts' );
function PL_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
'order' => 'ASC',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' , 'colorss' => $color ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}

发布于 2015-09-17 03:19:31
定义一个全局变量来检测是否已经添加了title。
function PL_recent_posts( $atts ) {
global $title_added;
...
if ( $rposts->have_posts() ) {
if ( $title_added ) {
$html = '<ul class="recent-posts">';
} else {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
$title_added = true;
}希望这能帮上忙!
https://stackoverflow.com/questions/32605643
复制相似问题