views:

47

answers:

2

I need a SQL query that I can run in PHPmyadmin that adds a custom field (with a value) to all existing posts. Can anyone help? Is this even possible?

A: 

Yes, this is possible, but it is inadvisable. Your data could be lost the next time you upgrade. If you're not planning on upgrading, then you're leaving gaping security holes in your site. The recommended way to do this is to use the postmeta table. This is what it exists for.

EDIT

Now that I better understand the question, ignore the part above. See comments for more details.

John P Bloch
i didn't rate your answer. i don't have a account here so I can't even do that anyway :)
Alex
I think Alex means how can he create Wordpress custom fields (which would use the `postmeta` table) with SQL, rather than how can he add new columns to the posts table (which seems to be how you've interpreted it John). The down vote seems uncharitable though. As for your question Alex, I don't think you can do this using a single SQL statement, you'd need to retrieve all the post IDs then add a row to the `postmeta` table for each post containing your custom field data.
Richard M
Ah. I think you're right, Richard. FWIW, Alex, I didn't ever think you had voted it down. Generally, people asking questions are interested in finding the answer and will communicate before voting down. The 'you' in my comment should have all be impersonal pronouns.
John P Bloch
Richard is right. There doesn't seem to be a way to use SQL to do this. I'd suggest using a plugin script that can be executed from the admin area to do what Richard suggested.
John P Bloch
+1  A: 

You can do this by inserting into the postmeta table using a select query on the posts table.

In the example below I use wp_ as my table prefix, your setup may differ.

insert into wp_postmeta (post_id, meta_key, meta_value) 
select ID, 'my-key', 'my-value' from wp_posts;
windyjonas
works. thanks!is there any way I can check if the meta key exists so I don't add duplicates?
Alex