【问题标题】:Shortcode issue in WordPressWordPress中的简码问题
【发布时间】:2016-11-20 20:27:26
【问题描述】:

我在 WordPress 中创建了一个短代码,用于调用最新的博客文章。 我已经用<h2><p> 包装了标题和内容,但这没有被应用。正在生成 html,但没有我想要的标签。我写错了什么?

这是我的代码:

<?php 

//blog posts shortcode

function my_recent_post()
 {
  global $post;

  $html = "";

  $my_query = new WP_Query( array(
       'post_type' => 'post',
       'cat' => '4',
       'posts_per_page' => 1
  ));

  if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();

       $html .= "<span>" . the_post_thumbnail( 'medium', array( 'class' => 'img-responsive') ) . "</span>";
       $html .= "<h2>" . the_title() . "</h2>";
       $html .= "<p>" . the_excerpt() . "</p>";

  endwhile; endif;

  return $html;
 }
 add_shortcode( 'blog', 'my_recent_post' );    
 ?>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    问题是您使用的是打印 html 的函数,而不是返回它。 试试这个

    //blog posts shortcode
    add_shortcode( 'blog', 'my_recent_post' );    
    
    function my_recent_post() {
        global $post;
    
        $html = "";
    
        $my_query = new WP_Query( array(
            'post_type' => 'post',
            'cat' => '4',
            'posts_per_page' => 1
        ));
    
       if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
    
           $html .= "<span>" . get_the_post_thumbnail( $post->ID, 'medium', array( 'class' => 'img-responsive') ) . "</span>";
           $html .= "<h2>" . get_the_title() . "</h2>";
           $html .= "<p>" . get_the_excerpt() . "</p>";
    
      endwhile; endif;
    
      return $html;
    }
    

    【讨论】:

    • 我的意思是你用the_excerpt代替get_the_excerpt,用the_title代替get_the_title。您可以尝试使用我的代码吗?
    猜你喜欢
    • 2019-03-15
    • 2011-08-21
    • 1970-01-01
    • 2017-05-17
    • 2018-12-02
    • 2013-07-25
    • 2020-01-21
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多