I created a field (not acf) in the user profile. The field is called “genere”, and I have another field in the post created with ACF called the same "genere", but it is invoked in my function by the $field_key
.
I can now pass this usermeta
field to the author’s post to a acf_field
with acf_update_field
but only after I click on “Update User” in edit-user.php.
There is only one post per author, at most two by mistake. So when I click on "Update User" in user-edit.php, the author post also updates. I would like every usermeta
of "genere" field value to pass automatically to the author's post already created.
Another my previous function creates the author's post when this user is created. When I update the user, his post already exists. So for future author's posts I do not need solutions because by updating the profile, the field value passes well and works. The problem is only for the posts already created (in my theme by default each user has a post).
There are 2500 users and I would need to pass the value to the post without manually updating the user-edit.php page.
This is my code in the file functions.php
function save_acf($user_id)
{
global $post;
$args = array(
'author' => $user_id,
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) :
setup_postdata($post);
$numero = $post->ID;
endforeach;
if( isset($_POST['genere']) ) {
$post_id = $numero ;
$field_key = "field_5941b968b5ad6";
$value = sanitize_text_field( $_POST['genere'] ) ;
update_field( $field_key, $value, $post_id );}
}
add_action( 'user_register', 'save_acf');
add_action( 'personal_options_update', 'save_acf' );
add_action( 'edit_user_profile_update', 'save_acf' );
- Probably the actions
user_register
andpersonal_options_update
are no influence
EDIT
With hwl's suggestions in his answer I found this work solution.
Bulk action > get user by usermeta from MySql > get the id of users with foreach > update postmeta with foreach post
add_filter( 'bulk_actions-edit-post', 'register_my_bulk_actions2' );
function register_my_bulk_actions2($post_ids) {
global $wpdb;
$users = $wpdb->get_results( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'genere'AND meta_value = 'Maschio' " );
foreach ( $users as $a ) {
$author_ids[] = $a->user_id;
}
$args = array( 'posts_per_page' => -1 , 'author__in' => $author_ids, );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :
$numero = $post->ID;
update_post_meta( $numero, 'genere', 'Maschio' );
endforeach;
}
Best regards
genere
, and you want to save the value of that in theacf_field
of all of the posts by that author, for every author? For current posts and/or for new posts as they are added?