doutu1939 2013-07-07 10:52
浏览 51

在Wordpress Shortcode中返回一个函数

Recently I have been playing around with Wordpress Shortcode. When following this tutorial (changed a few things, of course), I found that even without returning anything (return $return_string; - part) my code is still working as intended.

I opened PHP manual and it says:

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.

My question:

Since looks like there is nothing broken, should I keep doing what I do, or should I "return" something from my function (there is actually a downside from not "return-ing" anything I just haven't seen, yet) ?

Edit: The code, just in case.. no "return", still processing the shortcode / loop

function looping_cat($atts, $content) {
    extract(shortcode_atts(array(
      "query" => '',
      "category" => ''
    ), $atts));

    $wp_query = new WP_Query();

    if(!empty($category)){
      $query .= '&category_name='.$category;
    }
    $wp_query->query($query);
    ?>

      <ul>
      <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
          <li>
              <div>
                  <?php the_post_thumbnail(); ?>

                   <h2><?php the_title() ?></h2>
              </div>
               <?php the_excerpt(); ?>
              </div>
          </li>
      <?php endwhile; wp_reset_query(); ?>
      </ul>
    <?php 
}
  • 写回答

1条回答 默认 最新

  • dpsq8476 2013-07-07 10:57
    关注

    If you don't specify a return statement, null will be returned. See this question.

    If it fits your goals that nothing will be displayed for your shortcode, it is fine to omit the return statement.

    For readability purposes I recommend to use return statements everywhere, even if you are returning null.

    Edit:

    Now I understand what do you mean by returning nothing. Actually you're inlining the HTML in your shortcut function.

    Actually, I still prefer to collect and return all content as a string, because it gives you more control of handling the content. If a certain condition happens later, you may still decide to return something else. It may also "disturb" WP, because inlining will output the content immediately, while returning the content enabled WP to decide when (and where) will it show.

    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊