短码输出始终在内容之前

时间:2015-06-17 作者:pee2pee

我有以下几点。当我调用它时,在页面中,页面中的内容总是在插件之后,而不是之前。能帮点忙吗?

<?php
function category_has_children($term_id)
{
    $children = get_term_children($term_id, "category");
    if (is_array($children)) {
        return $children;
    } else {
        return false;
    }
}

// Add Shortcode
function dataservices_category($atts)
{

    // Attributes
    extract(shortcode_atts(array(
        \'id\' => \'\'
    ), $atts));

    // Code
    if (isset($id)) {
        $categories = get_categories(\'child_of=\' . $id);
        foreach ($categories as $category) {
            if ($category->parent != $id) {
                echo \'<div style="margin-left:50px;">\';
                echo \'<h4>\' . $category->name . \'</h4>\';
            } else {
                echo \'<h3>\' . $category->name . \'</h3>\';
            }
            if (category_has_children($category->term_id) == false):
                echo \'<ul>\';
                foreach (get_posts(\'cat=\' . $category->term_id) as $post) {
                    setup_postdata($post);
                    echo \'<li><a href="\' . get_permalink($post->ID) . \'">\' . get_the_title($post->ID) . \'</a> </li>\';
                }
                echo \'</ul>\';
            endif;
            if ($category->parent != $id) {
                echo \'</div>\';
            }
        }
    }

}
add_shortcode(\'dataservices\', \'dataservices_category\');
?>

1 个回复
SO网友:Mitul

返回HTML而不是echo

function dataservices_category($atts)
{

// Attributes
extract(shortcode_atts(array(
    \'id\' => \'\'
), $atts));
$html = "";
// Code
if (isset($id)) {

    $categories = get_categories(\'child_of=\' . $id);
    foreach ($categories as $category) {
        if ($category->parent != $id) {
            $html .=\'<div style="margin-left:50px;">\';
            $html .=\'<h4>\' . $category->name . \'</h4>\';
        } else {
            $html .=\'<h3>\' . $category->name . \'</h3>\';
        }
        if (category_has_children($category->term_id) == false):
            $html .=\'<ul>\';
            foreach (get_posts(\'cat=\' . $category->term_id) as $post) {
                setup_postdata($post);
                $html .=\'<li><a href="\' . get_permalink($post->ID) . \'">\' . get_the_title($post->ID) . \'</a> </li>\';
            }
            $html .=\'</ul>\';
        endif;
        if ($category->parent != $id) {
            $html .=\'</div>\';
        }
    }
}
return $html;
}
add_shortcode(\'dataservices\', \'dataservices_category\');

结束

相关推荐

Apply_Filters(‘the_content’,$Content)与DO_ShortCode($Content)

假设我有一个主题选项或自定义的postmeta文本区域。现在我想执行多个短代码、一般文本、图像等。最佳实践是什么?为什么?选项1:$content = //my text area data; echo apply_filters(\'the_content\', $content); 选项2:$content = //my text area data; echo do_shortcode($content); 请告诉我哪一个是最佳实践,以及为什么。EDIT让我详细描