Home › Forums › Backend Issues (wp-admin) › How can I set true/false field value to always be false instead of NULL
Hey!
I’ve been trying to sort first page products with true/false field. As it is true the product is supposed to appear on first page.
I used this meta_query to show all products
‘meta_query’ => array(
‘relation’ => ‘OR’,
array(
‘key’ => ‘show_on_first_page’,
‘compare’ => ‘EXISTS’,
),
array(
‘key’ => ‘show_on_first_page’,
‘compare’ => ‘NOT EXISTS’,
)
),
This mixes up all the products but if acf true/false field has been checked once it shows the products in the right order. Is there a way to set acf true/false field to be false globally on default if it is set to NULL?
There isn’t any way to retroactively set a new ACF field value for new fields added after posts are created.
Depending on how many posts you have the easiest way to do this might be to manually update every post.
How many existing posts are we talking about?
Hey John!
I have about 700 products and there is more to come so that solution really doesn’t work for me. I’ve been thinking about this a lot today and couldn’t come up with a workaround
There is no work-a-round. I was just doing some testing to see what happens and you just can’t order posts by a field that does not exist on every post.
What you have to do is to create this field with a default value on every “product”
add_filter('init', 'update_all_product_acf_field');
// query to get all posts that are missing the meta value
function update_all_product_acf_field() {
$args =array(
'post_type' => 'your-post_type', // change to correct post type
'posts_per_page' => -1, // all mosts
'meta_query' => array(
array(
// missing this field
'key' => 'show_on_first_page',
'compare' => 'NOT EXISTS',
),
),
'fields' => 'ids' // all we need is the id
);
$query = new wp_query($args);
if (!empty($query->posts)) {
foreach ($query->posts as $post_id) {
// use field key for your field
// because it does not exist
update_field('field_XXXXXXX', 0, $post_id);
}
}
}
More then likely the above will time out the loading of your site one or several times. When the site is able to load you can remove the init action because all the posts will be updated…. (it can’t find any more posts with the missing meta key)
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!
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.