stackers
stackers

Reputation: 385

add shortcode heading showing multiple time

Hi my code is below for adding shortcode in posts. when i am adding shortcode two times it shows me heading two times that i added in code "Recent Posts" is there is way to show this heading only top means one time?

/*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;
}

Ecample Image

Upvotes: 2

Views: 120

Answers (1)

Karthik
Karthik

Reputation: 1751

Define a global variable to detect whether title is already added.

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;
        }

Hope that helps..!

Upvotes: 1

Related Questions