Advertisement
daymobrew

WooCommerce - List stock levels of variable products

Jan 28th, 2018
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en-US">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>List Product Stock</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1" />
  7. </head>
  8. <body>
  9. <h1>List Product Stock</h1>
  10. <?php
  11. set_time_limit( 360 );
  12.  
  13. define('WP_USE_THEMES', false);
  14.  
  15. /** Loads the WordPress Environment and Template */
  16. require( dirname( __FILE__ ) . '/wp-blog-header.php' );
  17.  
  18. // Get IDs of all products.
  19. $args = array('post_type'=>'product', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false);
  20. $products_query = new WP_Query($args);
  21.  
  22. $product_ids = array();
  23. $product_ids = $products_query->posts; // No loop because only requested IDs.
  24. wp_reset_postdata();
  25.  
  26. // Only get 2 products because even that is timing out.
  27. $product_ids = array_slice( $product_ids, 0, 2 );
  28. //$product_ids = array_slice( $product_ids, 0, 1 );
  29.  
  30. foreach ($product_ids as $id) {
  31.     $product = wc_get_product( $id );
  32.     echo "<p>Product name: ", $product->get_name(), "<br/>Type: ", $product->get_type(), "</p>";
  33.     if ( 'variable' == $product->get_type( ) ) {
  34.         $variation_attributes = $product->get_variation_attributes(); // Get titles of the variations.
  35.         $attributes = array_keys( $variation_attributes );
  36.         $available_variations = $product->get_available_variations();
  37.  
  38.         echo '<ul>';
  39.         foreach ( array_keys( $available_variations ) as $index ) {
  40.             if ( true == $available_variations[ $index ][ 'is_in_stock' ] ) {
  41.                 echo "<li><strong>", $variation_attributes[ $attributes[ 0 ] ][ $index ], "</strong> is in stock (", $available_variations[ $index ][ 'max_qty' ], " left).</li>";
  42.             }
  43.            
  44.         }
  45.         echo '</ul>';
  46.     }
  47. }
  48.  
  49. echo '<p>', get_num_queries (), ' SQL queries done.';
  50. echo '<br />Page generation took ', timer_stop(), ' seconds.', '</p>';
  51. ?>
  52. </body>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement