Custom Post Type Rewrite Rule for Author & Paging?

Hi @banesto:

I think the simple answer may be that you need your paged URL to be specified before your shorter URL, but since I didn’t test it I’m not 100% sure.

That said, I’ve always run into a lot of trouble with the 'generate_rewrite_rules' hook. I’m sure a better developer than me could make it work but for me it’s been a lot cleaner to use the add_rewrite_rule() function so that’s how I show you have to make your URLs route.

Here’s a plugin to do what you asked for (the register_post_type() call is only there to allow this plugin to work in my test install of WordPress; you can replace it with your own):

<?php
/*
Plugin Name: Dienasgramatas Urls
Version: 1.0
Author: Mike Schinkel
Author URI: http://mikeschinkel.com/
*/

if (!class_exists('Dienasgramatas_Urls')) {
  class Dienasgramatas_Urls {
    static function init() {
      $post_type="dienasgramatas" ;
      register_post_type($post_type,
        array(
          'label'           => 'Dienasgramatas',
          'public'          => true,
          'show_ui'         => true,
          'query_var'       => 'dienasgramatas',
          'rewrite'         => array('slug' => 'dienasgramatas'),
          'hierarchical'    => false,
          'supports'        => array('title','editor','custom-fields'),
        )
      );

      add_rewrite_rule("{$post_type}/([^/]+)/page/?([2-9][0-9]*)",
        "index.php?post_type={$post_type}&author_name=\$matches[1]&paged=\$matches[2]", 'top');

      add_rewrite_rule("{$post_type}/([^/]+)",
        "index.php?post_type={$post_type}&author_name=\$matches[1]", 'top');

    }
    static function on_load() {
      add_action('init',array(__CLASS__,'init'));
    }
    static function register_activation_hook() {
      self::init();
      flush_rewrite_rules(false); 
    }
  }
  Dienasgramatas_Urls::on_load();
}

Of course whenever you add rewrite rules you need to flush the rewrite rules or they simply won’t work. Ideally you don’t want to flush rules for every page load so the standard way to do it is in a plugin’s activation hook. So I created a plugin for you but feel free to just use the add_rewrite_rule() calls in your theme’s functions.php file and manually flushing your URLs by clicking “Save Changes” in the “Settings > Permalinks” section of the admin console.

Leave a Comment