Wordpress Shortcode即使使用return也无序显示数据

时间:2017-01-20 19:28:58

标签: php wordpress custom-post-type shortcode

我正在尝试使用我的WP Shortcode显示一些数据,但它显示的一切都是乱序。搜索了一下之后,文档说你需要在函数中使用return,但它仍然不能正常工作。

这是代码

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');

在我的Wordpress页面中:

"Content of the page"

[jobs_california]

在页面上呈现的内容:

[jobs_california]
"Content of the page"

我还必须承认我不习惯使用PHP,所以如果我的代码质量不好,那就很抱歉。

谁能告诉我,我做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:2)

我认为你遇到的唯一问题就是你正在使用the_title() echo帖子标题......但是你想构建一个html字符串,这将由你的短代码功能。尝试使用:

the_title('', '', false)

或更好:

get_the_title()

希望这有帮助!