• Resolved garrettlynch

    (@garrettlynch)


    I’m trying to create a permalink for single posts that are in a particular category called ‘Test’. So I’ve set the stub with a filter which in turn sets the permalink when the post is saved. At the moment I have it hardcoded to ‘test/post1’. Stub and permalink set just fine. I then have a rewrite rule which writes ‘test/post1/’ to ‘index.php?pagename=test/post1’ (again hardcoded just to test).

    It looks like it’s sort of working but wordpress only shows me the index with no posts (404) – so I’m seeing the all posts page rather than the single post page. Anyone know what might be wrong?

    add_filter( 'wp_unique_post_slug', 'filter_wp_unique_post_slug', 10, 4 ); 
    add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
    add_filter('init','flushRules'); 
    
    function filter_wp_unique_post_slug( $slug, $post )
    {
        // Get the categories for the post
        $category = get_the_category($post->ID); 
        if (  !empty($category) && $category[0]->cat_name == "Test" )
        {
        	$slug = 'test/post1';
        }
        return $slug; 
    };
    
    // Adding a new rule
    function wp_insertMyRewriteRules($rules)
    {
        $newrules = array();
        $newrules['(.*)/(.*)/$'] = 'index.php?pagename=test/post1';
        return $newrules + $rules;
    }
    
    // Remember to flush_rules() when adding rules
    function flushRules(){
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
Viewing 1 replies (of 1 total)
  • Thread Starter garrettlynch

    (@garrettlynch)

    This worked:

    add_filter( 'post_link', 'custom_permalink', 10, 3 ); 
    add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
    add_filter('init','flushRules'); 
    
    function custom_permalink( $permalink, $post, $leavename ) {
      $category = get_the_category($post->ID); 
      if (  !empty($category) && $category[0]->cat_name == "Test" )
      {
          $permalink = trailingslashit( home_url('test/' . $post->post_name ) );
      }
      return $permalink;
    }
    
    function flushRules(){
      global $wp_rewrite;
      $wp_rewrite->flush_rules();
    }
    
    function wp_insertMyRewriteRules($rules)
    {
      $newrules = array();
      $newrules['^test/(.*)$'] = 'index.php?name=$matches[1]';
      return $newrules + $rules;
    }
Viewing 1 replies (of 1 total)
  • The topic ‘Rewrite rule and display of post’ is closed to new replies.