I have a shortcode which loops through a custom post type. It is supposed to output a link and a title for each post. But the result is that the divs and link tags that are created are empty, while the text content (link and title) ends up outside these wrapping divs.

Here is the code for the shortcode:

add_shortcode('products_info', 'get_products');

  function get_products(){
        //Loops through products
      $loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1) );
        if ($loop->have_posts()):
            $output = '<div class="test01">';

            while ($loop->have_posts()): $loop->the_post();
                $output .= '<div>
                        <a href="' . the_permalink() . '">';
                $output .= the_title() . '</a></div>';
            $output .= '</div>';

        else : $output = '<div>(no products)</div>';


        return $output;


And on the resulting page, I get:

<div class="entry-content">
                    http://thesite/product/theproduct/Nameoftheproduct1http://thesite/product/theproduct/Nameoftheproduct2<p>new test.<br />
    <div class="test01">
          <div><a href=""></a></div>
          <div><a href=""></a></div>

As you can see, the "a href" becomes empty, and the link ends up in the main content div, along with the title which is "Nameoftheproduct1" and "Nameoftheproduct2".

What have I done wrong?

  • 2
    Note that the_* is usually echo's the values and get_* is usually returns the value. It's also custom to clean up with wp_reset_postdata().. – birgire Feb 5 '16 at 13:45
  • Maybe I should use get_post and get_title then? And yes, I used reset postdata before, but wasn't sure if it was the right thing..but okay. – Galivan Feb 5 '16 at 13:53
  • I just tried using "get_permalink()" and "get_the_title()" and this solved the problem!! Thanks! – Galivan Feb 5 '16 at 13:58

Your Answer

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

Browse other questions tagged or ask your own question.