I have a custom post type called "expertise"
This is the url pattern I'm trying to achieve, /expertise/acf_Value/post-link/
I use relationship field to achieve the custom url part. But the post itself keep going to 404....
Pulling ACF value and create a new custom permalink
function sd_new_profile_permalink( $permalink, $post, $leavename = false ) {
if ( $post->post_type !== 'expertise' ) {
return $permalink;
}
// Get post
if ( ! $post ) {
return $permalink;
}
// Get custom info
$queries = get_posts(array(
'post_type' => 'expertise',
'meta_query' => array(
array(
'key' => 'sectors', // name of custom field
'value' => '"' . $post->ID . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE',
'posts_per_page' => 1
)
)
));
if( $queries ):
foreach( $queries as $query ):
$post_slug = $query->post_name;
// if ( ! is_wp_error( $city_info ) && ! empty( $city_info ) ) {
// $urldashreplace = str_replace( '\'', '', $city_info[ 'cityName' ] );
$urldashreplace = str_replace( ' ', '-', $post_slug );
$parent_slug = strtolower( $urldashreplace );
$child_slug = strtolower(str_replace( ' ', '-', $post->post_title ));
// $new_permalink = str_replace( array( '%postname%' ), array( $post_slug ), $permalink );
$new_permalink = get_bloginfo('url').'/expertise/'.$parent_slug.'/'.$child_slug.'/';
// print_r( $new_permalink );
return $new_permalink;
endforeach;
endif;
return $permalink;
}
add_filter( 'post_link', __NAMESPACE__ . '\\sd_new_profile_permalink', 10, 3 );
add_filter( 'post_type_link', __NAMESPACE__ . '\\sd_new_profile_permalink', 10, 3 );
Rewrite rule to avoid 404
function expertise_sector_rewrite_tag_rule() {
//?post_type=expertise&p=42
global $post;
add_rewrite_rule( 'expertise/([^/]*)/([^/]*)/?$', '?post_type=expertise&p='. $post->ID ,'top' );
}
add_action('init', __NAMESPACE__ . '\\expertise_sector_rewrite_tag_rule', 10, 0);