在插件中使用the_title()和the_permalink()时遇到问题

时间:2012-02-08 22:02:31

标签: php wordpress plugins

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

我已经准备好了基本的插件文件,并且实现并测试了短代码。现在我正试图让插件引入博客的最新帖子,但我遇到了一些麻烦。当我使用the_title()和the_permalink()时,它们显示在我试图包含它们的代码之外。此外,the_content()使用_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' );

1 个答案:

答案 0 :(得分:4)

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

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

但最好只使用get_the_title - 同样适用于get_the_contentget_permalink

相关问题