Last active
September 2, 2018 14:58
-
-
Save dbranes/4139486a3eb0d7ed4e03 to your computer and use it in GitHub Desktop.
WordPress: Ajax (POST) to update post meta key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Update post meta key via ajax POST request | |
* | |
* @see http://wpquestions.com/question/showLoggedIn/id/10604 | |
* | |
* On the remote site send a POST request to: | |
* | |
* http://example.tld/wp-admin/admin-ajax.php?action=update_post_meta | |
* | |
* with the following payload: | |
* | |
* security, post_id, meta_key, meta_value | |
* | |
* TODO: | |
* - Consider IP restriction. | |
* - Remember to update the security key below! | |
* | |
*/ | |
add_action( 'wp_ajax_update_post_meta', 'wpq_action_handler' ); | |
add_action( 'wp_ajax_nopriv_update_post_meta', 'wpq_action_handler' ); | |
function wpq_action_handler() { | |
// User input: | |
$args = array( | |
'security' => FILTER_SANITIZE_STRING, | |
'post_id' => FILTER_SANITIZE_NUMBER_INT, | |
'meta_key' => FILTER_SANITIZE_STRING, | |
'meta_value' => FILTER_SANITIZE_STRING, | |
); | |
$input = filter_input_array( INPUT_POST, $args ); | |
// Init: | |
$security = '123abc'; // Edit this! | |
$success = 0; | |
// Update meta key for a given post ID: | |
if( $security === $input['security'] ) { | |
$post = get_post( $input['post_id'] ); | |
if( ! is_null( $post ) ) { | |
if( get_post_meta( $post->ID, $input['meta_key'], true ) ) { | |
if( update_post_meta( $post->ID, $input['meta_key'], $input['meta_value'] ) ) { | |
$success = 1; | |
} | |
} | |
} | |
} | |
// Output: | |
if( $success ) { | |
wp_send_json_success(); | |
} else { | |
wp_send_json_error(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use this function in the page ?