每周在 Wordpress 单一.php模板中执行一次 PHP 代码



我的单个模板中有以下代码.php。它从外部网站检索价格,然后,如果它与现有的价格自定义字段不同,它会更新元值。

该部分按预期工作。不过,我想做的只是检查它并每周更新一次,而不是每次页面加载。

起初,我认为我可以根据帖子修改日期来做到这一点,但显然在更新帖子元时这不会改变。

如果我能以某种方式将其合并到功能中.php每周更新所有帖子,那就更好了。但是,如果它也只在帖子的负载上触发也很好。我确信有一种方法可以为它安排一个 cron,但我不熟悉编程 crons。

<!-- Check external price -->
<?php 
    if(get_field('xpath_price')) { 
        libxml_use_internal_errors(true);
        $doc = new DomDocument();
        $url = get_field('_scrape_original_url');
        $doc->loadHTML(file_get_contents($url));
        $xpath = new DOMXPath($doc);
        $query = get_field('xpath_price');
        $metas = $xpath->query($query);
        foreach ($metas as $meta) {
            $priceexternal1 = preg_replace("/(.*?)(.)(.*)/", "$1", $meta->nodeValue);
            $priceexternal = preg_replace("/[^0-9]/", "", $priceexternal1);
        }
        echo '<h3>External Price</h3>';
        echo $priceexternal;
    } 
?>
<!-- Update post_meta if different -->
<?php 
    if ($priceexternal && ($priceexternal) <> (get_field('price'))) {
        global $post;
        update_post_meta( $post->ID, 'price', $priceexternal ); 
        $priceout = $priceexternal;
    } elseif(get_field('price')) {
        $priceout = preg_replace("/[^0-9]/", "", get_field('price'));
    }
?>  

对于外行来说,整个 wp-cron 系统可能会有点混乱,尽管它绝对是做你想做的正确方法。但是,如果您不满意掌握它,则可以使用一个简单的瞬态集,以便在设定的时间段后过期(请参阅Codex(

例如。。。

if ( !get_transient( 'my-price-timer' ) ) { 
    // no transient exists, so process price check
    if(get_field('xpath_price')) {
        // etc
    }
    // now create the transient to say that we've done it
    set_transient( 'my-price-timer', 'done', WEEK_IN_SECONDS );
}

> https://codex.wordpress.org/Function_Reference/wp_cron

 add_filter( 'cron_schedules', 'cron_add_weekly' );
 function cron_add_weekly( $schedules ) {
    // Adds once weekly to the existing schedules.
    $schedules['weekly'] = array(
        'interval' => 604800,
        'display' => __( 'Once Weekly' )
    );
    return $schedules;
 }

然后

if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
  wp_schedule_event( time(), 'weekly', 'my_task_hook' );
}
add_action( 'my_task_hook', 'get_prices_function' );
function get_price_function() {
  // Your function
}

最新更新