-1

我有一个查询,我想将它包装在一个简码函数中,这样我就可以在帖子或页面中调用它。它应该拉 4 个帖子,如下所示。trim_title()是另一个将标题限制为特定字符数的自定义函数。当我将查询(带有循环)直接插入到 php 模板中时,我已经验证了它是否有效,但我希望能够将它作为简码包含在编辑器中。

这是我目前所拥有的:

function homepage_newsfeed($atts) {
        $args = array( 'post_type' => 'post', 'posts_per_page' => 4 );
        $wp_query = new WP_Query($args);
        echo '<a href="';
        the_permalink();
        echo '">';
        trim_title();
        echo '</a>'; 
        echo '<div class="newspostdate">';
        the_time('F j, Y');
        echo '</div>';
        endif;
        endwhile;
}

add_shortcode ( 'newsfeed', 'homepage_newsfeed'); 

这是在循环内。我还尝试在函数中包含循环,如下所示:

function homepage_newsfeed($atts) {
        $args = array( 'post_type' => 'post', 'posts_per_page' => 4 );
        $wp_query = new WP_Query($args);
        if ( have_posts() ) : while ( have_posts() ) : the_post();
        echo '<a href="';
        the_permalink();
        echo '">';
        trim_title();
        echo '</a>'; 
        echo '<div class="newspostdate">';
        the_time('F j, Y');
        echo '</div>';
        endwhile;
        endif;
}

add_shortcode ( 'newsfeed', 'homepage_newsfeed'); 

我也尝试过使用 return 而不是 echo 像这样:

function homepage_newsfeed($atts) {
        $args = array( 'post_type' => 'post', 'posts_per_page' => 4 );
        $wp_query = new WP_Query($args);
        if ( have_posts() ) : while ( have_posts() ) : the_post();
        return '<a href="';
        the_permalink();
        return '">';
        trim_title();
        return '</a>'; 
        return '<div class="newspostdate">';
        the_time('F j, Y');
        return '</div>';
        endwhile;
        endif;
}

add_shortcode ( 'newsfeed', 'homepage_newsfeed'); 

这些只是我在许多其他尝试中的一小部分。我做了很多搜索以了解如何在简码中执行 php,但我的大多数搜索结果都找到了引用使用do_shortcode() 以在 PHP 中使用简码的文章。我很感激任何帮助指出我正确的方向。

4

1 回答 1

1

return返回值,这是您需要的,但也退出函数。同样在 WP 中,您有一个get_辅助函数的前缀版本,它也返回一个值而不是直接回显它。

所以你可能想尝试的是:

function myfunction(){
    $string = 'lets'; 
    $string .= ' build some string ';
    $string .= get_the_permalink();
    return $string;
}

http://php.net/manual/en/language.operators.string.php

于 2013-08-14T19:35:40.237 回答