开发者

In WordPress how do you create a custom post type with the author's name in the slug?

开发者 https://www.devze.com 2023-01-20 20:48 出处:网络
I am building a new WordPress theme using register_post_type to create a custom post开发者_JAVA百科 type called Listings.

I am building a new WordPress theme using register_post_type to create a custom post开发者_JAVA百科 type called Listings.

I would like each listing to have the following permalink structure:

http://www.mysite.com/post-author/listing-title

I'm not quite sure how to achieve this with the CPT controls listed in the Codex. Any help or links would be greatly appreciated!


Actually, you'll need to define your own custom URL rewrite rule to achieve this ... it's not a built-in feature of custom posts. There's a good example in the Codex that will get you started.

Here's a quick untested first-thought of how you could do this:

add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['([^/]+)/([^/]+)$'] = 'index.php?author=$matches[1]&listing-title=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'listing-title');
    return $vars;
}

This should direct any links from http://www.mysite.com/me/my-listing to http://www.mysite.com/index.php?author=me&listing-title=my-listing. Handling the query after WordPress gets ahold of it is entirely up to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消