I'm new to PHP and I'm trying to do some rewrite rules to change the structure of some links. I tried some found code and this code only works for the first custom post type I specify in the for loop. I want to make a for loop that changes the links for all custom post types I specify (the names of these post types are in an array), here is my rewrite rule code:
function mycustomname_link($post_link, $post = 0) { if($post->post_name === $name_of_my_post) { return home_url('new' .'/'. 'posts'.'/'. $post->post_name .'/'. $post->ID . '/'); } else{ return $post_link; } } add_filter('post_type_link', 'mycustomname_link', 1,3); function mycustomname_rewrites_init(){ add_rewrite_rule('new/posts/([^/] )/([0-9] )?$', 'index.php?post_type=nature_posts&p=$matches[1]&p=$matches[2] ', 'top'); flush_rewrite_rules(); } add_action('init', 'mycustomname_rewrites_init');
I see there is a return statement in the function so it will only apply the rewrite rules on the first iteration and the first custom post name, how can I make a for loop so that it works for me all post_names specified and not stop on the first iteration?
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.