Skip to content

Instantly share code, notes, and snippets.

@akshuvo
Created March 8, 2021 10:36
Show Gist options
  • Select an option

  • Save akshuvo/5dd9d2ddb733e8c60b2b63c09de2bc51 to your computer and use it in GitHub Desktop.

Select an option

Save akshuvo/5dd9d2ddb733e8c60b2b63c09de2bc51 to your computer and use it in GitHub Desktop.

Revisions

  1. akshuvo created this gist Mar 8, 2021.
    51 changes: 51 additions & 0 deletions get-last-month-products.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    <?php

    /**
    * Get All Products from Last Month
    */
    add_shortcode('wc_get_products_last_month', function( $atts, $content = null ){

    $start_date = array(
    'year' => date("Y", strtotime("first day of previous month")),
    'month' => date("n", strtotime("first day of previous month")),
    'day' => date("j", strtotime("first day of previous month"))
    );

    $end_date = array(
    'year' => date("Y", strtotime("last day of previous month")),
    'month' => date("n", strtotime("last day of previous month")),
    'day' => date("j", strtotime("last day of previous month"))
    );


    $args = array(
    'post_type' => 'product',
    'date_query' => array(
    array(
    'after' => $start_date,
    'before' => $end_date,
    'inclusive' => true,
    ),
    ),
    'posts_per_page' => -1,
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {

    while( $query->have_posts() ) { $query->the_post();
    // Get $product object from product ID
    $product = wc_get_product( get_the_ID() );

    // Do you stuff here
    //_e( $product->get_name() );

    }

    } else {
    echo 'No Posts';
    }

    wp_reset_query();
    });