admin管理员组

文章数量:1127084

I want to customize the permalinks structure for posts in WordPress based on their categories but only posts of one category,

The permalinks of the "android" posts category become like these:

/

and other category posts no change:

/

I try below code but get 404:

I do "Flush Permalinks"

function custom_permalinks_structure($permalink, $post, $leavename) {
    if ($post->post_type == 'post' && has_category('android', $post)) {
        $permalink = home_url('/android/' . $post->post_name . '/');
    } elseif ($post->post_type == 'post') {
        $permalink = home_url('/' . $post->post_name . '/');
    }

    return $permalink;
}

add_filter('post_link', 'custom_permalinks_structure', 10, 3);
add_filter('post_type_link', 'custom_permalinks_structure', 10, 3);

I try the below code too :

add_filter( 'post_link', 'pl_custom_permalink', 10, 3 );
function pl_custom_permalink( $permalink, $post, $leavename ) {
  if ( has_category( 'android', $post->ID) ) {
    $permalink = trailingslashit( home_url('/android/'. $post->post_name . '/' ) );
  }
  return $permalink;
}
add_action('init', 'pl_custom_rewrite_rules');
function pl_custom_rewrite_rules( $wp_rewrite ) {
  add_rewrite_rule( '^new_slug/(.*)$', 'index.php?name=$matches[1]', 'top' );
}
add_action( 'wp', function( $wp ){
    if ( ! preg_match( '#^android/#', $wp->request ) &&
        is_singular() && in_category( 'android' ) ) {
        wp_redirect( get_permalink() );
        exit;
    }
} );

本文标签: functionsCustom permalink for post of one category