WebArtisan
WebArtisan

Reputation: 4227

update_post_meta not work only when save data, not for update

I have some trouble with regular wordpress functions in class methods I save post meta like this and Its works fine:

public function saveMetadata( $postname ) {
    $post_id     = $_POST[ 'post_ID' ];
    $post_holder = $_POST[ $postname ];

    update_post_meta( $post_id, $postname, $post_holder );

}

But when i try update meta use same method, it doesnt work! why?

Thats i invoke this

//creation and run object
add_action( 'save_post', $quality->saveMetadata( 'project_quality' ) );

Upvotes: 1

Views: 9610

Answers (3)

Harkály Gergő
Harkály Gergő

Reputation: 841

I had similar problem, I tried to update an order's post meta in my class function with WP AJAX, but get_post_meta() worked, update not, so I solved it with deletetion of actual meta and add again new data, short example:

public function order_decision_ajax_callback()
{
    $current_custom_postmeta = get_post_meta($orderID, 'custompostmeta', true);
    if($current_custom_postmeta)
    {
        delete_post_meta($orderID, 'custompostmeta');
    }
    add_post_meta($orderID, 'custompostmeta', $newmeta);
} 

Upvotes: 1

WebArtisan
WebArtisan

Reputation: 4227

So, finally I solved this by using anonimous functions inside action, and send variable $post_id inside it. It seems, wordpress expext id exacly from this var, strange but it works. Here the code:

public function saveMetadata() {

    add_action('save_post', function($post_id){
        if(isset($_POST[$this->id])) {
            update_post_meta( $post_id, $this->id, $_POST[ $this->id] );
        }
    });
}

Note: without any validation.

And invoke it, ofc:

//object creation and run
$someObject->saveMetadata();

Upvotes: 0

silver
silver

Reputation: 5331

Try adding priority

add_action( 'save_post', $quality->saveMetadata( 'project_quality' ), 999 );

also, try checking the database table wp_postmeta to verify if there's project_quality

I've having the same issue with update_post_meta functions but its because of Yoast SEO Field priority which I can't figure out

This might help

update_post_meta for Wordpress Yoast SEO

Upvotes: 0

Related Questions