How to iterate through custom posts and add the title to an array

I see two problems with the code you’ve written. The first one is that the_title() echos the post title although returning the title would be more appropriate in this context. Also wp_reset_postdata() should be after the while loop inside the if statement.

But as you mentioned that you only need the post titles, you can get them directly from the post objects from the query object without setting up the loop with have_posts() and the_post(). Like so,

add_action('woocommerce_after_order_notes', 'custom_checkout_field');
function custom_checkout_field($checkout) {

  $args = array(
    'post_type'              => 'pickup-point',
    'posts_per_page'         => -1,
    'post_status'            => 'publish',
    'no_found_rows'          => true, // pagination not needed
    'update_post_meta_cache' => false, // post meta not needed
    'update_post_term_cache' => false, // taxonomy terms not needed
  );
  $query = new WP_Query( $args );

  $titles = array_map( 'get_the_title', $query->posts );
  if ( $titles ) {
    // do something with $titles    
  }

}

I added couple of extra parameters to the query $args, which make the query a bit more efficient as only post titles are needed.

Leave a Comment