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 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题