sql - 自定义帖子类型每年/每月存档

标签 sql wordpress .htaccess mod-rewrite custom-post-type

我的 Wordpress 网站中有一个自定义帖子类型“新闻”。我正在使用高级自定义字段插件向每个帖子添加元数据。

我想创建一系列新闻项目作为存档:

[2013]
    [January] => 5
[2012]
    [January] => 20
    [February] => 10
[2011]
    [April] => 30

我设法使用以下方法使其正常工作:
    global $wpdb;
    $news = $wpdb->get_results(
        "SELECT wp_posts.post_date, COUNT(wp_posts.ID) as count
         FROM $wpdb->posts
         WHERE
         wp_posts.post_type = 'news' AND
         wp_posts.post_status = 'publish' AND
         wp_posts.post_date <= CURDATE() AND
         wp_posts.post_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR)
         GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date)
         ORDER BY wp_posts.post_date DESC", 
         ARRAY_A);

    $archive = array();
    foreach ($news as $post):
        $year = date('Y', strtotime($post['post_date']));      
        $month = date('m', strtotime($post['post_date']));     
        $month_name = date('F', strtotime($post['post_date']));
        $post['url'] = 'NOT SURE ABOUT URL';
        $archive[$year][$month_name] = $post;
    endforeach;

我需要能够使用 http://example.com/2012/ 链接到特定的年份和月份和 http://example.com/2012/10/ .

由于这涉及自定义帖子类型“新闻”,我不确定如何实现?

最佳答案

为了满足您的要求,您需要修改 Wordpress 重写,以便能够捕获自定义帖子类型的年/月/等帖子数据。

您可以使用以下代码执行此操作:

/**
 * Custom post type date archives
 */

/**
 * Custom post type specific rewrite rules
 * @return wp_rewrite             Rewrite rules handled by Wordpress
 */
function cpt_rewrite_rules($wp_rewrite) {
    $rules = cpt_generate_date_archives('news', $wp_rewrite);
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
add_action('generate_rewrite_rules', 'cpt_rewrite_rules');

/**
 * Generate date archive rewrite rules for a given custom post type
 * @param  string $cpt        slug of the custom post type
 * @return rules              returns a set of rewrite rules for Wordpress to handle
 */
function cpt_generate_date_archives($cpt, $wp_rewrite) {
    $rules = array();

    $post_type = get_post_type_object($cpt);
    $slug_archive = $post_type->has_archive;
    if ($slug_archive === false) return $rules;
    if ($slug_archive === true) {
        $slug_archive = $post_type->name;
    }

    $dates = array(
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum', 'day')),
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum')),
        array(
            'rule' => "([0-9]{4})",
            'vars' => array('year'))
        );

    foreach ($dates as $data) {
        $query = 'index.php?post_type='.$cpt;
        $rule = $slug_archive.'/'.$data['rule'];

        $i = 1;
        foreach ($data['vars'] as $var) {
            $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
            $i++;
        }

        $rules[$rule."/?$"] = $query;
        $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
    }
    return $rules;
}

你会注意到我已经硬编码 news$rules = cpt_generate_date_archives('news', $wp_rewrite);代码的一部分。您可以根据需要更改此设置。

使用此代码,您应该能够导航到 http://yoursite.com/news/2013/02/并在该特定时间接收该特定帖子类型的存档列表。

为了完整起见,我将介绍如何生成每月存档小部件以利用它。
/**
 * Get a montlhy archive list for a custom post type
 * @param  string  $cpt  Slug of the custom post type
 * @param  boolean $echo Whether to echo the output
 * @return array         Return the output as an array to be parsed on the template level
 */
function get_cpt_archives( $cpt, $echo = false )
{
    global $wpdb; 
    $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR($wpdb->posts.post_date), MONTH($wpdb->posts.post_date) ORDER BY $wpdb->posts.post_date DESC", $cpt);
    $results = $wpdb->get_results($sql);

    if ( $results )
    {
        $archive = array();
        foreach ($results as $r)
        {
            $year = date('Y', strtotime( $r->post_date ) );
            $month = date('F', strtotime( $r->post_date ) );
            $month_num = date('m', strtotime( $r->post_date ) );
            $link = get_bloginfo('siteurl') . '/' . $cpt . '/' . $year . '/' . $month_num;
            $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
            array_push( $archive, $this_archive );
        }

        if( !$echo )
            return $archive;
        foreach( $archive as $a )
        {
            echo '<li><a href="' . $a['link'] . '">' . $a['month'] . ' ' . $a['year'] . '</a></li>';
        }
    }
    return false;
}

要使用此功能,只需提供自定义帖子类型的 slug,即:get_cpt_archives( 'news' ) .这将返回一组唯一的年份/日期/链接,即:
Array
(
    [0] => Array
        (
            [month] => February
            [year] => 2013
            [link] => http://yoursite.com/news/2013/02
        )

    [1] => Array
        (
            [month] => January
            [year] => 2013
            [link] => http://yoursite.com/news/2013/01
        )

)

您可以使用 foreach 循环浏览这些内容。并根据需要输出它们。

或者,您可以使用 get_cpt_archives( 'news', true )这将自动回显包裹在 <li> 中的每个项目链接到其特定文件。

输出的格式不是你想要的,所以你必须稍微调整一下才能让它显示在
Year
    Month
    Month
Year
    Month

您需要的格式。

我希望这有帮助。

关于sql - 自定义帖子类型每年/每月存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14486792/

相关文章:

mysql - 使用不同的参数重复 SQL 查询

css - 使@media 查询更具体、更集中

apache - 使用 .htaccess [#Q1.] 修改 URL

mysql - 关于插入时mysql自动增量行为

mysql - 这个 SQL 查询是如何工作的?

python - "*** Error in ` python': free(): corrupted unsorted chunks: 0x0000000000ff2460 ***"in Python 的原因及解决方法

php - 所有 WordPress 选项作为单个选项(序列化多维数组)还是多个选项?

php - 上下滚动时 WordPress 粘性 php 侧边栏

php - 在 .htaccess 中启用人类可读的 URL

php - htaccess 将除一页以外的所有页面从 html 重定向到 php