Home › Forums › General Issues › Copy taxonomy values to a custom fields › Reply To: Copy taxonomy values to a custom fields
Yes, something like that could work, but it depends on how many posts you have.
add_action('acf/init', 'update_post_year_field');
update_post_year_field() {
$args = array(
'post_type' => 'your-post-type',
'post_status' =>'any',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'year'
'compare' =>'NOT EXISTS'
),
array(
'key' => 'year'
'value' => '',
'compare' =>'='
)
)
);
$query = new WP_Query($args);
if (count($query->posts)) {
foreach ($query->posts as $post) {
$terms = wp_get_post_terms($post->ID, 'your-taxonomy');
if (!empty($terms)) {
// use the field key here, not the field name
update_field('field_key', get_field('item_year', $term[0]), $post->ID);
}
}
}
}
If you have a lot of posts it may timeout the loading of your site. This is why the query is looking for the field not being set or has an empty value. The number of posts returned should be reduced each time and eventually it will complete and then you can remove the filter.
But you will also need to create an acf/save_post filter to update this field when a new post is created or a post is updated.
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.