如何使用wp cron jobs

时间:2017-12-22 05:29:00

标签: wordpress woocommerce cron

我正在开发我在wordpress中的自定义插件我希望每30分钟运行一次插件短代码功能。该插​​件功能用于显示woocommerce产品评论。我的插件功能如下。当我在产品上添加新评论时,' [wc_reviews]' 短代码会显示所有评论。我想使用wp cron作业运行' [wc_reviews]' 短代码。如何做到这一点请任何人帮助我。

function wpcron_intervals( $schedules ) {

        // one minute

        $one_minute = array(
                        'interval' => 60,
                        'display' => 'One Minute'
                    );

        $schedules[ 'one_minute' ] = $one_minute;

        // five minutes

        $five_minutes = array(
                        'interval' => 300,
                        'display' => 'Five Minutes'
                    );

        $schedules[ 'five_minutes' ] = $five_minutes;

        // return data

        return $schedules;

    }
    add_filter( 'cron_schedules', 'wpcron_intervals' );



    // add cron event
    function wpcron_activation() {

        if ( ! wp_next_scheduled( 'example_event' ) ) {

            wp_schedule_event( time(), 'five_minutes', 'example_event' );

        }

    }
    register_activation_hook( __FILE__, 'wpcron_activation' );

    // remove cron event
    function wpcron_deactivation() {
        wp_clear_scheduled_hook( 'example_event' );

    }
    register_deactivation_hook( __FILE__, 'wpcron_deactivation' );

    function wc_reviews_function ($values){

    $wc_reviews = get_comments( 
        array( 
            'status' => 'approve', 
            'post_status' => 'publish', 
            'post_type' => 'product',
            'parent' => '0',
            'number' => 10,
            'orderby' => 'date',
         'order' => 'DESC',
         'date_query' => array(
                array(
                'after' => '30 days ago',
                  )
               )

            ) 
        );

    if ( $wc_reviews ) { 
?>        
  <div class="testimonials">    
  <div class="row items" data-equalizer="" data-equalizer-mq="">
  <?php
        foreach ( $wc_reviews as $wc_review ) {   
  ?>
    <div class="item large-3 medium-6 columns">
        <div class="inner" style="">

             <a href="<?php echo get_permalink($wc_review->comment_post_ID); ?>"><?php echo get_the_post_thumbnail($wc_review->comment_post_ID, array( 150 , 150 ) ); ?>

             <h5><a href="<?php echo get_permalink($wc_review->comment_post_ID); ?>"></a></h5>

           </div>
    </div>    

  <?php 
        }
  ?>            
  </div>
</div>

<?php

        //if there is no reviews
        } else {
            echo'There are no reviews at all';
        }

}//end function



add_action( 'example_event', 'wc_reviews_function' );
add_shortcode( 'wc_reviews', 'wc_reviews_function' );

0 个答案:

没有答案