Search code examples
wordpressadvanced-custom-fieldscustom-wordpress-pages

Add the default value of page slug to a custom field in advanced custom fields


So I installed the Advanced custom fields plugin in wordpress and setup a custom field called page_slug and want to set the default value to the page slug of each page, is that possible?

enter image description here


Solution

  • This will set the value of the field to the page slug if it's empty so on creation of the page when you hit publish.

    function my_acf_load_value( $value, $post_id, $field ) {
        global $post;
        if(($value === null || trim($value) === '')) {
            $value = $post->post_name;
        }
        return $value;
    }
    add_filter('acf/load_value/name=page_slug', 'my_acf_load_value', 10, 3);
    

    If you change the slug after the post has been created this won't update teh field as it's checking for null. If you want it to always be updated and don't intend the field value to be anything other that the page slug then you can remove the if statement.

    I hope I've answered the question correctly as it's difficult to know why you'd need this as you should be able to use.

    $post->post_name