PluginUs.Net - Business Tools for WooCommerce and WordPress

[realize your idea - make your dreams come true]

Support Forum

You need to log-in to create request (topic) to the support

Converting taxonomies terms values into custom field

The support doesn work on Saturdays and Sundays, so some Friday requests can be answered on Monday.
If you not got email within 24~36 business hours, firstly check your spam box, and if no any email from the support there - back to the forum and read answer here. DO NOT ANSWER ON EMAILS [noreply@pluginus.net] FROM THE FORUM!! Emails are just for your info, all answers should be published only here.
The support doesn work on Saturdays and Sundays, so some Friday requests can be answered on Monday.

Hi,

I’m trying to copy the value of the taxonomy named item_year to the newly created custom field named year for each of my posts.

 

Following the explanation in https://wp-filter.com/howto/convert-taxonomies-terms-values-meta-values/

I pasted the following code to the functions.php file.

global $wpdb;

$pp = $wpdb->get_results("SELECT ID from {$wpdb->posts} WHERE post_type='post'");

if (!empty($pp)) {

foreach ($pp as $p) {

$terms = wp_get_post_terms($p->ID, 'item_year');

if (!empty($terms)) {

if (isset($terms[0])) {

update_post_meta($p->ID, 'year', $terms[0]->name);

}

}

}

}

 

However, I’m keep getting:

Uncaught Error: Cannot use object of type WP_Error as array in

 

With a reference for the line that contains

if (isset($terms[0])) {

 

Any help would be much appreciated!

Hello

please  change this  line - https://share.stackovergo.com/image/i20220124083428.png

if (!empty($terms) && !is_wp_error( $terms)){

Hello Pablo and thanks a lot for your help!

If I understand it correctly, the addition that you suggest will prevent the “Uncaught Error”, caused by WP_Error.

What bothers me in this case is what caused the WP_Error. From looking at the reference for wp_get_post_terms I understand that WP_Error is returned when no term (in my example 'item_year') can be found. However, I double checked and 'item_year' was the relevant taxonomy which I created (using Custom Post Type UI plugin) and all my posts had values for this taxonomy. I also tried to debug by changing 'item_year' to ‘post_tag’ and adding echo statement for showing the post id and the first tag of each post, and everything seemed ok.

Any ideas?

Hello

Run this code in the wp_head event

Thank you very much!!! Moving the code to header.php solved my issue!

Hello

Welcome;)