我的 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'));
}
?>