Support

Account

Home Forums General Issues Add advanced custom fields value to a custom column in WordPress

Solved

Add advanced custom fields value to a custom column in WordPress

  • I have two different Custom Post Types, country and beach. For country, I just have a name field.

    For beach, it’s a little bit different, it has a field name and also a select with the countries that I added in my custom post type country. It’s working.

    Link to the example image: https://pasteboard.co/GYW4X7p.png

    Now I’m trying to create custom columns inside my custom post type beach like:

    Name | Country | Date

    How to get the country name inside the beaches list?

    My code now:

    function add_custom_column_to_beaches($columns) {
      return array_merge ($columns, array(
        'country' => 'Country'
      ));
    }
    
    function country_custom_column ($column, $post_id) {
      switch ($column) {
        case 'country':
          echo get_post_meta($post_id, 'country_name', true);
          break;
      }
    }
    
    add_filter ('manage_beaches_posts_columns', 'add_custom_column_to_beaches' );
    add_action ('manage_beaches_posts_custom_column', 'country_custom_column', 10, 2);

    This is the result now:

    Link to example image: https://pasteboard.co/GYW5ytB.png

    I can’t find how to retrieve the country name through the advanced custom fields. It always return a number. And when I tried to show with a print_r the variable, it doesn’t have any country_name.

    Thanks!

  • After a pause and searching better, I found this workaround:

    function country_custom_column ($column) {
        global $post;
        switch ($column) {
          case 'country':
            $field = get_field_object('country_name', $post->ID);
            echo $field['value']->post_title;
            break;
        }
      }

    Just to be sure, is this a correct way to get the field value?

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.