I'm using a custom meta field, to specify which post will appear as a featured one in the front page.
This meta field is a true/false value, declared through ACF.
I want this condition to only be applied to one post, i.e. when the user declares a post as "featured", and saves it, all the other ones (theoretically only the last one) that have this meta value checked, should be turned "off".
To achieve this, I've declared a function attached to the "save_post" action, that turns to "false" this specific post meta value, for the older featured posts.
This is my approximation, but there's something that I'm missing, because it is not working at all.
function only_one_agenda_featured( $post_id ) {
// If this isn't a 'agenda' post, don't update it.
if ( 'agenda' != $post->post_type ) {
return;
}
// Stop when it is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Prevent quick edit from clearing custom fields
if (defined('DOING_AJAX') && DOING_AJAX) {
return;
}
$post_meta_value = get_post_meta( $post_id, 'agenda_featured', TRUE );
if ( $post_meta_value == '1' ) {
$args = array(
'meta_key' => 'agenda_featured',
'meta_value' => '1',
'post_type' => 'agenda',
'post__not_in' => array($post_id),
);
$posts_to_update = get_posts( $args );
foreach ( $posts_to_update as $post_to_update ) {
update_post_meta( $post_to_update->ID, 'agenda_featured', '0', '1' );
}
}
}
add_action( 'save_post', 'only_one_agenda_featured' );
Any help will be appreciated.