Wordpress foreach loop doesn't finish

2019-03-06 01:06发布

问题:

I have a little under 1,000 posts of type lp_lesson and I am trying to be able to loop through them all to apply text to a specific custom field.

The below code works for only a few of them. Possibility between 10-15. I wanted to know if it's because I am using wp_enqueue_scripts? I also tried applying this change on wp_login. Both of them update the exact same number of posts and the exact same posts.

I am completely new to php so if I am doing this complete wrong please let me know.

I do believe there's an issue with the loop not finishing before the system just times it out, maybe? I can confirm that all the posts are lp_lesson so the loop is not finishing. Perhaps $args cannot hold an array that big? Any tips are appreciated!

Thanks.

add_action( 'wp_enqueue_scripts', 'win_9388244_format_lp_lesson' );

function win_9388244_format_lp_lesson() {
  //Get post type of lp_lesson
        $args = array(
         'post_type' => 'lp_lesson'
        );
        $posts = get_posts($args);
  foreach($posts as $post) {
    update_post_meta( $post->ID, 'wpk_icon_text', 'Test' ); 
  }
}

回答1:

The default args of get_posts are :

$defaults = array(
        'numberposts' => 5,
        'category' => 0, 'orderby' => 'date',
        'order' => 'DESC', 'include' => array(),
        'exclude' => array(), 'meta_key' => '',
        'meta_value' =>'', 'post_type' => 'post',
        'suppress_filters' => true
    );

meaning that if you do not specify these values in your $args variables, wordpress will take these ones by default. If you give a value to numberposts, then wordpress will use this one, and the other default values.

You should set the numberposts. For instance :

$args = array(
         'post_type' => 'lp_lesson',
         'numberposts' => 99999
        );

get_posts function reference



标签: php wordpress