I have this PHP code that shows a related posts element created using advanced custom fields plugin. I want to create a shortcode inside functions.php with the code and then use the shortcode in a text element of a page builder. Would someone kindly assist me with the modified code to put inside functions.php? Thanks

$posts = get_field('related_posts', false, false);
$loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3, 'post__in' => $posts, 'post_status' => 'publish', 'orderby' => 'post__in', 'order' => 'ASC' ));

if($loop->have_posts()) { ?>
    <div class="rel-posts">

    <?php while ($loop->have_posts()) : $loop->the_post(); ?>

        <div class="related-post">
            <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('td_218x150'); ?></a>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

    <?php endwhile; ?>

<?php } wp_reset_query(); ?> 

If your code works fine then do this in function.php

    add_shortcode( 'custom_name', 'footag_func' );
    function footag_func( $atts ) {
    $html= '';
    $posts = get_field('related_posts', false, false);
    $loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3, 'post__in' => $posts, 'post_status' => 'publish', 'orderby' => 'post__in', 'order' => 'ASC' ));

    if($loop->have_posts()) { 
       $html .= '<div class="rel-posts">';

        while ($loop->have_posts()) : $loop->the_post(); 

           $html .= '<div class="related-post">';
            $html .='<a href="'.the_permalink().'">'.the_post_thumbnail('td_218x150').'</a>';
              $html .=  '<h3><a href="'.the_permalink().'">'.the_title().'</a></h3>';
           $html .=  '</div>';


   $html .= '</div>';
   } wp_reset_query(); 
    return $html;

your shortcode [custom_name]

  • Thank you for this. I have seen that the related posts appear at the top of the page created with page builder rather than at the location where I placed the shortcode (at the bottom). Is that a normal behaviour? – Mato Dec 29 '18 at 15:49
  • Shortcodes must return their contents, not directly print or echo. – Milo Dec 29 '18 at 16:27
  • @Milo I am a php newbie. How do I make the code above as you specified? Or could you kindly provide the edited code as per your suggestion? – Mato Dec 30 '18 at 8:12
  • @Mato edited the code – Techno Deviser Dec 31 '18 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.