【问题标题】:Wordpress output links to previous and next posts from custom queryWordpress 输出链接到自定义查询中的上一个和下一个帖子
【发布时间】:2016-07-04 18:42:06
【问题描述】:

我正在使用 wordpress 的高级自定义字段插件来创建一组自定义帖子类型,其中设置了日期。

我正在尝试根据自定义字段中存储的日期显示上一篇文章和下一篇文章。链接需要链接到日期设置在未来的帖子(所以不要显示日期已经过去的帖子的链接)/

我可以得到一份未来所有帖子的列表,并使用以下代码输出这些帖子;

<?php 
    $rightnow = current_time('Ymd');

    $args = array(                      
    'post_type' => 'Courses',
    'posts_per_page' => '25',
    'meta_query' => array(
        array(
            'key' => 'date_of_the_course_single_day',
            'compare' => '>=',
            'value' => $rightnow,
            )
            ),
    'meta_key' => 'date_of_the_course_single_day',
    'orderby' => 'meta_value',
    'order' => 'ASC',                                       
    'post_status' => 'publish'
); 
$posts = get_posts($args); 

foreach ( $posts as $post ) {
?>
    Output details of post here....
<?php   
}                   
?>                              

我认为我可以做的是获取当前帖子在数组中的位置,然后获取前后一个帖子的详细信息......但我不知道如何做到这一点。

我已经尝试过 wordpress 的 next_post_link 和 previous_post_link 功能,但这些功能似乎是基于帖子添加到 wordpress 的时间,而不是基于我的自定义日期字段。

我这样做是完全错误的吗?任何提示或指示将不胜感激!

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    使用WP_Query 加上paginate_links

    $rightnow = current_time('Ymd');
    
    // Query Args
    $args = array(                      
        'post_type' => 'Courses',
        'posts_per_page' => '25',
        'meta_query' => array( array(
            'key' => 'date_of_the_course_single_day',
            'compare' => '>=',
            'value' => $rightnow,
         ) ),
        'meta_key' => 'date_of_the_course_single_day',
        'orderby' => 'meta_value',
        'order' => 'ASC',                                       
        'post_status' => 'publish'
    ); 
    $query = new WP_QUery( $arg ); 
    $posts = $query->get_posts();
    
    // Paginate Args
    $page_args = array(
        'base'               => 'your_custom_page_url'.'%_%', // Make sure you got this current depending on your setup
        'format'             => '/%#%', // requires pretty permalinks
        'total'              => $query->max_num_pages,
        'current'            => 0,  
        'prev_text'          => __('«'),
        'next_text'          => __('»'),
    );
    
    foreach ( $posts as $post ) {
        // Output 
    }   
    
    echo paginate_links( $page_args );
    

    您必须验证分页参数的baseformat 是否正确,否则无法正常工作。

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多