简体   繁体   中英

Use get_posts on custom_type in a Wordpress plugin

I am building a plugin to update all posts from a custom type at once.

I have over 20K listings of events and 1000 venues. A venue is selected in the listing post when created and some info is copied into the listing, but if you modify the venue after that, the listing have to be refreshed manually. (I did not create that system but trying to improve.)

In the new admin page I created, you click a button, it refreshes and runs a PHP function on GET. That part works, the function is triggered. But apparently the get_posts function I'm using is causing the function to crash.

 function ac_update_listings() {
        global $post;

        $my_posts = get_posts( array(
                                    'post_type' => 'listing', 
                                    'post_status' => 'any',
                                    'numberposts' => -1
                                    ) );

        foreach ( $my_posts as $my_post ):

        $post_id = $my_post['ID'];
        echo $post_id;



            //Get Venue ID

            $thevenue = get_post_meta($post_id, 'thevenue', true);

            //Get Venue info

            $block = get_post_meta($thevenue, 'block', true);
            $street = get_post_meta($thevenue, 'street', true);
            $number = get_post_meta($thevenue, 'number', true);


            // Update Data

            update_post_meta($post_id, 'block', $block);
            update_post_meta($post_id, 'street', $street);
            update_post_meta($post_id, 'number', $number);

        endforeach;

        echo "Listings are now updated.";
    }

Firstly, you have numberposts , this should be posts_per_page . Since get_posts uses WP_Query parameters for query.

And I think the query will run faster if you set it to 999 instead of -1. -1 takes all the posts, and if you have 1000+ posts this takes time and resources. You could limit the query by querying only the latest posts, or if your venues have expiration date or something like that if you are pushing the ones that expired to the draft, you could probably query only published posts, which will then be < 999 posts (a guess).

All this will improve the performance of the query, and it could prevent any crashing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM