douqian2524 2016-07-18 09:30
浏览 31
已采纳

WordPress中的短代码问题

I've created a shortcode in WordPress that I use to call latest blog posts. I've wrapped title and content with <h2> and <p>, but this is not being applied. The html is being generated but without tags where I want. What am I writing wrong?

This is my code:

<?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' );    
 ?>
  • 写回答

1条回答 默认 最新

  • douchuo0730 2016-07-18 10:30
    关注

    The problem is that you are using function that print the html instead returns it. Try this

    //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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法