How to get Relationship Field dual-column showing IDs instead of post titles in ACF plugin?

by default, in the ACF plugin, the relationship field allows the user to choose a relation with another post in the default dual column view. In my case, I am using the Relationship field in order to connect dealer post-types to products.

Since I am importing Product data from CSV, I would need to import Relationship fields as well, and I am doing this using WP All Import Pro plugin. If I try to export a product in order to create the proper CSV format, I can see all set up relationships using the Dealer post-type title. I would need to type in CSV the dealers IDs instead of their full title, because the titles could change at some point.

Is that something possible through a function? Also, apart from dealers IDs, is it possible to achieve using another IDs set up using ACF (that is to say, another ID which is not the default one assigned by WP)?

For now, I am using Post Object return format, I’ve tried with Post ID return format but does not work (I am not sure if this could work since I am trying to do something out of my knowledge…).

Thank you in advance,
nflor

ACF — AJAX populate Gallery field with a Post select

I have a post type with two fields: a Post select and a Gallery.

On Post select change, I’m getting the image IDs from several fields in that post and attempting to attach them to the Gallery field. I’m following this method (my code below), and I’m able to fetch those IDs and set the Gallery’s hidden input field value with them.

Two things are not working:

  1. the Gallery field does not visually update to display the image array
  2. the Gallery field does not store the array on post save, despite seeing the value update

This indicates to me that maybe I’m not setting the Gallery value correctly? Here is my code:

PHP

// enqueue ajax in back-end for project case study select
function enqueue_scripts_back_end(){
    wp_enqueue_script( 'ajax-script', PARENT_THEME_URI.'admin/case-study.js', array('jquery'));

    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )) );
}
add_action('admin_enqueue_scripts','enqueue_scripts_back_end');

// ajax function works with admin/case-study.js
add_action( 'wp_ajax_case_study_images', 'case_study_images' );
function case_study_images() {
    global $wpdb;
    // get project ID from ajax
    $projectID = intval( $_POST('projectID') );
    if ($projectID !== false) {
        // start an image array
        $project_images = array();
        // check for hero cover image
        $cover_image = get_field('cover_image', $projectID);
        if ($cover_image) array_push($project_images, $cover_image('ID'));
        // check for slideshow images
        $project_slideshow = get_field('project_slideshow', $projectID);
        if ($project_slideshow): foreach ($project_slideshow as $image):
            if (!in_array($image('ID'), $project_images)) array_push($project_images, $image('ID'));
        endforeach; endif;

        // if there are images in array, send array to case study gallery
        if (!empty($project_images)):
            echo json_encode(
                array('project_images' => $project_images)
            );
        endif;
    }
    wp_die();
}

JS

jQuery(document).ready(function($) {

    // get case study select (must be set to return ID)
    var projectField = acf.getField('field_60ecc34dc2679');
    // get current gallery
    var gallery = acf.getField('field_60ecc370c267a');
    // when project field changes...
    var projectID, galleryCount;
    projectField.on('change', function( e ){
        galleryCount = gallery.val();
        // console.log('galleryCount',galleryCount);
        // if gallery has images
        if (galleryCount !== false) {
            console.log('gallery has '+galleryCount.length+' images');
        }
        // if gallery is empty
        else {
            console.log('gallery has no images');
            // get project ID and check for images (see case_study_images in functions.php)
            projectID = projectField.val();
            $.ajax({
                url: ajax_object.ajax_url,
                type : 'post',
                data: {
                    'action': 'case_study_images',
                    'projectID': projectID
                },
                dataType: 'json',
                success: function( data ) {
                    console.log('ajax data', data);
                    if (data) {
                        // attach image IDs to hidden Gallery field
                        $('input(name="acf(field_60ecc370c267a)")').val(data.project_images);
                        // gallery.trigger('change'); // testing, does nothing
                        // $(document).trigger('acf/update_field_groups'); // testing, does nothing
                    }
                }
            });
        }
    });
});

I have a fallback which makes all of this work with update_field via acf/save_post in functions, but I’d really love to be able to see this happen dynamically on select!

Save ACF relationship (name) value to ACF text field

I try to achieve the following.
I have two post types, “projects” & “kuenstlerinnen” (artists)
Within the post type “projects”, there’s an ACF relationship field setup, connecting these two to together → “project_to_kunstlerin”

The post-type “künstlerinnen” (Artists) contains two ACF text fields:
first-name (“artist_vorname”) & Last- or Group-Name (“artist_nachname”). There is a code snippet running, which saves both fields to the title → “artist_vorname””artist_nachname”

I know would like to have a hidden text field within the projects post type, which is automatically populated with the first value of the “project_to_kunstlerin” field. It should only use the last name field. The reason I try to get this to work, is that I can order by this hidden field, so I get the posts ordered by the last name of the artist.

So far I come up with the following code-snippet:

<?php

//Make special artist field autosave for sorting
function write_artist_name_to_hidden( $post_id ) {
    $post_type = 'projects'; //custom post type for events
  
    //Check if we are saving correct post type
    if( get_post_type( $post_id ) != $post_type)
      return;
  
    //Check it's not an auto save routine
    if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
      return;
    
    // get the artist id  of the post. Note this is in a relationship field
    $nameofartist = get_post_field ('project_to_kunstlerin', $post);
    
  
    // update the artist value 
    update_field( 'project_kunstlerin_nach_name_sort', $nameofartist, $post_id );
  }
  add_action('save_post', 'write_artist_name_to_hidden');

In the backend, it now populates the destination ACF field with:

One artist: “(“37″)”
Two artists: (“37″,”38”)

These are the IDs.

How can I get another value there instead of the post id?

In theory, it must be something like:

  1. Check with IDs are in the “project_to_kunstlerin” relationship field.
  2. Take the first ID.
  3. Look up, which value is stored in “artist_nachname” of ID in post type “kuenstlerinnen”

Maybe anybody of you has an idea how to get this to work?
Your help is highly appreciated!

filters – ACF Relationship Previous Next links of CPT

I have a CPT for artworks with custom taxonomy for artists. Then I have another CPT for artists. The artist pages are basically the the page title (artist name) and a relationship field where you add the artist’s artwork from the artworks CPT where you can filter by the custom taxonomy (since there are 50+ artists and 100s of artworks).

Each artwork is its own page as mentioned. When you click on the artwork from an artist page, we want to have the option of going to the next or previous artwork based on the order displayed on the artist page as determined by the order you set from its relationship field.

I’ve tried many solutions but none have worked yet. The only way I even get a hint of success is by adding a ACF field to the artworks post type that selects the artist post type via a post object field. I was using THIS PAGE as my guide.

There seems to be an issue with the following code. I’m note sure how $current_post_id applies to the array_search. If I print_r $current_index nothing appears. Same goes for $prev_module and $next_module. However, if I print_r $module_ids the array appears as it should in the order I set on the Artist page in the Relationship field. $first_module and $last_module show the correct IDs too. I just can’t seem to get the current post ID to then determine next and previous.

// create empty array for module ids
$module_ids = array();
             
// loop through modules and add them to array
foreach( $modules as $module ) :
    $module_ids() = $module->ID;
endforeach;
             
// get the current index
$current_index = array_search( $current_post_id, $module_ids );
             
// find the prev/next items
$prev_module = $current_index - 1;
$next_module = $current_index + 1;
             
// find first and last modules
$first_module = $module_ids(0);
$last_module = end($module_ids);

wp query – display ACF repater field in archive page

I created ACF repeater field for custom taxonomy terms. Repeater consist of two field “Question” and “Answer” . By this way I want to create FAQ section for each taxonomy term.
Thought I can show other custom fields easily in archive field, But I could not succeded with repeater field . Please help me.

$term = get_queried_object();
$meta = get_field('test', $term);
but when want to output the acf repeater have no success.

$term = get_queried_object();
if (have_rows('faq', $term)) :
    while (have_rows('faq', $term)) : the_row();
        echo get_sub_field('question');
        echo get_sub_field('answer');
    endwhile;
endif;

ACF update fields

I have created a field with acf that is a number field to be used as a counter.

In functions.php i have create my shortcode function and has this part:

<a href="https://myurl.com/wp-content/themes/child/dl.php?href=<?php echo esc_url( $link_url ); ?>&id=<?php echo $postid; ?>" target="_blank">Download</a>

And in my dl.php file i only have this:

<?php if($_GET('href')&&$_GET('id')) {  
$count = (int) get_field('download_counter',$_GET('id'));   
$count++;   
update_field('download_counter', $count);
header('Location: ' . $_GET('href'));
}else {
header('Location: https://myurl.com/');
}

but i get "HTTP ERROR 500" Page not found!

before doing that, in my function.php i puted the same code and with every refresh of the page the counter worked.

Does anyone knows why it doesn’t work in the dl.php file?

ACF FIELD ERROR ON ADMIN PANEL

I have the following problem showing when get access to acf field on admin panel

Error message: Cannot load edit.php?post_type=acf-field-group.

How to fix it ?

advanced custom fields – ACF select acf/load_field filter to render choices with option groups

I am using ACF select field and allowing multiple choices, with lazy loading etc.

Here is my ACF load_field filter fired within my class construct (hence the $this usage)…

add_filter('acf/load_field/name=provision', ( $this, 'load_provision_choices' ));

Here is the class function php in reference to the code above…

/**
 * @param $field
 * @return array
 * @noinspection PhpUnused
 */
public function load_provision_choices( $field ) {

    // current site key (purchase)
    $site = Site::key();

    // reset choices
    $field('choices') = ();

    // add our place holder
    $field('placeholder') = 'Select provisional items...';

    // if we have site key
    if($site) {

        // switch to site (data)
        Site::switch('data');

        // our post type option group breaks
        $groups = (
            'data-packaging' => 'Packaging',
            'data-confectionery' => 'Confectionery',
            'data-components' => 'Components',
            'data-shipping' => 'Shipping',
            'data-materials' => 'Materials'
        );

        // loop through groups as type => label
        foreach ($groups as $type => $label) {

            // provision args
            $args = (
                'numberposts'   => -1,
                'post_type'     => $type,
                'orderby'       => 'title',
                'order'         => 'ASC',
                'post_status'   => 'publish'
            );

            // get current data posts
            $provisions = get_posts($args);

            // if we have provisions
            if($provisions) {

                // foreach provisions
                foreach ($provisions as $provision) {

                    // add provision to field select choices
                    $field('choices')($label)($provision->ID) = $provision->post_title;

                }

            }

        }

        // switch to site (purchase)
        Site::switch($site);

    }

    dump($field);

    // return the field
    return $field;

}

Which returns this…

Array
(
    (ID) => 0
    (key) => field_60a44ccc4e40a
    (label) => Line Items
    (name) => provision
    (prefix) => acf
    (type) => select
    (value) => 
    (menu_order) => 0
    (instructions) => Select line item or items for this provision included in contract agreement.
    (required) => 1
    (id) => 
    (class) => 
    (conditional_logic) => 0
    (parent) => field_60a44b724e409
    (wrapper) => Array
        (
            (width) => 
            (class) => 
            (id) => 
        )

    (choices) => Array
        (
            (Packaging) => Array
                (
                    (24) => Maxi Round Pot
                )

            (Confectionery) => Array
                (
                    (89) => The Jelly Bean Factory
                )

        )

    (default_value) => Array
        (
        )

    (allow_null) => 0
    (multiple) => 1
    (ui) => 1
    (ajax) => 1
    (return_format) => value
    (placeholder) => Select provisional items...
    (_name) => provision
    (_valid) => 1
)

But unfortunately the loaded select field in question shows no values.

This is what the ACF field editor select choices show…

enter image description here

Does anyone have insight on my error above and how to pre load select options with option group divisions in ACF select choice array.

Thanks in advance!

wp query – WP Admin Dropdown List Filter for custom (ACF) field on custom post type(s)

I have a custom ACF field of type = user called “visible_to”. This field is set to pull in user_id for all subscriber roles. The admin can select which subscribers a custom post is visible to. For example, add new “resource” custom post type, then choose the user_id the post is visible to. Only that logged in user can see it. (If left blank then all users can see it).

enter image description here

A custom column for this field is already added using the manage_{$post_type}_posts_columns filter. Next I want to add a dropdown list filter for the same field.

enter image description here

My code is based on the closest solution to my problem found here: Filter by custom field in custom post type on admin page

Problem:
My problem revolves around my lack of understanding $query and parse_query filter. It is two-fold:

  1. The query results are pulling the meta value, as expected, but I need to convert this to user_id as a label that the logged in user can understand. I’m not sure the best way to do this. I previously tried changing my query to return user_id from wp_users but I cannot join wp_users to wp_posts. Plus that did not help with problem 2 below.
    enter image description here
  2. The filter is not currently working. All posts are returned, regardless of the list item selected.

Any help is much appreciated.

My code below.

    add_action('restrict_manage_posts', 'myehs_visible_to_dropdown');
    function myehs_visible_to_dropdown($post_type){
        
        global $wpdb;

    //Only add dropdown to the appropriate Custom Post Types
        if( $post_type !== 'resource' && $post_type !== 'manual' && $post_type !== 'news')
            return;

    //Grab data for the dropdown from the DB
            $query = $wpdb->prepare('
            SELECT DISTINCT pm.meta_value FROM %1$s pm
            LEFT JOIN %2$s p ON p.ID = pm.post_id
            WHERE pm.meta_key = "%3$s" 
            AND p.post_status = "%4$s" 
            AND p.post_type = "%5$s"
            ORDER BY "%3$s"',
            $wpdb->postmeta,
            $wpdb->posts,
            'visible_to', // Meta key
            'publish',         
            $post_type,
            'visible_to'
        );
        $results = $wpdb->get_col($query);

    //Ensure there are options to show
        if(empty($results))
            return;

    //Get selected option if there is one selected
    if (isset( $_GET('visible') ) && $_GET('visible') != '') {
        $selectedName = $_GET('visible');
    } else {
        $selectedName = -1;
    }

    //Grab all of the options that should be shown
        $options() = sprintf('<option value="-1">%1$s</option>', __('All Visible To'));
        foreach($results as $result) :
        if ($result == $selectedName) {
        $options() = sprintf('<option value="%1$s" selected>%2$s</option>', esc_attr($result), $result);
            } else {
                $options() = sprintf('<option value="%1$s">%2$s</option>', esc_attr($result), $result);
            }
        endforeach;

    //Output the dropdown menu
        echo '<select class="" id="visible" name="visible">';
        echo join("n", $options);
        echo '</select>';

    }

    // Make selected dropdown return results
        add_filter( 'parse_query', 'myehs_filter_by_visible_to' );
        function  myehs_filter_by_visible_to($query) {
        global $pagenow;
        $current_page = isset( $_GET('post_type') ) ? $_GET('post_type') : '';
            // If we are in Admin and on the right post type and dropdown selection is made
            if ( is_admin() && 
                $pagenow == 'edit.php' && 
                $current_page == array('resource','manual','news')  && 
                isset( $_GET('visible') ) && $_GET('visible') !='' &&
                $query->is_main_query()) 
                // Return only posts where visible to matches the selection
                {
                    $query->query_vars('meta_key') = 'visible_to'; 
                    $query->query_vars('meta_value') = $_GET('visible');
                    $query->query_vars('meta_compare') = '=';
                }
        }

categories – I want to show the category image (set with ACF) inside a loop that shows it inside the cards, how can I do it?

<?php get_header(); 

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

$id_cat = array('parent' => $cat_id);
$categories = get_categories( $id_cat );

// Get particular category’s object info.
$queried_object = get_queried_object();

// (Optional depending on desired outcome) If you wanted to get the type of taxonomy.
$taxonomy = $queried_object->taxonomy;

// (Optional depending on desired outcome) If you wanted to get the associated ID.
$term_id = $queried_object->term_id;

// Get image ID for this field.
$attachment_id = get_field( ‘category_image’, $queried_object );

// URL of image at specific size.
$image = $attachment_id(‘sizes’)(‘chosen-image-size’);

?>
<section class="p-5">
    <div class="container">
        <div class="row text-center">
            <h3><?php single_cat_title(); ?></h3>
            <p><?php category_description(); ?></p>
        </div>
    </div>
</section>

<section>
    <div class="container animated">
        <div class="row d-flex" data-masonry='{"percentPosition": true }'>

‘.’
term_id ).'”>’ .$category->name.”.’

‘;
}

?>


In evidenza

            <?php while(have_posts()): the_post(); ?>
                <div class="col-6 col-md-4 col-xl-3 mb-4">
                    <div class="card text-center">
                        <a href="<?php the_permalink() ?>">
                                        <!-- Immagine Articolo -->
                            <?php if(has_post_thumbnail()): ?>  
                                <div class="m-1"><?php the_post_thumbnail('thumbnail') ?></div>
                            <?php endif; ?>
                        </a>    
                        <div>
                            <h3><?php the_title(); ?></h3>
                            <p><?php the_excerpt(); ?></p>
                        </div>
                        <a href="<?php the_permalink() ?>" class="btn btn-outline-dark btn-sm">Continua a
                            Leggere</a>
                    </div>
                </div>
                    <?php endwhile; ?>
                    <?php else: ?>
                        <?php echo wpautop('ops.. non ho trovato nulla');?>
                    <?php endif; ?>
        </div>
    </div>
</section>