Home › Forums › General Issues › Add ACF Field to Permalink › Reply To: Add ACF Field to Permalink
I am looking for something similar and I managed partially. I managed to ‘construct’ a new permalink, but it’s not working, it’s forwarding to home.
I was trying to get the following permalink structure: /post-type/%post_id%-%custom_field_1%-%custom_field_2%
That I managed with the code below. But the permalink itself forwards to home instead of the post itself.
If anyone sees an error, or knows the solution, please let me know.
function register_rewrite_rules()
{
global $wp_rewrite;
$url_structure = '/my_post_type/%post_id%-%cf1%-%cf2%';
$wp_rewrite->add_permastruct('my_post_type', $url_structure, false);
}
function my_custom_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$dvp_name = get_field('dvp_name', $post_id);
$dvp_city = get_field('dvp_city', $post_id);
$rewritecode = array(
'%post_id%',
'%cf1%',
'%cf2%',
);
if ( !empty($permalink) && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$rewritereplace = array(
$post->ID,
strtolower($dvp_city),
strtolower($dvp_name),
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
} else { // if they're not using the fancy permalink option
}
return $permalink;
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.