Php 根据帖子数量动态添加_action()
我有一个wp_cron,我每小时运行一次 cron调用一个函数,该函数迭代自定义post类型。然后使用标题和一些元数据从远程服务器获取结果 问题是,由于帖子的数量太多,刮削需要很长时间。我想通过一次只迭代25篇文章来将这些内容分成几块。在query\u posts中使用offset参数很容易,但是如何动态添加\u action()并传递offset变量呢 在functions.php中Php 根据帖子数量动态添加_action(),php,wordpress,Php,Wordpress,我有一个wp_cron,我每小时运行一次 cron调用一个函数,该函数迭代自定义post类型。然后使用标题和一些元数据从远程服务器获取结果 问题是,由于帖子的数量太多,刮削需要很长时间。我想通过一次只迭代25篇文章来将这些内容分成几块。在query\u posts中使用offset参数很容易,但是如何动态添加\u action()并传递offset变量呢 在functions.php中 if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
wp_schedule_event( time(), 'hourly', 'my_task_hook' );
}
add_action( 'my_task_hook', 'rock_n_roll' );
我的scraper.php看起来像这样
function rock_n_roll($offset) {
query_posts(array(
'post_type' => 'wine',
'order' => 'ASC',
'posts_per_page' => -1,
'offset' => $offset
));
while (have_posts()) : the_post();
//compare values against scraped results
//write results to DB with update_post_meta
endwhile;
}
基本上,我需要一种方法来动态添加_action(),每次将$offset的值增加25。您的$offset将从另一个源传递给函数。。所以我可以想象,比如:
$Var = $Pre_definedoffset;
$Var = $Pre_definedoffset + 25;
rock_n_roll($var);
这只是我从代码中看到的假设
在代码将其推送到函数之前,需要修改包含传递给函数的整数的变量 您可以将变量传递给您的: 但您也可以在每次运行cron时使用,而不是添加操作:
do_action( $tag, $arg )
无论如何,将$offset
存储在某个地方很好,因此我看到了两个选项:
将持久值存储在中。也许阅读本文档,您可以找到另一个针对大型查询结果性能的优雅解决方案
使用和在数据库中记录实际的$offset
值
如果存储$offset变量,摇滚乐函数不需要再接收参数,只需在函数中检索它
function rock_n_roll() {
// Retrieve $offset value from WP_Object_Cache
// or from database with get_option()
query_posts(array(
'post_type' => 'wine',
'order' => 'ASC',
'posts_per_page' => -1,
'offset' => $offset
));
while (have_posts()) : the_post();
//compare values against scraped results
//write results to DB with update_post_meta
endwhile;
}
function rock_n_roll() {
// Retrieve $offset value from WP_Object_Cache
// or from database with get_option()
query_posts(array(
'post_type' => 'wine',
'order' => 'ASC',
'posts_per_page' => -1,
'offset' => $offset
));
while (have_posts()) : the_post();
//compare values against scraped results
//write results to DB with update_post_meta
endwhile;
}