Advertisement
helgatheviki

Test WC Products in transient

Apr 19th, 2023
955
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.77 KB | None | 0 0
  1. function test_transients() {
  2.     // Set the transient key
  3.     $transient_key = 'my_products_transient';
  4.  
  5.     // Check if the transient exists
  6.     if ( false === ( $products = get_transient( $transient_key ) ) ) {
  7.  
  8.         // If the transient does not exist, retrieve the products and store them in the transient
  9.         $products = wc_get_products( array(
  10.             'status' => 'publish',
  11.             'limit'  => 5,
  12.         ) );
  13.  
  14.         // Set the transient with a 1-hour expiration time
  15.         set_transient( $transient_key, $products, 60 * 60 );
  16.     }
  17.  
  18.     // Now you can use the $products array, which may have been retrieved from the transient or queried and stored in it
  19.     echo '<ul>';
  20.         foreach( $products as $p ) {
  21.             echo '<li>'. $p->get_name() . '</li>';
  22.         }
  23.     echo '</ul>';
  24.  
  25. }
  26. add_action( 'init', 'test_transients' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement