skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. OP’s question was for the Post Slug and Paul’s answer is very specific to this use case. However, you can edit Paul’s answer very slightly to fit more scenarios. For example, if instead of the slug you wanted to Page Title. Say you’re using Divi and trying to output the page title in a ACF field. The code would look like this:

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

    My field is named "headline_text", so note you can edit that in the last line to whatever your field name is. The only other change is $post->post_title instead of ->post_name.

    I hope this is helpful to somebody. 😀

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search