为某些类别的帖子重写帖子URL

时间:2017-08-06 作者:garrettlynchirl

正在尝试为任何类别为Shop的帖子创建自定义重写规则。帖子使用/%postname%/ 但我想/shop/%postname%/ 显示在url中。下面是我所拥有的,但我无法让它工作。

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 个回复
最合适的回答,由SO网友:garrettlynchirl 整理而成

generate\\u rewrite\\u规则对我根本不起作用,我在论坛上发现了其他人有相同问题的帖子。添加到rewrite\\u rules\\u数组确实有效。下面是解决方案。

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;
}

结束