带有‘Year’参数的快捷码

时间:2021-06-18 作者:Marcio

我想显示带有“年”参数的帖子。例如:要显示2020年的帖子,短代码应类似于[存档帖子年份=“2020”]。我尝试了下面的代码,但不起作用。“meta\\u值”可能不正确?任何帮助都将不胜感激。

谢谢

//get archived posts
add_shortcode( \'archived-posts\', \'archived_posts\' );
function archived_posts() {
$atts = shortcode_atts( array( \'year\' => date(\'Y\') ), $atts );
    $buffer = \'<h3>Post Titles</h3>\';
    $q = new WP_Query(array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => -1 ,
        \'meta_key\'       => \'post_date\',
        \'meta_value\'     => $atts[\'year\'],
        \'post_status\' => \'archive\' ,
        //\'year\' => 2021,
    ));
    while ($q->have_posts()) {
        $q->the_post();
        $buffer = $buffer.get_the_title().\'<br>\';
    }
    wp_reset_postdata();
    return $buffer;
}
**2021 6月20日编辑

我可以让代码在年份参数中工作,但现在它每年只显示一个结果。那么可能是环路断了还是什么?!请参阅下面的更新代码。

//get archived posts per year
add_shortcode( \'archived-posts\', \'archived_posts\' );
function archived_posts($atts) {
    $a = shortcode_atts( array( \'year\' => date(\'Y\') ), $atts );

    $q = new WP_Query(array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => -1 ,
        \'post_status\' => \'archive\' ,
        \'year\' => $a[\'year\'],
    ));
    while ($q->have_posts()) {
        $q->the_post();
        $buffer = \'<div class="archived-post-item"><a href="\'.get_permalink().\'">\'.get_the_title().\'</a></div>\';
    }
    wp_reset_postdata();
    return $buffer;
}
**

1 个回复
最合适的回答,由SO网友:Marcio 整理而成

在@bosco的帮助下,我找到了答案。以下是工作代码:

//get archived posts per year
add_shortcode( \'archived-posts\', \'archived_posts\' );
function archived_posts($atts) {
    $a = shortcode_atts( array( \'year\' => date(\'Y\') ), $atts );

    $q = new WP_Query(array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => -1 ,
        \'post_status\' => \'archive\' ,
        \'year\' => $a[\'year\'],
    ));
    while ($q->have_posts()) {
        $q->the_post();
        $buffer .= \'<div class="archived-post-item"><a href="\'.get_permalink().\'">\'.get_the_title().\'</a></div>\';
    }
    wp_reset_postdata();
    return $buffer;
}

相关推荐

“调用数组上的成员函数Have_Posts()”在Have_Posts()上出错;

我犯了一个最奇怪的错误。尝试显示自定义循环时,出现以下错误:Fatal error : Uncaught Error: Call to a member function have_posts() on array in /.../custom-page.php:42 Stack trace: #0 /.../wp-includes/template-loader.php(106): include() #1 /.../wp-blog-header.php(19): require_once(\'