Search code examples
phpwordpressshortcodecustom-wordpress-pagescustom-theme

Custom Shortcode Won't Show in Correct Location in WordPress


I have a custom post type (Portfolio) and I created a custom shortcode to display the latest posts for this custom post type. It works, however, it will not display in the correct location. It's at the top of the page, versus the bottom where I have the shortcode posted. Any help would be great!

<?php
function portfolio_posts(){?>
    <?php
    $args = array(
      'numberposts' => '8',
      'post_type'    => 'portfolio'
     );
    ?>
    <?php
    // the query.
    $the_query = new WP_Query( $args ); ?>

    <?php if ( $the_query->have_posts() ) : ?>
        <!-- pagination here -->

        <!-- the loop -->
        <?php
        while ( $the_query->have_posts() ) :
            $the_query->the_post();
            ?>
        <!-- Thumnail, Title and View More Button -->
        <p> <?php the_post_thumbnail('full', array('class' => 'img-fluid')); ?></p>
        <h2 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        <a class="btn" href="<?php the_permalink(); ?>">View</a>
        <?php endwhile; ?>
        <!-- end of the loop -->

        <!-- pagination here -->

        <?php wp_reset_postdata(); ?>

    <?php else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>


<?php    }
add_shortcode('latest_projects', 'portfolio_posts');

Everything works except I can't get it to show in the correct location.


Solution

  • Shortcodes in WordPress need to return content instead of echoing, you can use ob_start and ob_get_clean like this

    <?php
    function portfolio_posts(){
        ob_start();
        $args = array(
          'numberposts' => '8',
          'post_type'    => 'portfolio'
         );
        // the query.
        $the_query = new WP_Query( $args );
    
        if ( $the_query->have_posts() ) : ?>
            <!-- pagination here -->
    
            <!-- the loop -->
            <?php
            while ( $the_query->have_posts() ) :
                $the_query->the_post();
                ?>
            <!-- Thumnail, Title and View More Button -->
            <p> <?php the_post_thumbnail('full', array('class' => 'img-fluid')); ?></p>
            <h2 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
            <a class="btn" href="<?php the_permalink(); ?>">View</a>
            <?php endwhile; ?>
            <!-- end of the loop -->
    
            <!-- pagination here -->
    
            <?php wp_reset_postdata();
    
        else : ?>
            <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
        <?php endif;
    
        return ob_get_clean();
    }
    add_shortcode('latest_projects', 'portfolio_posts');