Hello,
for our website we are creating an alphabetical index.
The first letter of the keyword, a custom field called ‘keyword’, needs to be stored in a custom taxonomy called ‘alphabetical letter’.
Thanks to the fantastic support here on ACF, we now have a code which does the trick for every new post that has it’s keyword updated. this is stored in the site as a code snippt and works beautifully.
function my_acf_update_letter( $value, $post_id, $field ) {
$taxonomy = 'alphabetical_letter';
$first_letter = strtoupper(substr($value, 0, 1));
wp_set_post_terms( $post_id, $first_letter, $taxonomy );
// return
return $value;
}
add_filter('acf/update_value/name=keyword', 'my_acf_update_letter', 10, 3);
However, here comes the problem, we have over 20.000 articles where this function needs to run just once on it’s keywords and obviously opening all posts one by one and updating them is no option. since we are in no way php geniuses could you please get us on our way ?
we wrote/pulled together the following bit of code but it’s not doing what we want…
function kia_run_once(){
if ( false === get_transient( 'kia_run_once' ) ) {
$taxonomy = 'alphabetical_letter';
$alphabet = array();
$posts = get_posts(array('numberposts' => -1) );
foreach( $posts as $p ) :
//set term as first letter of post title, lower case
$first_letter = strtoupper(substr($value, 0, 1));
wp_set_post_terms( $p->ID, $first_letter, $taxonomy );
endforeach;
set_transient( 'kia_run_once', 'true' );
}
}
add_action('init','kia_run_once');