short code output too early

时间:2012-03-27 作者:andresmijares

我正在尝试基于以下代码创建一个短代码:

<ul class="filter">
<li>Filter:</li>
<li class="link-store"><a href="<?php echo get_permalink( 23 ); ?>">All</a></li>
    <?php global $post; $thispage = $post->ID; // grabs the current post id from global and then assigns it to thispage ?>
    <?php $pagekids = get_pages("child_of=".$thispage."&sort_column=menu_order"); // gets a list of page that are sub pages of the current page and assigns then to pagekids ?>

    <?php if ($pagekids) { // if there are any values stored in pagekids and therefore the current page has subpages ?>
        <ul>
            <?php wp_list_pages("depth=1&title_li=&sort_column=menu_order&child_of=".$thispage); // display the sub pages of the current page only ?>
        </ul>
            <?php } elseif($post->post_parent)
               $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); if ($children) { // if there are no sub pages for the current page ?>
        <ul>
            <?php echo $children; ?>
        </ul>
            <?php } ?>
        </ul>
Out of the question, 这是一个非常好的资源,因为它返回子页面,甚至兄弟页面。

好的,回到游戏。。。。我试图在此基础上创建一个简短的代码,但如果不起作用,到目前为止,我有以下内容:

function filter_store ( $atts ) {
global $post; $thispage = $post->ID;
if ($pagekids) {
   $output .= \'<ul>\';
      wp_list_pages("depth=1&title_li=&sort_column=menu_order&child_of=".$thispage);
       $output .= \'</ul>\';   
            } elseif($post->post_parent) 
           $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); if ($children) {
       $output .= \'<ul>\';
            echo $children;
       $output .= \'</ul>\';
            }
        return $output;
    }

   add_shortcode(\'filter\', \'filter_store\');
我已经花了大约3个小时试图找到错误所在,我的头快要爆炸了,如果能在这方面得到任何帮助,我将不胜感激。

提前感谢。

3 个回复
最合适的回答,由SO网友:fuxia 整理而成

一个短代码必须返回一个字符串,您不应该打印类似于wp_list_pages()echo. 从…起Shortcode API:

将短代码处理程序函数的返回值插入到post内容输出中,以代替短代码宏。Remember to use return and not echo - 任何回显的内容都将输出到浏览器,但不会显示在页面的正确位置。

SO网友:Harkály Gergő

您的问题是,短代码内容出现在其他内容之前,而不是您想要的位置?如果是,您可以通过以下方式解决此问题:

function filter_store()
{
    ob_start();
    ...
    echo $children;
    ...
    $ReturnString = ob_get_contents();
    ob_end_clean();
    return $ReturnString;
}

SO网友:nu everest

的输出部分https://codex.wordpress.org/Shortcode_API 建议使用此模式。

function my_shortcode() {
    ob_start();
    ?> <HTML> <here> ... <?php
    return ob_get_clean();
}

结束

相关推荐

How to execute a shortcode?

我有一个WordPress选项,可以存储一些数据,例如:<h1>Header</h1> <p>Paragraph</p> [shortcodesomething/] [shortcode]Contents[/shortcode] 我正在使用显示此选项的值echo get_option(\'my_option\'));.当然,短代码不起作用,我想知道如何迫使他们做他们应该做的事情?echo do_shortcode(get_o