【问题标题】:Wordpress : using template tags and functions in shortcodesWordpress:在简码中使用模板标签和函数
【发布时间】:2011-01-08 02:59:39
【问题描述】:

我正试图弄清楚为什么我的简码不起作用 - 任何人都可以看到原因(对于糟糕的格式表示歉意,似乎无法让这个简码正确显示)?

出于某种原因,该代码在我的简码上方运行。不确定我是否完全理解如何在简码中使用模板标签/WP 函数,因为我相信您需要在函数的开头使用 get_ 之类的东西才能在简码中的变量中返回它。有人可以帮忙吗?

谢谢

osu

/* News from Blog category only - category 3 */

add_shortcode( 'latestblogposts', 'osu_latestblogposts' );

function osu_latestblogposts() {
    $start = '<div class="widget widget_osu_blog">';
    $start .= '<a title="Subscribe to our RSS feed" href="/feed?cat=3" class="rss"><img alt="RSS" src="' . get_bloginfo('template_directory') . '/images/ico-rss-big.png"></a>';
    $start .= '<div>';

    $my_query = new WP_Query('category=3&showposts=3');
    while ($my_query->have_posts()) : $my_query->the_post();
        $inner = '<div class="item"><a href="' . get_permalink() . '" title="';
        $inner .= printf( esc_attr__( 'Permalink to %s', 'inspire' ), the_title_attribute( 'echo=0' ) );
        $inner .= '" rel="bookmark" class="title">' . the_title() . '</a>';
        $inner .= '<p class="post-meta">';
        $inner .= '<span class="small">by</span> <span class="post-author"><a title="Posts by ';
        $inner .= the_author();
        $inner .= '" href="' . the_author_posts_link() . '">' . the_author() . '</a></span>';
        $inner .= '<span class="small">on</span> <span class="post-date">';
        $inner .= get_the_date('d/m/Y') . '</span></p>';
        $inner .= the_excerpt() . '</div> <!-- End div.item -->';
    endwhile;

    $end = '</div>';
    $end .= '</div> <!-- End div.widget_osu_blog -->';

    $latestblogposts = $start . $inner . $end;
    return $latestblogposts;
}

【问题讨论】:

    标签: wordpress function shortcode


    【解决方案1】:

    如果我对您的理解正确,您需要使用可选参数调用函数以获得返回值,而不是直接回显它。例如,使用 the_title(),您有 3 个可选参数,第三个设置输出(默认为 true)。 the_title().

    对于其他值,您需要更改您调用的函数。 the_author() 总是显示(回显)值,你需要调用 get_the_author() 来代替。

    【讨论】:

    • 您还需要将“the_excerpt()”更改为 get_the_excerpt()。
    • 您好 AJweb,感谢您回复我 - 您一针见血。那么在大多数这些事情之前使用 get_ 是一个简单的例子吗?我假设我需要检查这些功能中的每一个的 codex 以查看它是否可用。我相信还有一种更简洁的方法可以在短代码中添加循环!
    • 对了,恐怕你需要检查codex中的函数,并非总是在函数名称中添加get_(the_title()就是一个例子)。跨度>
    • 我想你总是可以使用 ob_start() 和 ob_get_contents() 来捕获输出,尽管我只在没有其他解决方案的情况下使用输出缓冲,如果只是因为额外的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2014-03-20
    • 2011-07-13
    • 1970-01-01
    • 2013-11-21
    • 2019-07-05
    相关资源
    最近更新 更多