0

I want to query a database in order to get all the desired posts alongside with their images. I have managed to do it with 2 different queries. The first one, brings all the posts alongside with the desired fields and the second one, runs in a foreach loop in order to get the image for each post. My problem is that this takes a really long time and i want to avoid id. I need a solution in order to avoid the foreach loop in the second query and merge it into the first.

Query 1

"SELECT * FROM wp_posts";

And foreach returned posts.ID

Query 2

"SELECT wp_posts.guid IN (Select wp_postmeta.meta_value from wp_postmeta where wp_postmeta.meta_key = '_thumbnail_id' AND wp_postmeta.post_id = ('the returned post id foreach of ID output of the first query')"

3 Answers 3

1

Using normalization method it will solve your problem by avoiding two queries:

SELECT WP.guid
FROM wp_posts WP,
     wp_postmeta WPM
WHERE wp_postmeta.meta_key = '_thumbnail_id'
  AND WPM.post_id=WP.yourForeignField
GROUP BY WP.guid
Sign up to request clarification or add additional context in comments.

Comments

0

You can use wordpress default function get_posts() like this.

$args = array('posts_per_page'=> -1,'meta_key'=> '_thumbnail_id' );
get_posts( $args );

You can get more information from here

Comments

0

I know in posgresql, a JOIN would do this. I don't know enough about word press, but I'll look into it and update this answer

UPDATE This should do it:

SELECT guid FROM wp_posts 
OUTER JOIN wp_postmeta on wp_postmeta.post_id = wp_posts.id
where wp_postmeta.meta_key = '_thumbnail_id';

The JOIN combines the two tables on a specific key.

Comments

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.