【问题标题】:Dynamically add_action() based upon number of posts根据帖子数量动态 add_action()
【发布时间】:2013-01-21 00:28:57
【问题描述】:

我有一个 wp_cron,每小时运行一次。

cron 调用一个函数,该函数遍历自定义帖子类型。然后使用标题和一些元数据从远程服务器抓取结果。

问题是由于帖子的数量,抓取需要很长时间。我想通过一次仅迭代 25 个帖子将抓取分成块。在 query_posts 中使用 offset 参数很容易,但是如何动态地 add_action() 并传递 offset 变量呢?

functions.php

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;

}

基本上我需要一种方法来动态地 add_action(),每次将 $offset 的值增加 25。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您可以将变量传递给您的add_action()

    add_action( $tag, $function_to_add, $arg );
    

    但您也可以使用 do_action() 而不是每次运行 cron 时都添加操作:

    do_action( $tag, $arg )
    

    无论如何,将您的 $offset 存储在某个地方是很好的,所以我看到了两个选项:

    将您的持久值存储在WP_Object_Cache 中。也许阅读此文档,您可以找到另一个优雅的解决方案,以提高大型查询结果的性能。

    使用add_option()get_option() 在数据库中记录您的实际$offset 值。

    如果你存储了your $offset变量,你的rock_and_roll函数就不需要再接收参数了,你只需要在函数内部取回它。

    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;
    
    }
    

    【讨论】:

      【解决方案2】:

      您的 $Offset 是从另一个来源传递给函数的。所以我可以想象,类似:

      $Var = $Pre_definedoffset;
      $Var = $Pre_definedoffset + 25; 
      rock_n_roll($var);
      

      这只是我从您的代码中看到的假设。

      在代码将其推送到函数之前,您需要修改包含传递给函数的整数的变量。

      【讨论】:

        猜你喜欢
        • 2016-12-22
        • 2015-03-18
        • 1970-01-01
        • 2012-01-16
        • 1970-01-01
        • 2013-10-30
        • 2014-08-23
        • 2016-03-18
        • 1970-01-01
        相关资源
        最近更新 更多