Advertisement
lorro

WooCommerce - Loop through products to get terms

Jan 4th, 2017
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.88 KB | None | 0 0
  1. WooCommerce - Loop through products to add terms to wp_postmeta to enable ordering, sorting or filtering on terms
  2.  
  3. You’ll need something like this to loop through your products. It goes in functions.php for your child theme. Uncomment the add_action() to make it run. It may take ages, so comment it again after its done its job. The prints are there so you can see if its finding the right data. Comment them if they are correct. Finally, uncomment the update_post_meta() to actually do the update.
  4.  
  5. This has the potential to screw up the wp_postmeta table big style, so back up the table or the database first, or better, run it on a dev install first.
  6.  
  7. If you only want certain terms in the wp_postmeta table, you’ll need an if ($name == 'my_term' ) {}in there.
  8.  
  9. Its meant as a framework, so some further effort and debugging may be needed.
  10.  
  11. // add_action( 'init', 'update_postmeta' );
  12.   function update_postmeta() {
  13.     global $post;
  14.     // get all the products
  15.     $args = array(
  16.      'post_type' => 'product',
  17.      'post_status' => 'publish',
  18.      'numberposts' => -1 );
  19.     $selected_posts = get_posts( $args ); // array of 38 posts
  20.  
  21.      // loop through them
  22.     foreach( $selected_posts as $post ) {
  23.       setup_postdata($post);
  24.       $post_id = get_the_ID();
  25.       print 'Post ID: '.$post_id;
  26.       $object_ids = array( $post_id );
  27.       $taxonomies = array ( 'product_tag' );
  28.       $terms = wp_get_object_terms( $object_ids, $taxonomies );
  29.       if ( !is_wp_error($terms) ) {
  30.         print ' Nr terms found: '.count($terms).'<br>';;
  31.         if ( $terms ) {
  32.           foreach( $terms as $term ) {
  33.             $name = $term->name;
  34.             $slug = $term->slug;
  35.             print 'Name: '.$name.' Slug: '.$slug.'<br>';
  36.             // update_post_meta( $post_id, $name, $slug );
  37.           }
  38.         }
  39.       }
  40.       print '<br>';
  41.       wp_reset_postdata();
  42.     }
  43.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement