在Wordpress短代码中执行查询


Execute Query Within Wordpress Shortcode

我有一个查询,我想把它包装在一个shortcode函数中,这样我就可以在帖子或页面中调用它。它应该拉动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中使用短代码的文章。我很感激任何能给我指引正确方向的帮助。

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

所以你可能想尝试的是:

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

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