Support

Account

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

  • Hi there,
    I can’t make this work.
    I have a true/false field called “best of week” in my posts. How exactly do you find the field id?

    Here is my code:

    add_action('acf/save_post', 'my_acf_save_post', 1);
    function my_acf_save_post( $post_id ){
    	$fields = false;
    	/* Here I added a if statement so the code runs only for a defined category */
    	if(get_post( $post_id )){
    		// Check if Fields have been posted
    		if ( isset( $_POST['fields'] ) ) {
    			$fieldId = 'acf-field_57872ec102054-1';
    			$fields = $_POST['fields'];
    			// Store the true/false field on a variable (change the "Field_xxx" id by yours)
    			$BestWeek = $fields[$fieldId];
    			// Check if the true/false field is true
    			if ( $BestWeek ) {
    				/* If it's set to true do a WP_query so you can get the other post that have $BestWeek 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(
    					'post_type' => 'post', 
    					'meta_query' => array(
    						array(
    							'key' => 'best_of_week',
    							'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() );
    					}
    				}
    			}
    		}
    	}
    }