I’ve spent about 6 days trying to research and decipher a way to have a custom post type’s permalink change based on an Advanced Custom Fields(ACF) selection element. From my experiments, it’s half worked. all articles have correct permalinks that lead to the correct page setups. sadly, it seems these custom pages themselves just 404 when visited.

Can anyone tell me what’s wrong with my code? I’ve done my very best to get this far, but I don’t known enough to get that final boost to finish this system.

Here’s the relevant coding segments:

register_post_type(
    'articles', array(
        'labels' => array(
            'name' => 'Articles',
            'singular_name' => 'Article',
            'add_new' => 'Add new article',
            'edit_item' => 'Edit article',
            'new_item' => 'New article',
            'view_item' => 'View article',
            'search_items' => 'Search articles',
            'not_found' => 'No articles found',
            'not_found_in_trash' => 'No articles found in Trash',
            ),
        'public' => true,
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'revisions',
                        'thumbnail'
        ),
        'rewrite' => array('slug' => 'community/articles/%category_type%'),
        'menu_icon' => "dashicons-groups",
        'capability_type' => array('article','articles'),
        'map_meta_cap' => true,
    )
);

function rem_articles_rewrite( $post_link, $id = 0 ){
    $post = get_post($id);
    if ( is_object( $post ) ){
        $ptype=get_post_type($post);
        //Check the correct post type
        if($ptype=="articles"){
            //Here you need to get the value of the field, you have the ID of the post
            $post->ID and assign the value to $category variable
            $category=get_field('category',$post->ID);
            if( $category ){
                return str_replace( '%category_type%' , $category , $post_link );
            }
        }
    }
return $post_link;
}
add_filter( 'post_type_link', 'rem_articles_rewrite', 1, 3 );
add_filter('rewrite_rules_array', 'rem_articles_rewrite_rules');
function rem_articles_rewrite_rules($rules) {
    $newRules = array();
    $newRules['articles/(.+)/(.+?)/?$'] = 'index.php?articles=$matches[2]';
    return array_merge($newRules, $rules);
}

The intended URL is something like https://website.com/community/articles/theory/testarticle/
Any ideas what I’ve messed up on, or what needs adding?

Thanks in advance for any help!

Read more here: Custom permalink rewrite rules – how do I fix this?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: