Pages

Thursday, December 19, 2013

Generate re-write rules for custom post type - wordpress

Please write below code in functions.php

function wp_rewrite_rules($wp_rewrite) {
    $rules = wp_generate_date_archives('CUSTOM_POST_TYPE_SLUG', $wp_rewrite);
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

add_action('generate_rewrite_rules', 'wp_rewrite_rules');
function wp_generate_date_archives($postslug, $wp_rewrite) {
    $rules = array();

    $post_type = get_post_type_object($postslug);
    $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')),
        array(
            'rule' => "([^/]+)",
            'vars' => array('name'))
        );

    foreach ($dates as $data) {
        $query = 'index.php?post_type='.$postslug;
        $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;
}

No comments: