0

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

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

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

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

<!-- 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'));
    }
?>  
4

2 回答 2

0

整个 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 );
}
于 2018-04-18T11:41:52.580 回答
-1

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
}
于 2018-04-17T18:28:23.720 回答