P粉6052337642023-07-28 00:14:02
You can try this:
In the mycustomname_link function, we added a loop to traverse the $custom_post_types array. For each custom post type, it checks if the current post type matches any name in the array. If there is a match, the rewrite rules will be applied.
Similarly, in the mycustomname_rewrites_init function, we added a loop to register the rewrite rules for all custom post types. Each custom post type will have its own rewrite rules.
With this modification, the rewrite rules will be applied to all custom post types specified in the $custom_post_types array without stopping on the first iteration. Make sure to update the $custom_post_types array with the names of all custom post types you want to include in the rewrite rule.
function mycustomname_link($post_link, $post = 0) { $custom_post_types = array('name_of_my_post', 'another_post_type', 'yet_another_post_type'); // Add all your custom post type names here foreach ($custom_post_types as $post_type) { if ($post->post_type === $post_type) { return home_url('new' .'/'. 'posts'.'/'. $post->post_name .'/'. $post->ID . '/'); } } return $post_link; } add_filter('post_type_link', 'mycustomname_link', 10, 2); function mycustomname_rewrites_init(){ $custom_post_types = array('name_of_my_post', 'another_post_type', 'yet_another_post_type'); // Add all your custom post type names here foreach ($custom_post_types as $post_type) { add_rewrite_rule('new/posts/([^/]+)/([0-9]+)?$', 'index.php?post_type=' . $post_type . '&p=$matches[1]&p=$matches[2]', 'top'); } flush_rewrite_rules(); } add_action('init', 'mycustomname_rewrites_init');