2

I'm using a generic wordpress sql statement to grab the post titles. I want to replace the post titles with a postmeta value of the all in one seo plugin is an all in one seo title exists for the post.

How do I use this if statement in the sql command?

Existing code without the all in one if statement.

//Limit to last 30 days, 1,000 items                    
$rows = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_date_gmt, $wpdb->posts.post_title
                    FROM $wpdb->posts, $wpdb->postmeta
                    WHERE $wpdb->posts.post_status='publish' 
                    AND (DATEDIFF(CURDATE(), post_date_gmt)<=30)
                    $includeMe
                    ORDER BY $wpdb->posts.post_date_gmt DESC
                    LIMIT 0, 1000");    

New Function That's Getting an Error Now after Phil's Answer

$rows = $wpdb->get_results("SELECT COALESCE($wpdb->postmeta.meta_value, $wpdb->posts.post_title) AS post_title, $wpdb->posts.post_date_gmt, $wpdb->posts.ID
                    FROM $wpdb->posts
                    LEFT JOIN $wpdb->post_meta
                    ON $wpdb->posts.ID = $wpdb->postmeta.post_id
                    AND $wpdb->postmeta.meta_key = '_aioseop_title' 
                    WHERE $wpdb->posts.post_status='publish' 
                    AND (DATEDIFF(CURDATE(), post_date_gmt)<=30)
                    $includeMe
                    ORDER BY $wpdb->posts.post_date_gmt DESC
                    LIMIT 0, 1000");    

1 Answer 1

1

I'd use COALESCE() with a LEFT JOIN on the post_meta table. For example (note, generic query only, not directly related to Wordpress)

SELECT COALESCE(post_meta.value, posts.title) AS title
FROM posts
LEFT JOIN post_meta
ON posts.id = post_meta.post_id
AND post_meta.key = 'some_meta_key'
Sign up to request clarification or add additional context in comments.

8 Comments

Cool thanks - never saw the coalesce() function before - going to try now.
Phil, I just changed my function and I'm getting an error - I'm about to post it back in the question - you mind taking a look?
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '_aioseop' at line 4]
I think it's because of the WHERE directly after the ON variables
@Bob Is it $wpdb->post_meta or $wpdb->postmeta? You use both and I'm guessing the the latter is the valid one.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.