terms – $_POST sometimes empty even though isn’t when using edited_[taxonomy] hook

Question

I’m trying to save some term meta for some custom fields I have added via the [taxonomy]_edit_form_fields hook, I then save the data from these fields on edit with the hook action edited_[taxonomy].

For a few different reasons I’m deleting all term meta via wpdb with my prefix and then looping through $_POST, finding my prefixed form names and adding the term meta, this works fine on my local environment, but on another environment (and only occasionally) the adding of term meta does not happen, the $wpdb query still deletes all the term meta first.

It’s almost like sometimes $_POST is empty, but I’ve caught when it happens and used var_dump on $_POST and can see the data is coming through, any help with why this might occasionally happen and potential code edits to stop this occurring?

My code is:

function save_my_taxonomy( $term_id ) {

    global $wpdb;

    if ( !empty( $_POST ) ) {

        // Delete all term meta with my term name (this ensures this if an option was previously populated and no longer is and isn't submitted such as checkboxes, the removal occurs)

        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM `{$wpdb->prefix}termmeta` WHERE `term_id` = %d AND `meta_key` LIKE %s;",
                $term_id,
                'my_taxonomy_name_%'
            )
        );

        // Loop all $_POST

        foreach ( $_POST as $key => $value ) {

            // If my field

            if ( strpos( $key, 'my_taxonomy_name_' ) === 0 ) {

                update_term_meta( $term_id, $key, $value );

            }

        }

    }

}
add_action( 'edited_my_taxonomy_name', 'save_my_taxonomy' );

in progress 0
bigdaveygeorge 1 month 2021-08-06T09:11:55-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-08-08T08:55:21-05:00

    I think this was maybe the wpdb query was running slower than the adding of meta, I’ve replaced the wpdb query with a get terms, foreach, delete and this seems to have solved the issue.

Leave an answer

Browse
Browse