plugins - Post URL based on Custom Post Types variables

admin2025-06-04  2

I would like to create custom post URL from Custom Post Types variable. I considered a way to do that:

In Permalinks settings, I see there are some default tags you can choose to compound URL from (%year%, %post_id%, %postname% etc.). I was thinking about creating custom tag you can include(e. g. %mytag%) or rewriting existing one. That tag should be automatically generated based on variables from CPT.

So the final tag should be:

 %mytag% = $variable1 .  '_' . $variable2

Is this possible to do? Maybe there is much easier way to do that, so please let me know how would you solve this issue.

Thank you very much for your answers!

I would like to create custom post URL from Custom Post Types variable. I considered a way to do that:

In Permalinks settings, I see there are some default tags you can choose to compound URL from (%year%, %post_id%, %postname% etc.). I was thinking about creating custom tag you can include(e. g. %mytag%) or rewriting existing one. That tag should be automatically generated based on variables from CPT.

So the final tag should be:

 %mytag% = $variable1 .  '_' . $variable2

Is this possible to do? Maybe there is much easier way to do that, so please let me know how would you solve this issue.

Thank you very much for your answers!

Share Improve this question edited Jan 16, 2019 at 17:01 mrben522 1,7131 gold badge12 silver badges17 bronze badges asked Jan 16, 2019 at 16:45 PandaBoiiPandaBoii 1 2
  • What are you expecting this to look like when it works? is it just a front before post URLs for your CPT or are you expecting this to change on each individual post? – mrben522 Commented Jan 16, 2019 at 16:52
  • I expect it to change on every post. Lets say I have Custom Post Type "Cars" with Advanced Custom Fields "Brand" ($variable1) and "License Plate" ($variable2). I fill Brand="Ford" and License Plate="ABCDE". The URL of the post should look like website/cars/ford-ABCDE. Hope this is clear. – PandaBoii Commented Jan 16, 2019 at 17:32
Add a comment  | 

1 Answer 1

Reset to default 1

Instead of creating a new tag, I would suggest just writing code to create the slug on a per-post basis using ACF's save_post function.

//Update Cars slug field:
function wpse_post_slug_updater( $post_id ) {

    if( get_post_type() == 'cars') {
        $my_post = array();
        $my_post['ID'] = $post_id;
        $my_post['post_title'] = esc_html(get_the_title($post_id));

        $my_new_slug = get_field('brand') . ' ' . get_field('license_plate');
        if(!empty($my_new_slug)){
            $my_post['post_name'] = sanitize_title($my_new_slug);
            wp_update_post( $my_post );
        }
    }

}

// run after ACF saves the $_POST['fields'] data
add_action('acf/save_post', 'wpse_post_slug_updater', 20);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749004665a315544.html

最新回复(0)