To display checkboxes on front end in wordpress metabox - php

I am building a plugin that provides author names as checkboxes on the admin side. The names that have been checked should be displayed on the front-end side in Wordpress.
I have written the code for the admin side, i.e. my code provides checkboxes and its values are saved.
How should the checked values be displayed on the front end?
<?php
add_action('add_meta_boxes', 'add_custom_boxx');
function add_custom_boxx($post) {
add_meta_box(
'Meta Box', // ID, should be a string.
'Featured People', // Meta Box Title.
'people_meta_boxx', // Your call back function, this is where your form field will go.
'post', // The post type you want this to show up on, can be post, page, or custom post type.
'side', // The placement of your meta box, can be normal or side.
'core' // The priority in which this will be displayed.
);
}
function people_meta_boxx($post) {
wp_nonce_field('my_awesome_nonce', 'awesome_nonce');
$checkboxMeta = get_post_meta($post->ID);
$html = "";
$blogusers = get_users('blog_id=1&orderby=nicename&role=author');
// Array of WP_User objects.
foreach ($blogusers as $user) {
?>
<input type="checkbox"
name="<?php echo $user->display_name;?>"
id="<?php echo $user->display_name;?>"
<?php if (isset($checkboxMeta[$user->display_name])) {
checked($checkboxMeta[$user->display_name][0], 'yes'); } ?> />
<?php echo $user->display_name;?><br />
<?php
} // end foreach
?>
<?php } // end function people_meta_boxx
add_action('save_post', 'save_people_checkboxesx');
function save_people_checkboxesx($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if ((isset($_POST['my_awesome_nonce'])) && (! wp_verify_nonce($_POST['my_awesome_nonce'], plugin_basename(__FILE__))))
return;
if ((isset($_POST['post_type'])) && ('page' == $_POST['post_type'])) {
if (! current_user_can('edit_page', $post_id)) {
return;
}
} else {
if (! current_user_can('edit_post', $post_id)) {
return;
}
}
$blogusers = get_users('blog_id=1&orderby=nicename&role=author');
// Array of WP_User objects.
foreach ($blogusers as $user) {
//saves bob's value
if (isset($_POST[$user->display_name])) {
update_post_meta($post_id, $user->display_name, 'yes');
} else {
update_post_meta($post_id, $user->display_name, 'no');
}
}
}
function display_contributors($content) {
//Code to be inserted here.
return $content;
}
add_filter('the_content','display_contributors');
?>

Related

Save meta field in wordpress?

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'] );

wordpress API: how to update custom meta box

I've created a custom meta box, but i can't update that through api rest. This is my code. The var $_POST in a function save_custom_meta_box is always empty when I send a request.
Create meta box
add_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );
if (!function_exists('adding_custom_meta_boxes')) {
function adding_custom_meta_boxes( $post_type, $post ) {
add_meta_box(
"demo-meta-box",
"Custom Meta Box",
"custom_meta_box_markup",
"post",
"side",
"high",
null
);
}
}
Storing Meta Data
add_action("save_post", "save_custom_meta_box", 10, 3);
function save_custom_meta_box($post_id, $post, $update)
{
if(!current_user_can("edit_post", $post_id)){
return $post_id;
}
if($post->post_type != "post"){
return $post_id;
}
$meta_box_checkbox_value = "";
if(isset($_POST["meta-box-checkbox"]))
{
$meta_box_checkbox_value = $_POST["meta-box-checkbox"];
}
update_post_meta($post_id, "meta-box-checkbox", $meta_box_checkbox_value);
}
SOLUTION:
Use action rest_after_insert_post.
add_action('rest_after_insert_post', 'wp_kama_rest_after_insert_post_type_action', 10, 3);
function wp_kama_rest_after_insert_post_type_action( $post, $request, $creating ) {
if ($creating) {
return;
}
$body = json_decode($request->get_body());
if($body->metaBoxCheckbox)
{
update_post_meta($post->ID, "meta-box-checkbox", $body->metaBoxCheckbox);
}
return;
}

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

wordpress meta-box confusion

My question is on save($postID) function. Here there is a parameter $postID which is using in the function for saving as id. I see that this $postID has a null value. How does actual post id work for $postID?
This is the simple meta-box code
/* simple meta box */
/* creating field */
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
function testfield(){
global $post;
?>
<input type="text" name="Asif" id="Asif" value="<?php echo get_post_meta($post->ID, 'Sumon', true); ?>">
<?php
}
/* end of creating field */
/* storing field after pressing save button */
add_action('save_post', 'save');
function save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['Asif'])
{
update_custom_meta($postID, $_POST['Asif'], 'Sumon');
}
}
}
// saving in postmeta table
function update_custom_meta($postID, $newvalue, $field_name){
if(!get_post_meta($postID, $field_name)){
// create field
add_post_meta($postID, $field_name, $newvalue);
}
else{
//update field
update_post_meta($postID, $field_name, $newvalue);
}
}
You've used the wrong Action Hook.
Instead of using add_action('admin_menu', 'my_post_options_box');
Use add_action('add_meta_boxes', 'my_post_options_box');
add_action('add_meta_boxes', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
You can look in to http://codex.wordpress.org/Function_Reference/add_meta_box for detailed overview.
Some SO Question/Answers you can look into.
Add multiple dates to custom post type in Wordpress
how to add a meta box to wordpress pages
While Saving Post
Action save_post automatically passes Post ID to callback function. Which you can use inside your callback function.
Some already answered quesitons
https://wordpress.stackexchange.com/questions/41912/perform-an-action-when-post-is-updated-published
Reference
http://codex.wordpress.org/Plugin_API/Action_Reference/save_post

Wordpress add_meta_box() weirdness

The code below is working nearly flawlessly, however my value for page title on one of my pages keeps coming up empty after a few page refreshes... It sticks for awhile, then it appears to reset to empty. I'm thinking I must have a conflict in the code below, but I can't quite figure it.
I'm allowing the user to set a custom page title for posts as well as pages via a custom "post/page title input field). Can anyone see an obvious issue here that might be resetting the page title to blank?
// ===================
// = POST OPTION BOX =
// ===================
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
//add_meta_box( $id, $title, $callback, $page, $context, $priority );
add_meta_box('post_header', 'Custom Post Header Code (optional)', 'custom_post_images', 'post', 'normal', 'low');
add_meta_box('post_title', 'Custom Post Title', 'custom_post_title', 'post', 'normal', 'high');
add_meta_box('post_title_page', 'Custom Post Title', 'custom_post_title', 'page', 'normal', 'high');
add_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', 'page', 'normal', 'core');
add_meta_box('categorydiv', __('Page Options'), 'post_categories_meta_box', 'page', 'side', 'core');
}
}
//Adds the custom images box
function custom_post_images() {
global $post;
?>
<div class="inside">
<textarea style="height:70px; width:100%;margin-left:-5px;" name="customHeader" id="customHeader"><?php echo get_post_meta($post->ID, 'customHeader', true); ?></textarea>
<p>Enter your custom html code here for the post page header/image area. Whatever you enter here will override the default post header or image listing <b>for this post only</b>. You can enter image references like so <img src='wp-content/uploads/product1.jpg' />. To show default images, just leave this field empty</p>
</div>
<?php
}
//Adds the custom post title box
function custom_post_title() {
global $post;
?>
<div class="inside">
<p><input style="height:25px;width:100%;margin-left:-10px;" type="text" name="customTitle" id="customTitle" value="<?php echo get_post_meta($post->ID, 'customTitle', true); ?>"></p>
<p>Enter your custom post/page title here and it will be used for the html <title> for this post page and the Google link text used for this page.</p>
</div>
<?php
}
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
// called after a post or page is saved and not on autosave
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['customHeader'])
{
update_custom_meta($postID, $_POST['customHeader'], 'customHeader');
}
else
{
update_custom_meta($postID, '', 'customHeader');
}
if ($_POST['customTitle'])
{
update_custom_meta($postID, $_POST['customTitle'], 'customTitle');
}
else
{
update_custom_meta($postID, '', 'customTitle');
}
}
}
function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
}else{
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}
?>
Wordpress's auto save system may well be your problem, as I think custom fields are not passed along for auto saves (so your customHeader and customTitle post variables will be empty during an auto save).
In your save function you should check if the DOING_AUTOSAVE constant is set (this seems to be preferable to checking the post action) and return if so. Something like this:
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
See this ticket for more info: http://core.trac.wordpress.org/ticket/10744
The WordPress Codex has got an function reference for add_meta_box(), with a great example.
And yes, it uses
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
and I think you've implemented it the right way.
FYI, the solution posted here http://wordpress.org/support/topic/custom-post-type-information-disappearing worked for me and I think is much more elegant.

Categories