Created
September 12, 2014 04:58
-
-
Save thefuxia/784822c3118dd7b3a2be to your computer and use it in GitHub Desktop.
Test post meta fields in WordPress
This file contains 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
<?php # -*- coding: utf-8 -*- | |
/** | |
* Plugin Name: Post Meta Test | |
* Description: Adds a simple post meta field below the title to the post editor screen. | |
* Plugin URI: http://marketpress.com/ | |
* Version: 2014.09.12 | |
* Author: MarketPress, Thomas Scholz | |
* Author URI: http://marketpress.com/ | |
* Licence: GPL 2 | |
* License URI: http://opensource.org/licenses/GPL-2.0 | |
*/ | |
namespace MarketPress\Test; | |
if ( 'POST' === $_SERVER[ 'REQUEST_METHOD' ] ) | |
add_action( 'save_post', __NAMESPACE__ . '\save_field', 10, 2 ); | |
else | |
add_action( 'edit_form_after_title', __NAMESPACE__ . '\show_field' ); | |
/** | |
* @param \WP_Post $post | |
* @return void | |
*/ | |
function show_field( \WP_Post $post ) { | |
$key = get_key(); | |
$field_id = $key . '_id'; | |
$value = get_post_meta( $post->ID, $key, TRUE ); | |
wp_nonce_field( get_nonce_action(), get_nonce_name() ); | |
?> | |
<p> | |
<label for="<?php print $field_id; ?>"> | |
Post Meta Test | |
<?php | |
print "<input type='text' id='$field_id' name='$key' value='$value' class='regular-text'>"; | |
?> | |
</label> | |
</p> | |
<?php | |
} | |
/** | |
* @param int $post_id | |
* @param \WP_Post $post | |
* @return bool|int | |
*/ | |
function save_field( $post_id, \WP_Post $post ) { | |
$key = get_key(); | |
if ( ! is_valid_request( $post ) ) | |
return FALSE; | |
if ( empty ( $_POST[ $key ] ) ) | |
return delete_post_meta( $post_id, $key ); | |
return update_post_meta( $post_id, $key, $_POST[ $key ] ); | |
} | |
/** | |
* @param \WP_Post $post | |
* @return bool | |
*/ | |
function is_valid_request( \WP_Post $post ) { | |
if ( wp_is_post_autosave( $post ) ) | |
return FALSE; | |
if ( wp_is_post_revision( $post ) ) | |
return FALSE; | |
if ( empty ( $_POST[ get_nonce_name() ] ) ) | |
return FALSE; | |
return wp_verify_nonce( $_POST[ get_nonce_name() ], get_nonce_action() ); | |
} | |
/** | |
* @return string | |
*/ | |
function get_key() { | |
return '_marketpress_meta_test'; | |
} | |
/** | |
* @return string | |
*/ | |
function get_nonce_action() { | |
return 'marketpress_nonce_action'; | |
} | |
/** | |
* @return string | |
*/ | |
function get_nonce_name() { | |
return 'marketpress_nonce_name'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment