I have a table wp_postmeta
meta_id bigint(20) unsigned PRI (NULL) auto_increment
post_id bigint(20) unsigned MUL 0
meta_key varchar(255) utf8_unicode_ci MUL (NULL)
meta_value longtext utf8_unicode_ci (NULL)
table smth like this:
meta_id post_id meta_key meta_value
1 1 area 12
2 1 rooms 2
3 2 rooms 3
I need to create a trigger that will add a string into this table if not exist
with meta_key = ‘area’ and meta_value = ‘0’.
Or UPDATE where meta_key = ‘area’ and meta_value = ‘NULL’.
But…
There could be a lot of meta_key for each post_id. and meta_key = ‘area’ for each post_id is set limit 1.
But problem is that not every post_id have the meta_key = ‘area’
so firstly need to create it!!
I have something like this now..(code below) it’s a part that will give the meta_value = ‘0’ of meta_key = ‘area’.But I can’t understand how do i must create this string if it’s not exist.
CREATE
TRIGGER `trigger` BEFORE INSERT ON `wp_postmeta`
FOR EACH ROW BEGIN
IF NEW.meta_key = 'area' AND NEW.meta_value IS NULL THEN
SET NEW.meta_value = '0';
END IF;
END;
$$
Since it looks like the
wp_posts
entry must be created before thewp_postmeta
entry (otherwise you won’t know thepost_id
), I’d put an after insert trigger onwp_posts
that inserts thewp_postmeta
row.Did that:
–> when i set a new posts it’s automatically set the area value => ‘0’
Second trigger I set for wp_postmeta: