
There is not mechanism in WP that will allow you to query posts based on the meta values of a related post. To query posts all values must be associated with the posts you want to query.
This means that you need to
– create an acf/save_post hook that
– gets the relationship field
– gets the values for the fields on the related post
– saves those values to the post currently being saved

Hi @atise
If you’re creating an image field, when you add the code to your template (please see here), you can add the class to your img tag.
Once you add the class, say ‘responsive-img’, you can then reference that in your CSS.
So:
<?php
$image = get_field('image');
if( !empty( $image ) ): ?>
<img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" class="responsive-img" />
<?php endif; ?>
Then in your CSS:
.responsive-img {
/*whatever you need to add*/
}

Hi @liqid
Ok, so hardcoding works, which means it must be when outputting the field that additional code(?) is being added.
If you hard code it and it works, copy the line into something like notepad
Then, add your code back in, inspect it and copy the line into notepad
If you compare them, does the latter one have anything different? If so, what is the difference?

Hi @pmmg
I think I’d be inclined to do something like:
$current_url = get_permalink();
$state_url = get_field('state_url');
$product = get_title();
echo '<a href="$current_url.$state_url.'-'.$product">Link</a>';
Or
$site_url = get_site_url();
$state_url = get_field('state_url');
$product = get_title();
echo '<a href="$site_url.'/product/'.$state_url.'-'.$product">Link</a>';
May need a little tweaking but should get you underway!

Hi @avahidesign
I guess you can approach it in different ways.
If you’re looping through your CPT, you can simply echo out the custom field if it exists:
<?php
global $wp_query;
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 10,
'post_type' => 'your-cpt',
'paged' => $paged
);
$wp_query = new WP_Query($args); ?>
<?php if ($wp_query->have_posts()) : ?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post();
$position = get_field('position');
?>
Your loop content
<?php
if($position):
echo $position;
endif;
?>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>
Or you can add ACF fields to a custom excerpt:
// Custom Excerpt function for Advanced Custom Fields
function custom_field_excerpt() {
global $post;
$text = get_field('position'); //Replace 'your_field_name'
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = 20; // 20 words
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('the_excerpt', $text);
}
Then in your loop, display the custom excerpt:
echo custom_field_excerpt();

Hi @liqid,
What does ‘social_icon_static’ return?
If you hard code that line (so do away with the get_field part), does it still display outside the tag? If not, then it’s how the include is working.
I’m sure I had similar once before with something. If you declare the get_field above, then include the $var, does that work:
if ( $depth == 0 ) {
$social_icon_static = get_field('social_icon_static', $item);
$item_output .= '<div class="uk-inline-clip uk-transition-toggle uk-animation-toggle social-icon-container" tabindex="0">
<svg class="uk-animation-slide-top uk-animation-reverse social-top" width="16px" height="16px"> '. get_template_part( 'assets/images/svg/inline', $social_icon_static) .' </svg>
<svg class="uk-transition-slide-bottom social-bottom" width="16px" height="16px"> '. get_template_part( 'assets/images/svg/inline', get_field('social_icon_hover', $item)) .' </svg>
</div>';
}
If hard coding still blows it out, then it must be non ACF related. Sometimes, using the browser inspect tool can help as you can play about with it, then adjust the code accordingly.

Hi @unbekannter
The below will output the selected checkboxes into an array:
$values = array();
$time = get_field('second-field');
foreach ($time as $second) {
$values[] = '"'.$second.'" => 0';
}
echo implode(',', $values);
Do you need it as an associative array? I’m trying to work out it out.
You asked for checkboxes to be an array but the example you give of how it needs to be is more like an associative array (I believe but could be wrong!).
Judging from the way Adam Balée’s code augments the SQL query, it appears that the term names are already in the post meta table. Here are the two PHP statements in his code that modify the query (they are in separate functions, but clearly end up in the same piece of SQL):
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );

I’ve done something similar with Gravity forms, whereby someone would submit content and I needed to use the added image field to set the featured image on the new post.
The code used this:
$upload_path = rgar($entry, '11');
if (!empty($upload_path)){
$attachmentid = wp_create_image_id($upload_path, $member_post_id);
$setfeatimg = set_post_thumbnail($member_post_id, $attachmentid);
}
Obviously, you would need to alter from a gravity form field to your.
$member_post_id was the post ID I needed to add the image to
function wp_create_image_id( $image_url, $parent_post_id = null ) {
// Bail if the image url isn't valid
if( empty( $image_url ) || ! esc_url( $image_url ) )
return false;
// Escape the url, just to be save
$image_url = esc_url( $image_url );
// Cache info on the wp uploads dir
$wp_upload_dir = wp_upload_dir();
// get the file path
$path = parse_url( $image_url, PHP_URL_PATH );
// File base name, e.g. image.jpg
$file_base_name = basename( $image_url );
// Full path, set up to work with a WP in a subdirectory or default location
if( site_url() != home_url() ) {
$home_path = dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) );
} else {
$home_path = dirname( dirname( dirname( dirname( __FILE__ ) ) ) );
}
// Remove the trailing slash on the home path
$home_path = untrailingslashit( $home_path );
// Combine the two to get the uploaded file path
$uploaded_file_path = $home_path . $path;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( $file_base_name, null );
// error check
if( !empty( $filetype ) && is_array( $filetype ) ) {
// Create attachment title - basically, pull out the text
$post_title = preg_replace( '/\.[^.]+$/', '', $file_base_name );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $uploaded_file_path ),
'post_mime_type' => $filetype['type'],
'post_title' => esc_attr( $post_title ),
'post_content' => '',
'post_status' => 'inherit'
);
// Set the post parent id if there is one
if( ! is_null( $parent_post_id ) && absint( $parent_post_id ) )
$attachment['post_parent'] = absint( $parent_post_id );
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $uploaded_file_path );
//Error check
if( !is_wp_error( $attach_id ) ) {
//Generate wp attachment meta data
if( file_exists( ABSPATH . 'wp-admin/includes/image.php') && file_exists( ABSPATH . 'wp-admin/includes/media.php') ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
} // end if file exists check
} // end if error check
return $attach_id;
} else {
return false;
} // end if $filetype
} // end function prg_create_image_id
If you need to get the image path, please read this forum post

Hi @miksynder
You would need to query your posts to see if your custom field exists, something like:
<?php
$args = array(
'post_type' => array('post', 'page'),
'posts_per_page' => 10,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'start_date',
'compare' => 'EXISTS',
),
),
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<h2>Amazing Events List</h2>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $start_date = get_field('start_date');?>
<li>
<a href="<?php the_permalink(); ?>">
<?php if($start_date): echo $start_date; endif; ?>
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>

The featured image for a post is stored as a post ID (attachment ID), this means that it is an image in the media library and this is required. In order to do this you would need to download and insert the image into media. see media_sideload_image()
So you want to create a taxonomy based on the location added to a post?
Right!
Is the new term supposed to be added to the post?
Yes, the terms should be stored in the post. Term_relation or what it is called.
How will this be used?
It will be shown on the single post and so the visitor can click on it and see what other posts are in the state, city or post_code.
So, I just want to add the google Map details, to my existing taxomonies – under the hood, automatic, the User does not have to do anything.
Denis

A taxonomy field only stores the term ID, it does not store the them name or any other information related to the term as part of post meta. If you want to search posts by term names then you need to copy the term name(s) to some post meta field when the post is updated so that it is available for searching. Either this or your custom search must include a taxonomy query and I’m not sure how you’d accomplish that.

I don’t really have enough information. You said you want to add these values to a taxonomy, so that’s what I’m going on.
But how do I put the info $location[ ‘city’ ] and $location[ ‘state’ ] into the Taxonomies.
I would need more information on what this means

update_field( 'new_spot_city', $location[ 'city' ], $post_id );
$post_id needs to be altered to the correct value for the taxonomy term you want to save the values to. This can be a term object or a string "term_{$term_id}"
Thank you for your reply.
I did try that. Interestingly, when the field in question is of type: Select, it returns an object every time. However, if the field is of type: text, it only returns the object once. Then Null (false) for the rest of the loop.

I’ve used the below which grabs values from an option page, then creates a CSS file and enqueues it:
###################################################
# Create Custom CSS
###################################################
function acf_generate_options_css() {
$ss_dir = get_stylesheet_directory();
ob_start(); // Capture all output into buffer
require($ss_dir . '/inc/custom-styles.php'); // Grab the custom-style.php file
$css = ob_get_clean(); // Store output in a variable, then flush the buffer
file_put_contents($ss_dir . '/css/custom-styles.css', $css, LOCK_EX); // Save it as a css file
}
add_action( 'acf/save_post', 'acf_generate_options_css', 20 );
I then enqueue the script:
function acf_enqueue_scripts() {
wp_enqueue_style( 'custom-theme-css', get_template_directory_uri() . '/css/custom-styles.css' );
}
add_action( 'wp_enqueue_scripts', 'acf_enqueue_scripts', 99 );
And custom-styles.php looks like this:
$colour_name = get_field('colour_name','option');
$select_colour = get_field('select_colour','option');
.bg-colour-<?php echo str_replace(" ","-",strtolower($colour_name)); ?> {
background-color: <?php echo $select_colour; ?>;
}
Not sure if that helps at all?

Could you use something like the below:
$args = array(
'numberposts' => -1,
'post_type' => array('post', 'page'),
'meta_key' => 'colours', // your existing colur select field
);
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
$colours = array();
while( $the_query->have_posts() ) : $the_query->the_post();
$colours[] = get_field('colours');
endwhile;
endif;
// remove duplicates
$filtered_colours = array_unique($colours);
if ( $filtered_colours ) :
foreach ( $filtered_colours as $colour ) :
echo $colour;
endforeach;
endif;
Depends on how you need to show/use the values I guess
I’m looking for this as well. I found a solution here: https://stackoverflow.com/a/20293486/1766219
Note, that there is typo on that solution, which I have corrected in below-written solution:
global $wpdb; // (this is required when are you inside the function)
$values = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta pm, $wpdb->posts p WHERE meta_key = 'NAME_OF_THE_FIELD_YOURE_AFTER' and pm.post_id=p.ID and p.post_type='CUSTOM_POST_TYPE_NAME' ",ARRAY_A);
print_r($values);

I’m not sure if something like this could work:
<?php
##########################################
# Populate ACF field with list of colours
##########################################
function load_colours_into_acf_select_field( $field ) {
$args = array(
'numberposts' => -1,
'post_type' => array('post', 'page'),
'meta_key' => 'colours', // your existing colur select field
);
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
$colours = array();
while( $the_query->have_posts() ) : $the_query->the_post();
$colours[] = get_field('colours');
endwhile;
endif;
// remove duplicates
$filtered_colours = array_unique($colours);
if ( $filtered_colours ) :
//Add empty option
$field['choices']["0"] = 'Select a colour';
foreach ( $filtered_colours as $colour ) :
$field['choices'] = $colour;
endforeach;
endif;
return $field;
}
//Change colour_dropdown to your field which is assigned to your custom post type
add_filter( 'acf/load_field/name=colour_dropdown', 'load_colours_into_acf_select_field' );
Hopefully, the code/comments will help. It’s not tested and simply cobbled together, however, it should be a good starting point.

Hi idesignandhost
Question 1.
Yes, you can simply use php concatenate. For example:
$field_1 = get_field('field_1');
$field_2 = get_field('field_2');
$join_me = 'Hello, using a . joins things together: '.$field_1.' and '.$field_2;
Question 2
You can try something like:
function wp_disable_acf_fields( $field ) {
if( !is_admin() ){
$field['disabled'] = 1;
}
return $field;
}
add_filter('acf/load_field/key=field_5996a05bc0d7d', 'wp_disable_acf_fields'); #replace field key

Hi @miksynder
Could you not use the file field instead? Then add a field for each image size you require?
Perhaps not ideal but a possible solution
This one has me stumped.
Uploading an image, via ACF as usual, but I need to create multiple sized versions of that same image.
I could just use the regular add_image_size but, this means any other image uploaded, also gets created at these sizes which is not what I want (there will be around 100+ post_thumbnails created each time).
So, my question:
Using ACF to upload an image, how would I then create multiple sized copies of that image?
I came here to report the exact same issue! Everything was fine until recently. Perhaps the last WordPress update broke something? I am using the same versions as you.
Everything appears to be sending correctly and the response looks correct on the initial save, but the data is not saved.
/wp-admin/admin-ajax.php?_fs_blog_admin=true
Request
acf[field_5fc3aad04255a]: 10
acf[field_5fc7261aae126]: 2021
action: acf/validate_save_post
nonce: e31d46a48c
post_id: 4987
Response
{“success”:true,”data”:{“valid”:1,”errors”:0}}
The update sends the exact same data to the exact same endpoint and gets the exact same response, but it works.
Has there been any progress on this? I have a repeater field with a minimum of 2 items and in the repeater a WYSIWYG block, which have default (some Lorem ipsum text) and when I add a block to the Gutenberg editor a completely empty block is shown. If I click the editor and edit the content the preview becomes visible.
The code above does nothing for me (or do I need to change some values to my field names?)
I made a screencast to better illustrate the issue. As you can se when you edit the block it becomes visible
https://www.youtube.com/watch?v=IzM-OMoHbWQ
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.