1

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:

https://example.com/android/mypost/

and other category posts no change:

https://example.com/mypost2/

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;
    }
} );
1
  • I saw post_type_link in your code, so are you doing this for both the post type post and custom post types? Because if so, then there'd be a conflict when visiting the single post page, because posts in different post types can share the same slug. So for example, the post types post and phones could have a post with the slug foo, which means, if they're both in the "android" category, then what should be displayed when viewing https://example.com/android/foo - i.e. how would you determine which foo post should be displayed?
    – Sally CJ
    Jan 18 at 5:00

0

Your Answer

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

Browse other questions tagged or ask your own question.