7

Hi and thanks for reading.

I want to insert the post author into my custom post type slug.

Example: http://example.com/charts/%author%/

Any ideas how to accomplish this?

Here is my custom post type:

register_post_type('charts', array(
  'label' => 'Charts',
  'description' => '',
  'public' => true,
  'show_ui' => true,
  'show_in_menu' => true,
  'capability_type' => 'post',
  'hierarchical' => false,
  'rewrite' => array('slug' => '/charts/author'),
  'query_var' => true,
  'supports' => array(
    'title',
    'editor',
    'trackbacks',
    'custom-fields',
    'comments',
    'author',
  ),
  'labels' => array ( 
    'name' => 'Charts',
    'singular_name' => 'Charts',
    'menu_name' => 'Charts',
    'add_new' => 'Add Charts',
  ),
));

bless jnz

8

I figured out a solution and decided I'd share because its nice to be nice. This works for me and is based on a solution by Jonathan Brinley. If anyone has any suggestions or corrections please feel free to let me know.

First, create your custom post type and set it up like this (this is just an example, remember to make it fit your own needs. The slug setting is important!)

register_post_type('charts', array( 
  'label' => 'Whatever',
  'description' => '',
  'public' => true,
  'show_ui' => true,
  'show_in_menu' => true,
  'capability_type' => 'post',
  'hierarchical' => true,
  'rewrite' => array('slug' => '/whatever/%author%'),
  'query_var' => true,
  'supports' => array(
    'title',
    'editor',
    'trackbacks',
    'custom-fields',
    'comments',
    'author'
  ) 
));

Next, setup a function for your filter (in functions.php):

function my_post_type_link_filter_function($post_link, $id = 0, $leavename = FALSE) {
  if (strpos('%author%', $post_link) === FALSE) {
    $post = &get_post($id);
    $author = get_userdata($post->post_author);
    return str_replace('%author%', $author->user_nicename, $post_link);
  }
}

Then activate the filter (also in functions.php):

add_filter('post_type_link', 'my_post_type_link_filter_function', 1, 3);

Like I said, I'm not sure this is the best way to do this but it works for me :)

|improve this answer|||||
  • That’s an interesting solution. Please mark your question as answered. – fuxia Feb 25 '12 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.