• Resolved Rhand

    (@rhand)


    I am using the following function to load one custom post type post by shortcode. Nice and easy to add to a Gutenberg block. But somehow the title loads where I add the shortcode and the excerpt loads at the beginning of the page before all other blocks. Any ideas why?

    Here is the code

    <?php
    // [imwz-random-posts] shortcode
    add_shortcode('imwz-random-posts','imwz_rand_posts');
    function imwz_rand_posts() { 
     
    $args = array(
        'post_type' => 'molecule',
        'orderby'   => 'rand',
        'posts_per_page' => 1, 
        );
     
    $random_molecules = new WP_Query( $args );
    	$rndmom = ''; 
    if ( $random_molecules->have_posts() ) {
    	
    
    	while ( $random_molecules->have_posts() ) :
    			$random_molecules->the_post();
    			$rndmom .= '<div>';
    			$rndmom .= '<h3><a href="'. get_permalink() .'">'. get_the_title() .'</a></h3><p>' . the_excerpt() . '</p>';
    			$rndmom .= '</div>';
    	endwhile;
    	
    	
    	/* Restore original Post Data */
    	wp_reset_postdata();
    } else {
     
    $rndmom .= 'no posts found';
    }
     
    return $rndmom; 
    } 
Viewing 2 replies - 1 through 2 (of 2 total)
  • The the_excerpt() function outputs it’s content. It doesn’t return it. Becuase of that it outputs the excrpt part when the function is called, which is before the rest of the page is output.

    You need to change that to get_the_excerpt() instead.

    Thread Starter Rhand

    (@rhand)

    Geez, should have looked into that. Thank you very much for your help @catacaustic . Learned something here about something I thought I already knew. Updated code and now using get_the_excerpt. Thanks again!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘shortcode excerpt loaded before all other content’ is closed to new replies.