【问题标题】:Having trouble using the_title() and the_permalink() in a plugin在插件中使用 the_title() 和 the_permalink() 时遇到问题
【发布时间】:2012-02-08 22:02:30
【问题描述】:

我正在尝试编写一个新插件,因为我无法找到一个完全符合我想要的可扩展性的插件。该插件的目标是能够使用简单的短代码来显示一个图像滑块,该滑块会自动填充您博客的最新帖子。

我已经准备好基本的插件文件,并且已经实现并测试了简码。现在我正试图让插件拉入博客的最新帖子,但我遇到了一些麻烦。当我使用 the_title() 和 the_permalink() 时,它们显示在我试图包含它们的代码之外。此外,the_content() 使用 the_permalink() 和 the_title() 显示一次,然后第二次显示它应该显示的位置.

你可以看到here的行为。 这是我正在使用的代码:

function slyd( $category, $slydcount ) {
    global $post;
    $tmp_post = $post;  // Create $tmp_post to empty $post once Slyd is done with it

    $args = array(
        'category'    => $category,
        'numberposts' => $slydcount
    );
    $slydposts = get_posts( $args );
    foreach( $slydposts as $post ) : setup_postdata($post);
        $post_permalink = the_permalink();  // Get the post's permalink
        $post_title = the_title();          // Get the post's title
        $post_content = the_content();      // Get the post's content - will write code to get excerpt later
        return '<h2><a href="' . $post_permalink . '">' . $post_title . '</a></h2>\n'
        . '<p>' . $post_content . '</p>';
    endforeach;
    $post = $tmp_post;                      // Empty $post once Slyd is done with it
}

// Create the shortcode
function slyd_shortcode( $atts ) {
    // $atts        ::=        array of attributes
    // examples:               [slyd]
    //                         [slyd category='slide']
    //                         [slyd slydcount='5']
    //                         [slyd theme='default']

    /* Retrieve attributes set by the shortcode and set defaults for
       unregistered attributes. */
    extract( shortcode_atts( array(
        'category'   =>  '',        // Which category(s) to display posts from
        'slydcount'  =>  '5',       // How many Slyds to display
        'theme'      =>  'default'  // Which Slyd theme to use
    ), $atts ) );

    return "<p>category = {$category}, count = {$slydcount}</p>"
    . slyd( $category, $slydcount );
}

add_shortcode( 'slyd', 'slyd_shortcode' );

【问题讨论】:

    标签: php wordpress plugins


    【解决方案1】:

    默认情况下,the_title 将打印出(回显)标题。您可以向函数传递额外的参数,以使其仅返回标题,如下所示:

    <?php the_title('', '', false); ?> 
    

    但最好只使用 get_the_title 代替 - get_the_contentget_permalink 也是如此。

    【讨论】:

    • 太棒了,这绝对是解决方案。我在 WP Codex Shortcodes 页面中读到了一些关于使用 return 而不是 echo 的内容,我只是不确定如何解决这个问题。非常感谢!
    • 那应该是get_permalink。这可能是 WordPress 中最烦人的矛盾之一。
    • Simon 是对的,它是 get_permalink。我必须对代码进行更多研究才能弄清楚这一点。
    • 我没有看到 WP 中的不一致之处我只看到当人们说这样的话和/或投反对票时缺乏研究。所有带有 get_ 的函数都是返回函数,非常适合在循环外使用。
    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多