I can't find links for any record type?

Please help with functions. Works only the last rule. It is the second function. How it correctly to write, that worked both rules, not just the last?

add_filter( 'post_type_link', function( $link, $post = 0 ) {

 global $post;

 if ( $post->post_type == 'projects' ) {
 return home_url( '/' . $post->ID );
 } else if ( $post->post_type == 'colors' ) {
 return home_url( '/' . $post->ID );
 } else {
 return $link;
}

}, 1, 3 );




add_action( 'init', function() {

 add_rewrite_rule( '([0-9]+)?$', 'index.php?post_type=projects&p=$matches[1]', 'top' );
 add_rewrite_rule( '([0-9]+)?$', 'index.php?post_type=colors&p=$matches[1]', 'top' );

});
July 8th 19 at 11:32
2 answers
July 8th 19 at 11:34
Solution
Let's first understand why it happens :-)

For example you have a record in projects c id == 123, and the entry in colors c id == 124
You add a rule to reg. expression ([0-9]+)?$ and you want a link and WP gave you a record with projects, and then add another rule with the same reg. expression, but want the results recording colors, a question: how do WP know that they are different record types? Answer: no, as reg. the expression is the same, WP will overwrite the previous rule last.

The conclusion is that you need to change the links to write to reg. expressions in the rules are different, for example p123 and c124 or project-123 and color-124 or something like that.
July 8th 19 at 11:36
You have the same regular season, it will fire once (the last entry, because thanks to the argument top is added to the top of the list rewrite_rules) and return true, after which all further checks stop. Usually such problems are solved by prefixes in the url:
/projects/XXX
/colors/XXX

Find more questions by tags WordPress