Home › Forums › General Issues › New Field – Auto Update posts in custom post type
I created a new field for a custom post type with a default value. I know the posts all need to be “updated” to receive that default value. Is this the way to do it?
$args = array(
'post_type' => 'book'
);
$all_books = get_posts( $args );
update_field($selector, $value, $all_books);
I don’t want to open the 1000+ posts and click the update button đ
You need to loop through the posts and update the field, yes you could do that.
get posts
while have posts
the post
update value
But I wouldn’t.
The best way to do this is to check the value where it is used and substitute a default value if it’s not set, it only takes a couple lines of code to deal with it.
$value = get_field('your-new-field');
if (!$value) {
$value = 'the default value';
}
// do something with value
you could also add an acf/load_value filter for the field in question that sets the default value if it is empty https://www.advancedcustomfields.com/resources/acf-load_value/
I am considering using acf/load_value/key={$field_key}
are all the parameters required? So do I still need to loop through each post in the custom post type?
@hube2 actually I am finding that though it does “load and save” the correct data to the database, it seems as if the post isn’t actually “updated”. Without updating I am not able to use the column filtering in the backend for that field. Only once I actually update the post does then that data become filterable.
Yes, because the value is not updated, you’re just inserting a default.
To make the filtering work you will need to create a temporary function that queries the posts, loops through them and updates each value.
You have a lot of posts and this could time out.
I would add a meta query to my WP_Query to only get posts where this custom field does not exist, this way you will only update posts that have not value. If it times out the first time you can just keep re-loading the page until they are all updated. https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
You must be logged in to reply to this topic.
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!
ACF wouldnât be so widely used in WordPress if it didnât have some pretty amazing capabilities. In this article, we look at a few of the features weâll discuss during â7 things you didnât know you could do with ACFâ at #WPEDecode later this month. https://t.co/5lnsTxp81j pic.twitter.com/Yf0ThPG1QG
— Advanced Custom Fields (@wp_acf) March 16, 2023
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.