0

I need to add a new meta key and value part only on posts where another key is present (regardless of its value).

I tried to use a query to automate it, but my SQL is quite limited

Here's what I tried:

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT
(SELECT meta.post_id
FROM `wp_postmeta` meta
INNER JOIN wp_posts posts ON meta.post_id = posts.id
WHERE meta.meta_key = 'existingkey'),
('newkey'),
('newvalue')

It returns the #1242 - Subquery returns more than 1 row error.

1
  • Why are you doing this with raw SQL rather than API?
    – Rarst
    Sep 22, 2013 at 21:29

1 Answer 1

2

There's no need to do this via raw SQL.

Make use of the WordPress core functions get_post_meta and update_post_meta.
Use them like so:

$existing = get_post_meta( $post_id, 'existingkey', true );

if ( ! empty( $existing ) ) {
    update_post_meta( $post_id, 'newkey', 'newvalue' );
}

Done.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.