Search code examples
phpwordpresscustom-post-typeshortcode

Wordpress Shortcode displaying data out of order even using return


I am trying to display some data with my WP Shortcode, but it's showing everything out of order. After searching a bit, the docs say you need to use return in the function, but it's still not working.

Here's the code

function dwwp_jobs_from_california($atts){

  $atts = shortcode_atts(array(
    'title' => 'All jobs in California:',
    ),
    $atts
  );

  $query = new WP_Query( array('post_type' => 'job'));
  $jobs = "<h1>" . $atts['title'] . '</h1><br>';
  if( $query->have_posts()):
    while ( $query->have_posts() ) :
      $query->the_post();
      $jobs .= '<h3>' . the_title() . '</h3><br>';
    endwhile;
  endif;

  $jobs .= "End of the loop!";
  wp_reset_query();
  return $jobs;
  }

add_shortcode('jobs_california', 'dwwp_jobs_from_california');

In my Wordpress page:

"Content of the page"

[jobs_california]

What it is rendering on the page:

[jobs_california]
"Content of the page"

I must also admit i'm not very used to work with PHP, so sorry if my code quality is not nice.

Can anyone tell me what am i doing wrong? Thanks in advance!


Solution

  • I think the only problem you are having is that you are using the_title() which will echo the post title... But you want to build a html string instead, that will be returned by your short code function. Try using:

    the_title('', '', false)
    

    or, much better:

    get_the_title()
    

    Hope this helps!