Save meta field in wordpress? - php

I am trying to add a new select field to the page properties sidebar, but I am having trouble getting it to save the value.
This is what I have at the moment:
<?php
function addMyMeta() {
add_meta_box( 'my_custom_metabox', 'My Meta', 'setMyMeta', 'page', 'side', 'default' );
}
add_action( 'add_meta_boxes', 'addMyMeta' );
function setMyMeta() {
global $page;
$value = get_post_meta( $page->ID, 'my_custom_metabox', true );
?>
<fieldset>
<select name="my_custom_metabox" id="my_custom_metabox" autocomplete="off">
<option value="">Default</option>
<option value="my-value" <?php if($value == 'my-value') {echo ' selected ';}; ?>>My Value</option>
</select>
</fieldset>
<?php
}
function saveMyMeta( $page_id, $page ) {
if ( !isset( $_POST['my_custom_metabox'] ) ) {
update_post_meta( $page->ID, 'my_custom_metabox', $_POST['my_custom_metabox'] );
}
}
add_action( 'save_post', 'saveMyMeta', 1, 2 );
?>

Change global $page; to global $post; and $value = get_post_meta( $post->ID, 'my_custom_metabox', true );
function setMyMeta() {
global $post;
$value = get_post_meta( $post->ID, 'my_custom_metabox', true );
?>
<fieldset>
<select name="my_custom_metabox" id="my_custom_metabox" autocomplete="off">
<option value="">Default</option>
<option value="my-value" <?php if($value == 'my-value') {echo ' selected ';}; ?>>My Value</option>
</select>
</fieldset>
<?php
}

You should use isset instead of !isset in saveMyMeta function. Why would you want to run the update_post_meta if the value is not even set?
I prefer to add meta boxes using OOP because it's easy and saves you from having to worry about naming collisions in the global namespace.
Things to consider using while adding meta boxes:
wp_nonce_field() to validate that the contents of the form came from the location on the current site and not somewhere else.
selected() for select fields.
array_key_exists() to check if the key exists.
Sanitizing the values before saving or updating by using: sanitize_text_field(), sanitize_textarea_field(), intval(), floatval() etc.
Adding post_type suffix to save_post action hook. in your case it will be save_post_page.
Here is the full OOP code:
abstract class My_Custom_MetaBox {
/**
* Set up and add the meta box.
*/
public static function add() {
add_meta_box(
'my_custom_metabox', // Unique ID
'My Meta', // Box title
[ self::class, 'html' ], // Content callback, must be of type callable
'page', // Post type
'side', // The context within the screen where the box should display
'default' // Priority
);
}
/**
* Display the meta box HTML to the user.
*/
public static function html( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field('my_custom_meta_box', 'my_custom_meta_box_nonce');
$value = get_post_meta($post->ID, '_my_custom_metabox', true);
?>
<fieldset>
<select name="my_custom_metabox" id="my_custom_metabox" autocomplete="off">
<option value="" <?php selected($value, ''); ?>>Default</option>
<option value="my-value" <?php selected($value, 'my-value'); ?>>My Value</option>
</select>
</fieldset>
<?php
}
/**
* Save the meta box selections.
*/
public static function save( int $post_id ) {
// Check if our nonce is set.
if ( !isset($_POST['my_custom_meta_box_nonce']) ) {
return $post_id;
}
$nonce = $_POST['my_custom_meta_box_nonce'];
// Verify that the nonce is valid.
if ( !wp_verify_nonce($nonce, 'my_custom_meta_box') ) {
return $post_id;
}
// If this is an autosave, our form has not been submitted,
// so we don't want to do anything.
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user's permissions.
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can('edit_page', $post_id) ) {
return $post_id;
}
} else {
if ( !current_user_can('edit_post', $post_id) ) {
return $post_id;
}
}
// Saving or Updating the data
if ( array_key_exists('my_custom_metabox', $_POST) ) {
$selected_value = sanitize_text_field($_POST['my_custom_metabox']);
update_post_meta( $post_id, 'my_custom_metabox', $selected_value);
}
}
}
add_action( 'add_meta_boxes', ['My_Custom_MetaBox', 'add'] );
add_action( 'save_post_page', ['My_Custom_MetaBox', 'save'] );

Related

How to identify single instance of Wordpress default text widget?

I wanted to use the default WordPress text widget to the sidebar of pages where the title of the widget would dynamically change to add the title of the pages.
So I used the following code in my functions file:
function my_widget_title($title, $instance, $id_base) {
if ( is_singular() && 'text' == $id_base) {
return get_the_title($post->ID).__(' Custom Tour Inquiry');
}
else {
return $title;
}
}
add_filter ( 'widget_title' , 'my_widget_title', 10, 3);
This surely does what it is supposed to do, but it changes the titles of all other text widgets I try to use as well.
Is there any way I can pinpoint to one particular widget where this code will apply while the other text widgets will "behave normally"?
You could give the widget a specific name like "My Dynamic Text Widget". Then add detection of that title as a condition in your code like the following:
function my_widget_title($title, $instance, $id_base) {
if ( is_singular() && 'text' == $id_base && $title == 'My Dynamic Text Widget') {
return get_the_title($post->ID).__(' Custom Tour Inquiry');
}
else {
return $title;
}
}
add_filter ( 'widget_title' , 'my_widget_title', 10, 3);
Please replace your code with following one. I just added global $post to your code to get access to the specific post.
function my_widget_title($title, $instance, $id_base)
{
global $post;
if ( is_singular() && 'text' == $id_base) {
return get_the_title($post->ID).__(' Custom Tour Inquiry');
}
else
{
return $title;
}
}
add_filter ( 'widget_title' , 'my_widget_title', 10, 3);
Hope this will work for you as well.
Here is complete solution according to your situation. Kindly replace your old code with this new code and get your required result.
This will add checkbox into text widget and if you check this it will replace the title otherwise normal title will be render.
function kk_in_widget_form($t,$return,$instance){
if($t->id_base == "text"){
$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '', 'float' => 'none') );
?>
<p>
<input id="<?php echo $t->get_field_id('change_title'); ?>" name="<?php echo $t->get_field_name('change_title'); ?>" type="checkbox" <?php checked(isset($instance['change_title']) ? $instance['change_title'] : 0); ?> />
<label for="<?php echo $t->get_field_id('change_title'); ?>"><?php _e('Change Title'); ?></label>
</p>
<?php
$retrun = null;
}
return array($t,$return,$instance);
}
function kk_in_widget_form_update($instance, $new_instance, $old_instance){
$instance['change_title'] = isset($new_instance['change_title']);
return $instance;
}
add_action('in_widget_form', 'kk_in_widget_form',5,3);
//Callback function for options update (priorität 5, 3 parameters)
add_filter('widget_update_callback', 'kk_in_widget_form_update',5,3);
function my_widget_title($title, $instance, $id_base) {
if ( is_singular() && 'text' == $id_base && $instance['change_title']) {
return get_the_title($post->ID).__(' Custom Tour Inquiry');
}
else {
return $title;
}
}
add_filter ( 'widget_title' , 'my_widget_title', 10, 3);
Here is backend checkbox screen

How to set Payment Gateway by change order from admin side in WooCommerce

please help! I'm trying to define Payment Gateway by changing order details from admin.
As a default option I want to use 'bacs' payment gateway. Customer make order and then I want to change order and turn payment method to custom 'payment2' gateway.
For this, I've made metabox with checkbox which should turn on/off 'payment2' method and unset default 'bacs'. Checkbox working properly.
But, I can't get it to work. First of all, I can't get post meta with checkbox value. Check code below please:
function show_payment2_payment_gateway( $available_gateways ) {
$use_payment2 = get_post_meta( $post->ID, 'use_payment2', true );
if($use_payment2 == "yes") {
unset( $available_gateways['bacs'] );
}
else {
unset( $available_gateways['payment2'] );
}
return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'show_payment2_payment_gateway', 10, 1 );
UPD
This is my code for backend checkbox. As I said it's working well and save meta value as 'yes'
//
//Adding Meta container admin shop_order pages
//
add_action( 'add_meta_boxes', 'mv_add_meta_boxes' );
if ( ! function_exists( 'mv_add_meta_boxes' ) )
{
function mv_add_meta_boxes()
{
global $woocommerce, $order, $post;
add_meta_box( 'mv_other_fields', __('PAYMENT2','woocommerce'), 'mv_add_other_fields_for_packaging', 'shop_order', 'side', 'core' );
}
}
//
//adding Meta field in the meta container admin shop_order pages
//
if ( ! function_exists( 'mv_save_wc_order_other_fields' ) )
{
function mv_add_other_fields_for_packaging()
{
global $woocommerce, $order, $post;
$meta_field_data = get_post_meta( $post->ID, 'use_payment2', true );
$meta_field_data_checked = $meta_field_data["use_payment2"][0];
if($meta_field_data == "yes") $meta_field_data_checked = 'checked="checked"';
echo '
<label for="use_epay">TURN PAYMENT2 ON?</label>
<input type="hidden" name="mv_other_meta_field_nonce" value="' . wp_create_nonce() . '">
<input type="checkbox" name="use_payment2" value="yes" '.$meta_field_data_checked.'>';
}
}
//
//Save the data of the Meta field
//
add_action( 'save_post', 'mv_save_wc_order_other_fields', 10, 1 );
if ( ! function_exists( 'mv_save_wc_order_other_fields' ) )
{
function mv_save_wc_order_other_fields( $post_id ) {
// We need to verify this with the proper authorization (security stuff).
// Check if our nonce is set.
if ( ! isset( $_POST[ 'mv_other_meta_field_nonce' ] ) ) {
return $post_id;
}
$nonce = $_REQUEST[ 'mv_other_meta_field_nonce' ];
//Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce ) ) {
return $post_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user's permissions.
if ( 'page' == $_POST[ 'post_type' ] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
}
// --- Its safe for us to save the data ! --- //
// Sanitize user input and update the meta field in the database.
update_post_meta( $post_id, 'use_payment2', $_POST[ 'use_payment2' ] );
}
}
UPD
This is working code for Back-End (custom checkbox metabox). It save checkbox value and change payment method in order details:
//
//Adding Meta container admin shop_order pages
//
add_action( 'add_meta_boxes', 'mv_add_meta_boxes' );
if ( ! function_exists( 'mv_add_meta_boxes' ) )
{
function mv_add_meta_boxes()
{
global $woocommerce, $order, $post;
add_meta_box( 'mv_other_fields', __('PAYMENT2','woocommerce'), 'mv_add_other_fields_for_packaging', 'shop_order', 'side', 'core' );
}
}
//
//adding Meta field in the meta container admin shop_order pages
//
if ( ! function_exists( 'mv_save_wc_order_other_fields' ) )
{
function mv_add_other_fields_for_packaging()
{
global $woocommerce, $order, $post;
$meta_field_data = get_post_meta( $post->ID, 'use_payment2', true );
echo '<label for="use_payment2">USE PAYMENT2?</label>
<input type="hidden" name="mv_other_meta_field_nonce" value="' . wp_create_nonce() . '">';
if($meta_field_data == "yes") {
$meta_field_data_checked = 'checked="checked"';
echo'<input type="checkbox" name="use_payment2" value="yes" '.$meta_field_data_checked.'>';
}
else {
echo'<input type="checkbox" name="use_payment2" value="yes">';
}
}
}
//Save the data of the Meta field
add_action( 'save_post', 'mv_save_wc_order_other_fields', 10, 1 );
if ( ! function_exists( 'mv_save_wc_order_other_fields' ) )
{
function mv_save_wc_order_other_fields( $post_id ) {
// We need to verify this with the proper authorization (security stuff).
// Check if our nonce is set.
if ( ! isset( $_POST[ 'mv_other_meta_field_nonce' ] ) ) {
return $post_id;
}
$nonce = $_REQUEST[ 'mv_other_meta_field_nonce' ];
//Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce ) ) {
return $post_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user's permissions.
if ( 'page' == $_POST[ 'post_type' ] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
}
// --- Its safe for us to save the data ! --- //
// Sanitize user input and update the meta field in the database.
$use_payment2 = sanitize_text_field($_POST[ 'use_payment2' ]);
update_post_meta( $post_id, 'use_payment2', $use_payment2 );
if($_POST[ 'use_payment2' ] == 'yes') {
update_post_meta( $post_id, '_payment_method', 'payment2' );
}
elseif (get_post_meta( $post_id, '_payment_method', true ) != 'bacs') {
update_post_meta( $post_id, '_payment_method', 'bacs' );
}
}
}
But, how I can use checkbox state on my front-end? I still can't get checkbox value using this code:
function show_payment2_payment_gateway( $available_gateways ) {
global $woocommerce, $order, $post;
$payment_method = get_post_meta( $post_id, 'use_payment2', true );
if(isset($payment_method) == 'yes') {
unset( $available_gateways['bacs'] );
}
else {
unset( $available_gateways['payment2'] );
}
return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'show_payment2_payment_gateway', 10, 1 );
Now, it's always showing Payment2 option even if checkbox is checked or unchecked.
Update 2 related to your comments (and your question update)
The hook your are using is a front end hook (not admin), so it will not work.
To achieve what want, you need to replace some code inside the function that is going to save your custom checkbox value when you update the order in backend (Admin) edit order pages.
So your code will be now like this:
add_action( 'save_post', 'mv_save_wc_order_other_fields', 10, 1 );
if ( ! function_exists( 'mv_save_wc_order_other_fields' ) )
{
function mv_save_wc_order_other_fields( $post_id ) {
// We need to verify this with the proper authorization (security stuff).
// Check if our nonce is set.
if ( ! isset( $_POST[ 'mv_other_meta_field_nonce' ] ) )
return $post_id;
// Passing the value to a variable
$nonce = $_REQUEST[ 'mv_other_meta_field_nonce' ];
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( 'page' == $_POST[ 'post_type' ] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
// --- Its safe for us to save the data ! --- //
// Sanitize user input and update the meta field in the database.
$use_payment2 = sanitize_text_field($_POST[ 'use_payment2' ]);
update_post_meta( $post_id, 'use_payment2', $use_payment2 );
// Updating securely the data with your conditions
if($use_payment2 == 'yes')
update_post_meta( $post_id, '_payment_method', 'payment2' );
else
update_post_meta( $post_id, '_payment_method', 'bacs' );
}
}
This should work as you expect now…
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
As this code comme from one of my answers, you are not obliged to keep the same functions beginning names with "mv_" that was related to the username of the question. You can change it to "dan_" for example…
Reference: WooCommerce : Add custom Metabox to admin order page
The function that lists default payment gateways in WooCommerce is core_gateways(). This function is hooked to a filter called woocommerce_payment_gateways. So, the first step is to remove that filter and add our own. I will work only in the functions.php file within the theme folder (remember? Never modify core files). To do so, we’ll use the remove_filter() and the add_filter() functions:
remove_filter( 'woocommerce_payment_gateways', 'core_gateways' );
add_filter( 'woocommerce_payment_gateways', 'my_core_gateways' );
Now that we have removed the filter, you can see that in the add_filter() function we have a callback named my_core_gateways. This callback is the name of a function that will replace the default core_gateways() function. This function is the one that list WooCommerce default payment gateways. I will change the content of that function and replace the call to the WC_Gateway_BACS class. This class is the bank transfer default class. Here is the code of that new function:
/**
* core_gateways function modified.
*
* #access public
* #param mixed $methods
* #return void
*/
function my_core_gateways( $methods ) {
$methods[] = 'WC_Gateway_BACS_custom';
$methods[] = 'WC_Gateway_Cheque';
$methods[] = 'WC_Gateway_COD';
$methods[] = 'WC_Gateway_Mijireh';
$methods[] = 'WC_Gateway_Paypal';
return $methods;
}
As you can see the only change I made is that I replaced WC_Gateway_BACS by WC_Gateway_BACS_custom.
Are you still with me huh? Well, to summarize, I need to remove the filter that calls the default payment gateways, and use a custom function. In this custom function, I replace the call to the BACS class, and now i need to create this new BACS class. To do so, use that code:
class WC_Gateway_BACS_custom extends WC_Gateway_BACS {
/**
* Process the payment and return the result
*
* #access public
* #param int $order_id
* #return array
*/
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
// Mark as processing (that's what we want to change!)
$order->update_status('processing', __( 'Awaiting BACS payment', 'woocommerce' ));
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
$woocommerce->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order->id, get_permalink(woocommerce_get_page_id('thanks'))))
);
}
}
In this snippet, I only changed the default status from “on-hold” to “processing”…. and boom the magic appears! Now each order paid using the BACS payment gateway will be marked as processing, not as on hold.
After few days of headache I found easy way how to show defined payment gateway only when I send link to customer.
Now customer can make order with default 'bacs' method, and Admin can check it before payment. Then admin change order status to Waiting for payment and link sends to customer. When customer opens link, my custom payment gateway becomes active.
I decided to use woocommerce endpoints to check if it 'order-pay' page. I used code below:
function show_payment2_payment_gateway( $available_gateways ) {
global $woocommerce, $order, $post;
if (is_wc_endpoint_url( 'order-pay' )) {
unset( $available_gateways['bacs'] );
}
else {
unset( $available_gateways['payment2'] );
}
return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'show_payment2_payment_gateway', 10, 1 );
Now it works exactly as I wanted before. I hope this will be useful. Thanks to #LoicTheAztec for help!

Validate custom fields in wordpress post

I have a custom post type speaker and in speaker I have a custom field speaker_organization. How can I validate this and display error in admin notice.
add_action( 'add_meta_boxes', 'speaker_organization_box' );
function speaker_organization_box() {
add_meta_box(
'speaker_organization',
__( 'Organization', 'dbem' ),
'speaker_organization_box_content',
'speaker',
'side',
'high'
);
}
function speaker_organization_box_content( $post ) {
// generate a nonce field
wp_nonce_field( basename( __FILE__ ), 'dbem-speaker-organization-nonce' );
// get previously saved meta values (if any)
$speaker_organization = get_post_meta( $post->ID, 'speaker_organization', true );
echo '<label for="speaker_organization"></label>';
echo '<input type="text" id="speaker_organization" name="speaker_organization" placeholder="Organization Name" value="'.$speaker_organization.'" />';
}
function speaker_organization_box_save( $post_id ) {
$speaker_organization = $_POST['speaker_organization'];
update_post_meta( $post_id, 'speaker_organization', $speaker_organization );
}
add_action( 'save_post', 'speaker_organization_box_save' );
using
add_action( 'admin_notices', 'my_admin_notice' );
or using validate js
add_action('admin_enqueue_scripts', 'add_my_js');
function add_my_js(){
wp_enqueue_script('my_validate', 'path/to/jquery.validate.min.js', array('jquery'));
wp_enqueue_script('my_script_js', 'path/to/my_script.js');
}
jQuery().ready(function() {
jQuery("#post").validate();
});
<input type="text" name="my_custom_text_field" class="required"/>
function wpse_update_post_custom_values($post_id, $post) {
// Do some checking...
if($_POST['subhead'] != 'value i expect') {
// Add an error here
$errors->add('oops', 'There was an error.');
}
return $errors;
}
add_action('save_post','wpse_update_post_custom_values',1,2);
validate js code
using condition + admin notice

How to save custom meta boxes in Wordpress

I've been trying to get my custom meta box data to save in Wordpress, and I haven't had any luck. I've tried researching other posts, but since everyone does it a little bit differently, I haven't had any success at using the tutorials and other posts out there.
I created a metabox:
add_action( 'add_meta_boxes', 'ic_add_heading_box' );
function ic_add_heading_box( $post ) {
add_meta_box(
'Meta Box',
'Heading Titles',
'ic_heading_box_content',
'page',
'normal',
'high'
);
}
function ic_heading_box_content( $post ) {
echo '<label>Main Heading (h1)</label>';
echo '<input type="text" name="heading_box_h1" value="" />';
echo '<label>Sub Heading (h3)</label>';
echo '<input type="text" name="heading_box_h3" value="" />';
}
I just can't for the life of me get the data I insert in to the fields to save in Wordpress. Any help would be greatly appreciated.
The function you are using is only a display function.
You are not actually doing nothing with the data . it is only for creating the metabox. not handling it.
You need to add
add_action( 'save_post', 'myplugin_save_postdata' );
and then use update_post_meta() with a function like in the codex example :
function myplugin_save_postdata( $post_id ) {
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions. If want
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
/* OK, its safe for us to save the data now. */
// Sanitize user input. if you want
$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata ); // choose field name
}

How to add a field in edit post page inside Publish box in Wordpress?

I want to add a new checkbox field inside Publish block in add/edit post page. Does anyone have idea how to do that ?
I have finally found the solution. I hope it will be of good use for somebody.
add_action( 'post_submitbox_misc_actions', 'publish_in_frontpage' );
function publish_in_frontpage($post)
{
$value = get_post_meta($post->ID, '_publish_in_frontpage', true);
echo '<div class="misc-pub-section misc-pub-section-last">
<span id="timestamp">'
. '<label><input type="checkbox"' . (!empty($value) ? ' checked="checked" ' : null) . 'value="1" name="publish_in_frontpage" /> Publish to frontpage</label>'
.'</span></div>';
}
function save_postdata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if(empty($postid) || $_POST['post_type'] != 'article' ) return false;
if($_POST['action'] == 'editpost'){
delete_post_meta($postid, 'publish_in_frontpage');
}
add_post_meta($postid, 'publish_in_frontpage', $_POST['publish_in_frontpage']);
}
rbncha's code didn't work out of the box and needed a lot of tweaking, the code below is what I came up with. I've added some comments which explains everything thoroughly.
The following code adds a checkbox in the publish block of posts (you can easily change the post type), and stores/retrieves the value in/from the database. With some minor tweaking you could easily add a text field or anything you like.
It should be noted that you have to change my_ to a unique key for your theme or plugin!
add_action( 'post_submitbox_misc_actions', 'my_featured_post_field' );
function my_featured_post_field()
{
global $post;
/* check if this is a post, if not then we won't add the custom field */
/* change this post type to any type you want to add the custom field to */
if (get_post_type($post) != 'post') return false;
/* get the value corrent value of the custom field */
$value = get_post_meta($post->ID, 'my_featured_post_field', true);
?>
<div class="misc-pub-section">
<?php //if there is a value (1), check the checkbox ?>
<label><input type="checkbox"<?php echo (!empty($value) ? ' checked="checked"' : null) ?> value="1" name="my_featured_post_field" /> Featured on frontpage</label>
</div>
<?php
}
add_action( 'save_post', 'my_save_postdata');
function my_save_postdata($postid)
{
/* check if this is an autosave */
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
/* check if the user can edit this page */
if ( !current_user_can( 'edit_page', $postid ) ) return false;
/* check if there's a post id and check if this is a post */
/* make sure this is the same post type as above */
if(empty($postid) || $_POST['post_type'] != 'post' ) return false;
/* if you are going to use text fields, then you should change the part below */
/* use add_post_meta, update_post_meta and delete_post_meta, to control the stored value */
/* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */
if(isset($_POST['my_featured_post_field'])){
/* store the value in the database */
add_post_meta($postid, 'my_featured_post_field', 1, true );
}
else{
/* not marked? delete the value in the database */
delete_post_meta($postid, 'my_featured_post_field');
}
}
If you want to read more about custom fields see here: http://codex.wordpress.org/Custom_Fields
Well!, I could not find a solution to add a field in Publish Block. For the temporary solution, I have added new block by simply adding simple codes like below.
add_action( 'admin_init', 'category_metabox');
//add new publish to frontpage box
add_meta_box(
'publish_in_frontpage',
'Publish in Frontpage',
'publish_in_frontpage_callback',
'article',
'side',
'high'
);
function publish_in_frontpage_callback($post)
{
$value = get_post_meta($post->ID, '_publish_in_frontpage', true);
echo '<label><input type="checkbox"' . (!empty($value) ? ' checked="checked" ' : null) . 'value="1" name="publish_in_frontpage" /> Publish to frontpage</label>';
}
add_action( 'save_post', 'save_postdata');
function save_postdata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if(empty($postid) || $_POST['post_type'] != 'article' ) return false;
if($_POST['action'] == 'editpost'){
delete_post_meta($postid, 'publish_in_frontpage');
}
add_post_meta($postid, 'publish_in_frontpage', $_POST['publish_in_frontpage']);
}
Use the Advanced Custom Fields plugin for wordpress.

Categories