1

I want to have output of an WP_Query to an array.for example an array of my last 10 post titles or an array of last post urls

1 Answer 1

2

If you want to collect the results from WP_Query() into another array, you can try this:

$my_array=array();

// the query
$args=array('post_type' => 'post','posts_per_page'=>10,'orderby'=>'date', '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;

// debug: 
print_r($my_array);
print_r($my_query);

And this example will give you the 10 last post titles into the array $my_array()

Sign up to request clarification or add additional context in comments.

2 Comments

it just print array() that so I have posts in my wordpress
hmm..., it works for me, where are you using it? I updated the code with get_the_ID() inside get_the_title().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.