0

Attempting to create a custom rewrite rule for any post that has a category of Shop. The posts use /%postname%/ but I want /shop/%postname%/ to appear in the url. Below is what I have but I can't get it working.

add_filter( 'post_link', 'custom_permalink', 10, 3 );

function custom_permalink( $permalink, $post, $leavename ) {
    // Get the categories for the post
    $category = get_the_category($post->ID); 
    if (  !empty($category) && $category[0]->cat_name == "Shop" ) {
        $permalink = trailingslashit( home_url('/' . $post->post_name ) );
    }
    return $permalink;
}

add_action('generate_rewrite_rules', 'custom_rewrite_rules');

function custom_rewrite_rules( $wp_rewrite ) {
    $new_rules['^shop/([^/]*)-([0-9]+)/?'] = 'index.php?postname=$matches[1]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

1 Answer 1

1

generate_rewrite_rules didn't work for me at all and I found posts on forums where others were having the same issue. Adding to the rewrite_rules_array did work. Below is the solution.

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 == "Shop" )
  {
      $permalink = trailingslashit( home_url('shop/' . $post->post_name ) );
  }
  return $permalink;
}

function flushRules(){
  global $wp_rewrite;
  $wp_rewrite->flush_rules();
}

function wp_insertMyRewriteRules($rules)
{
  $newrules = array();
  $newrules['^shop/(.*)$'] = 'index.php?name=$matches[1]';
  return $newrules + $rules;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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