0

I would like to remove some metadata if I save post with another metadata with custom post type in my plugin.. I tried to use init hook and iterate array from get_posts function but it doesn't work and too I tried with save_post hook but it doesn't work too..

Attaching action in my __construct function (in class with plugin functions):

add_action('save_post_survey', [$this, 'survey_start_type_validation']);

And here I trying to check if metadata exists and if yes, then delete the old:

function survey_start_type_validation($post_id)
    {
            $type_of_running = get_post_meta($post_id, 'spusteni_dotazovani');

            if($type_of_running == 'manually_run') {
                if(metadata_exists($post_id, 'datum_a_cas_planovaneho_spusteni')) {
                    delete_post_meta($post_id, 'datum_a_cas_planovaneho_spusteni');
                }
            } elseif($type_of_running == 'planned_run') {
                if(metadata_exists($post_id, 'running_status')) {
                    delete_post_meta($post_id, 'running_status');
                }
            }

    }

I can't figure out what's wrong with my code.. Can anyone advice me?

1
  • Have you check the function paramaters in wordpress documentation? seems like you are passing the incorrect arguments to it, metadata_exists( string $meta_type, int $object_id, string $meta_key ) Jan 14, 2022 at 15:03

1 Answer 1

0

Try applying these and your code might work:

  1. Looking at the expressions $type_of_running == 'manually_run' and $type_of_running == 'planned_run', where you're expecting get_post_meta() to return a single meta value, you should then set the 3rd parameter to true:

    // Set the 3rd param to true to get a single meta value.
    $type_of_running = get_post_meta($post_id, 'spusteni_dotazovani', true);
    
  2. metadata_exists() requires 3 parameters, i.e. the meta type (e.g. post for post meta or term for term meta), the "object" ID (e.g. post ID or term ID) and the meta key, so make sure you pass the correct parameters like so:

    if(metadata_exists('post', $post_id, 'datum_a_cas_planovaneho_spusteni')) {
        delete_post_meta($post_id, 'datum_a_cas_planovaneho_spusteni');
    }
    

    and

    if(metadata_exists('post', $post_id, 'running_status')) {
        delete_post_meta($post_id, 'running_status');
    }
    
1
  • 1
    Thanks! It helped me so much.. :) Jan 14, 2022 at 17:55

Your Answer

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

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