Home › Forums › Backend Issues (wp-admin) › True/false – When new true, update the rest to false › Reply To: True/false – When new true, update the rest to false
Ummm something doesn’t go well. Here is my code:
/* When a ACF "Featured article" (in 71% articles) is set to true, all the rest are updated to false */
/* First you would have to add acf/save_post action to you function.php so the action runs every time a post is saved or udpated run before ACF saves the $_POST['fields'] data */
add_action('acf/save_post', 'my_acf_save_post', 1);
function my_acf_save_post( $post_id ){
$fields = false;
$fieldId = 'field_5343d06c3e9dc';
$catId = 27;
/* Here I added a if statement so the code runs only for a defined category */
if ( in_category( $catId, $post_id ) ) {
// Check if Fields have been posted
if ( isset( $_POST['fields'] ) ) {
// Store the true/false field on a variable (change the "Field_xxx" id by yours)
$featuredArticle = $fields[$fieldId];
// Check if the true/false field is true
if ( $featuredArticle ) {
/* If it's set to true do a WP_query so you can get the other post that have $featuredArticle set to true here you may want to change the 'cat' to whatever your is (or to all) in the meta query you should use your true/false field name as a key */
$args = array(
'cat' => $catId,
'meta_query' => array(
array(
'key' => 'featured_article',
'value' => '1',
'compare' => '=='
)
)
);
$post_query = new WP_Query( $args );
/* Here we check if the query returns post (if it does it will return featured posts) */
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();
/* For each posts we update the true/false field and set it to false */
update_field( $fieldId, false, get_the_ID() );
}
}
}
}
}
} // end my_acf_save_post
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.