I need the following functionality. Whenever my custom post type is updated or saved I need to overwrite certain custom post metas.
I need to make sure this only affects posts of the post type ‘VA_LISTING_PTYPE’ and posts that have the have for the ‘meta_key’ => ‘featured-cat’ the ‘meta_value’ => 1
The code I’m using at the moment is the following (not working)
//Remove urls from free listings
function remove_url_free_post( $post_id ) {
$slug = 'VA_LISTING_PTYPE',
if ( $slug != $_POST['post_type'] ) {
return;
}
$meta_values = get_post_meta( $post_id, 'featured-cat', true );
if ( $meta_values != 1 ) {
return;
}
update_post_meta($post_id, 'website', '');
update_post_meta($post_id, 'twitter', '');
update_post_meta($post_id, 'facebook', '');
}
add_action('save_post', 'remove_url_free_post');
I also tried different action hooks like pre_post_update coming from this answer
I just can’t seem to get it working. The only really ugly fix that is working for me right now is this one:
//Remove urls from free listings
function remove_url_free_post() {
//Fetches all the listings that have featured cat which equals free listing for us
$r = new WP_Query(
array(
'post_type' => VA_LISTING_PTYPE,
'no_found_rows' => true,
'meta_key' => 'featured-cat',
'meta_value' => 1
) );
if ( $r->have_posts() ) :
while ( $r->have_posts() ) : $r->the_post();
//removes the website, twitter and facebook
$post_id3 = get_the_ID();
update_post_meta($post_id3, 'website', '');
update_post_meta($post_id3, 'twitter', '');
update_post_meta($post_id3, 'facebook', '');
endwhile;
endif;
}
//Not ideal at all as called everytime, save_post not working as intended
add_action('wp_footer', 'remove_url_free_post');
You’re right to use ‘save_post’ action hook.
Try this:
if you’re on WordPress 3.7 or higher, you can use it this way:
I hope it work with you.