Query WordPress Posts and put Titles in Array

I’m trying to query my WordPress for a specific post type “team_members” and then store the titles in an array. When I use the following my output just shows 0, 1, 2 (I only have the 3 posts) it doesn’t show the post titles.

 $my_array=array();

// the query
$args=array('post_type' => 'team_members','order'=>'ASC');
$my_query = new WP_Query($args);

if ($my_query->have_posts()) : 
while ($my_query->have_posts()) : $my_query->the_post(); 
    $my_array[]=get_the_title( get_the_ID() );
endwhile;
endif;

Any help or direction would be greatly appreciated.

Read More

Thanks
John

Related posts

Leave a Reply

4 comments

  1. Thanks Guys,

    Your right it does work, I think it was the way I was trying to use the variable in Visual Composer. When I use the variable in a drop down box I see the titles correctly but when I use it for multiple checkboxes it displays the post ID.

    It’s a Visual Composer issue.

    Thanks Mauro as the_title(); did simplify the code and also worked for me.

    Thanks
    John

  2. I can’t see any problem with your code. Try using get posts and using the post_title property instead.

    E.g.

    $my_array = array();
    
    // the query
    $args=array('post_type' => 'team_members','order'=>'ASC');
    
    $posts = get_posts( $args );
    
    if ( $posts ) {
        foreach ( $posts as $post ) {
            $my_array[] = $post->post_title;
        }
    }
    
  3. // the query
    $args=array('post_type' => 'team_members','order'=>'ASC');
    $my_query = new WP_Query($args);
    
    if ($my_query->have_posts()) : 
    while ($my_query->have_posts()) : $my_query->the_post();
        $id = $my_query->posts->ID; 
        $my_array[]=get_the_title( $id );
    endwhile;
    endif;