I've successfully been able to create one custom metabox for WordPress post types using the following code:
function bandcamp_metabox(){
$posttypes = Array(
'discos',
'Projetos'
);
add_meta_box('bandcamp_link', 'bandcamp link', 'bandcamp_link_meta_callback', $posttypes, 'side');
}
function bandcamp_link_meta_callback( $post ) {
wp_nonce_field('save_bandcamp_link', 'bancamp_meta_box_nonce');
$value = get_post_meta($post->ID,'_bandcamp_link_value_key', true);
echo '<label for="bancamp_link_field">';
echo '<input type="url" id="bancamp_link_field" name="bancamp_link_field" value="' . esc_attr ( $value ) . '" size="25" />';
}
function save_bandcamp_link ( $post_id ) {
if( ! isset( $_POST['bancamp_meta_box_nonce'] ) ){
return;
}
if ( ! wp_verify_nonce( $_POST['bancamp_meta_box_nonce'], 'save_bandcamp_link' ) ){
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ){
return;
}
if( ! isset( $_POST['bancamp_link_field'] ) ) {
return;
}
$bandcamp_link = sanitize_text_field( $_POST['bancamp_link_field'] );
update_post_meta($post_id, '_bandcamp_link_value_key', $bandcamp_link);
}
add_action('add_meta_boxes', 'bandcamp_metabox');
add_action('save_post', 'save_bandcamp_link');
I was hoping (still kind of a noob) that through a 'foreach' function I'd be able to re-use the code to create multiple metaboxes at once like this:
$varsocial = Array(
'bandcamp',
'soundcloud',
'facebook',
'instagram',);
foreach($varsocial as $sociallink) {
function social_metabox(){
$posttypes = Array(
'discos',
'Projetos');
add_meta_box(''. $sociallink .'_link', ''. $sociallink .' link', 'social_link_meta_callback', $posttypes, 'side');
}
function social_link_meta_callback( $post ) {
wp_nonce_field('save_social_link', 'social_meta_box_nonce');
$value = get_post_meta($post->ID,'_'. $sociallink .'_link_value_key', true);
echo '<label for="'. $sociallink .'_link_field">';
echo '<input type="url" id="'. $sociallink .'_link_field" name="'. $sociallink .'_link_field" value="' . esc_attr ( $value ) . '" size="25" />';
}
function save_social_link ( $post_id ) {
if( ! isset( $_POST['social_meta_box_nonce'] ) ){
return;
}
if ( ! wp_verify_nonce( $_POST['social_meta_box_nonce'], 'save_social_link' ) ){
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ){
return;
}
if( ! isset( $_POST[''. $sociallink .'_link_field'] ) ) {
return;
}
$social_link = sanitize_text_field( $_POST[''. $sociallink .'_link_field'] );
update_post_meta($post_id, '_'. $sociallink .'_link_value_key', $social_link);}
return add_action('add_meta_boxes', 'social_metabox');
return add_action('save_post', 'save_social_link');
}
But such is not working. What am I doing wrong?
Related
If I need to add simply text input, I can use a function like woocommerce_wp_text_input inside (for eg.) woocommerce_product_options_advanced. Then I use woocommerce_process_product_meta where I can use update_post_meta. This is clear and handy!
Now - I would like to add a custom field with the PDF upload option as I would like to attach PDF files to the product.
So is it possible to add such a field in a similar way?
Note: This is NOT a virtual download product. It's just simple product.
You can add a custom meta boxes to upload a pdf. You can retrieve it by using <?php get_post_meta( get_the_ID(), 'advanced_options_pdf', true ); ?> on the front end. Just paste the following on your function.php file.
class Advanced_Options {
private $config = '{"title":"Advanced Options","prefix":"advanced_options_","domain":"advanced-options","class_name":"Advanced_Options","post-type":["product"],"context":"normal","priority":"default","fields":[{"type":"media","label":"PDF","return":"url","id":"advanced_options_pdf"}]}';
public function __construct() {
$this->config = json_decode( $this->config, true );
add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'admin_head', [ $this, 'admin_head' ] );
add_action( 'save_post', [ $this, 'save_post' ] );
}
public function add_meta_boxes() {
foreach ( $this->config['post-type'] as $screen ) {
add_meta_box(
sanitize_title( $this->config['title'] ),
$this->config['title'],
[ $this, 'add_meta_box_callback' ],
$screen,
$this->config['context'],
$this->config['priority']
);
}
}
public function admin_enqueue_scripts() {
global $typenow;
if ( in_array( $typenow, $this->config['post-type'] ) ) {
wp_enqueue_media();
}
}
public function admin_head() {
global $typenow;
if ( in_array( $typenow, $this->config['post-type'] ) ) {
?><script>
jQuery.noConflict();
(function($) {
$(function() {
$('body').on('click', '.rwp-media-toggle', function(e) {
e.preventDefault();
let button = $(this);
let rwpMediaUploader = null;
rwpMediaUploader = wp.media({
title: button.data('modal-title'),
button: {
text: button.data('modal-button')
},
multiple: true
}).on('select', function() {
let attachment = rwpMediaUploader.state().get('selection').first().toJSON();
button.prev().val(attachment[button.data('return')]);
}).open();
});
});
})(jQuery);
</script><?php
}
}
public function save_post( $post_id ) {
foreach ( $this->config['fields'] as $field ) {
switch ( $field['type'] ) {
default:
if ( isset( $_POST[ $field['id'] ] ) ) {
$sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
update_post_meta( $post_id, $field['id'], $sanitized );
}
}
}
}
public function add_meta_box_callback() {
$this->fields_table();
}
private function fields_table() {
?><table class="form-table" role="presentation">
<tbody><?php
foreach ( $this->config['fields'] as $field ) {
?><tr>
<th scope="row"><?php $this->label( $field ); ?></th>
<td><?php $this->field( $field ); ?></td>
</tr><?php
}
?></tbody>
</table><?php
}
private function label( $field ) {
switch ( $field['type'] ) {
case 'media':
printf(
'<label class="" for="%s_button">%s</label>',
$field['id'], $field['label']
);
break;
default:
printf(
'<label class="" for="%s">%s</label>',
$field['id'], $field['label']
);
}
}
private function field( $field ) {
switch ( $field['type'] ) {
case 'media':
$this->input( $field );
$this->media_button( $field );
break;
default:
$this->input( $field );
}
}
private function input( $field ) {
if ( $field['type'] === 'media' ) {
$field['type'] = 'text';
}
printf(
'<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
isset( $field['class'] ) ? $field['class'] : '',
$field['id'], $field['id'],
isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
$field['type'],
$this->value( $field )
);
}
private function media_button( $field ) {
printf(
' <button class="button rwp-media-toggle" data-modal-button="%s" data-modal-title="%s" data-return="%s" id="%s_button" name="%s_button" type="button">%s</button>',
isset( $field['modal-button'] ) ? $field['modal-button'] : __( 'Select this file', 'advanced-options' ),
isset( $field['modal-title'] ) ? $field['modal-title'] : __( 'Choose a file', 'advanced-options' ),
$field['return'],
$field['id'], $field['id'],
isset( $field['button-text'] ) ? $field['button-text'] : __( 'Upload', 'advanced-options' )
);
}
private function value( $field ) {
global $post;
if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
$value = get_post_meta( $post->ID, $field['id'], true );
} else if ( isset( $field['default'] ) ) {
$value = $field['default'];
} else {
return '';
}
return str_replace( '\u0027', "'", $value );
}
}
new Advanced_Options;
I am using the visual composer for the WordPress posts and pages actually for over all. But I want to make some custom meta boxes under the screen of the post editor. Actually already I have made the fields. But now I want to make those fields available in the visual composer. Actually I want to add those fields in the visual editor. How can I do that? Please help me with your valuable knowledge.
Here is my code of the meta boxes
<?php
function myplugin_add_meta_box() {
$screens = array( 'post', 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
function myplugin_meta_box_callback( $post ) {
wp_nonce_field( 'myplugin_save_meta_box_data', 'myplugin_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
}
function myplugin_save_meta_box_data( $post_id ) {
if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_save_meta_box_data' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
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;
}
}
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['myplugin_new_field'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );
I see that you are echoing your fields as inputs. You need to use the wp_editor() function instead. It will take care of the wysiwyg (visual editor) field creation for you.
I m creating a wp plugin which supports custom post type. In that i have created a custom meta box..when i enter the metabox values it will not save into the admin dashboard as well as database. Can any one help me out this.
Thanks..
//enter code here
function astestimonial_meta_box($post_id)
{
wp_nonce_field('astest_meta_box','astest_meta_box_nonce');
$clientname = get_post_meta($post->ID,'_clientname_value','true');
echo'<label for="client_name_val">';
_e('Name: ', 'astestimonial_textdomain');
echo'</label>';
echo'<input type="text" id="client_name_val" name="client_name_val" value="'.esc_attr($clientname).'" />';
}
//Save meta data code
function astest_save_client_info($post_id)
{
if(!isset($_POST['astest_meta_box_nonce']))
{
return;
}
if(!wp_verify_nonce($POST['astest_meta_box_nonce'],'astest_meta_box'))
{
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
{
return;
}
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] )
{
if ( ! current_user_can( 'edit_post', $post_id ) )
{
return;
}
}
else
{
if ( ! current_user_can( 'edit_page', $post_id ) )
{
return;
}
}
if( !isset( $_POST['client_name_val']) && !isset($_POST['client_email_val']) && !isset($_POST['client_comp_val']) && !isset($_POST['client_desig_val']))
{
return;
}
$cli_name_data = sanitize_text_field( $_POST['client_name_val'] );
update_post_meta($post_id, '_clientname_value', $cli_name_data);
}
add_action( 'save_post', 'astest_save_client_info' );
I got a WordPress Rating plugin from "http://www.smashingmagazine.com/2012/05/08/adding-custom-fields-in-wordpress-comment-form/"
I would like to count the total number of rating and print that number under the Blog Post. Is this possible?
I added some customisation in this code.
<?php
// Add fields after default fields above the comment box, always visible
add_action( 'comment_form_logged_in_after', 'additional_fields' );
add_action( 'comment_form_after_fields', 'additional_fields' );
function additional_fields () {
echo '<p class="comment-form-rating">'.
'<label for="rating">'. __('Rating') . '<span class="required">*</span></label>
<span class="commentratingbox">';
for( $i=1; $i <= 5; $i++ )
echo '<span class="commentrating"><input type="radio" checked name="rating" id="rating" value="'. $i .'"/>'. $i .' Star</span>';
echo'</span></p>';
}
// Save the comment meta data along with comment
add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') )
$rating = wp_filter_nohtml_kses($_POST['rating']);
add_comment_meta( $comment_id, 'rating', $rating );
}
// Add the filter to check if the comment meta data has been filled or not
add_filter( 'preprocess_comment', 'verify_comment_meta_data' );
function verify_comment_meta_data( $commentdata ) {
if ( ! isset( $_POST['rating'] ) )
wp_die( __( 'Error: You did not add your rating. Hit the BACK button of your Web browser and resubmit your comment with rating.' ) );
return $commentdata;
}
//Add an edit option in comment edit screen
add_action( 'add_meta_boxes_comment', 'extend_comment_add_meta_box' );
function extend_comment_add_meta_box() {
add_meta_box( 'title', __( 'Comment Metadata - Extend Comment' ), 'extend_comment_meta_box', 'comment', 'normal', 'high' );
}
function extend_comment_meta_box ( $comment ) {
$phone = get_comment_meta( $comment->comment_ID, 'phone', true );
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
wp_nonce_field( 'extend_comment_update', 'extend_comment_update', false );
?>
<p>
<label for="rating"><?php _e( 'Rating: ' ); ?></label>
<span class="commentratingbox">
<?php for( $i=1; $i <= 5; $i++ ) {
echo '<span class="commentrating"><input type="radio" name="rating" id="rating" value="'. $i .'"';
if ( $rating == $i ) echo ' checked="checked"';
echo ' />'. $i .' </span>';
}
?>
</span>
</p>
<?php
}
// Update comment meta data from comment edit screen
add_action( 'edit_comment', 'extend_comment_edit_metafields' );
function extend_comment_edit_metafields( $comment_id ) {
if( ! isset( $_POST['extend_comment_update'] ) || ! wp_verify_nonce( $_POST['extend_comment_update'], 'extend_comment_update' ) ) return;
if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != '') ) :
$phone = wp_filter_nohtml_kses($_POST['phone']);
update_comment_meta( $comment_id, 'phone', $phone );
else :
delete_comment_meta( $comment_id, 'phone');
endif;
if ( ( isset( $_POST['title'] ) ) && ( $_POST['title'] != '') ):
$title = wp_filter_nohtml_kses($_POST['title']);
update_comment_meta( $comment_id, 'title', $title );
else :
delete_comment_meta( $comment_id, 'title');
endif;
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') ):
$rating = wp_filter_nohtml_kses($_POST['rating']);
update_comment_meta( $comment_id, 'rating', $rating );
else :
delete_comment_meta( $comment_id, 'rating');
endif;
}
// Add the comment meta (saved earlier) to the comment text
// You can also output the comment meta values directly in comments template
add_filter( 'comment_text', 'modify_comment');
function modify_comment( $text ){
$plugin_url_path = WP_PLUGIN_URL;
if( $commenttitle = get_comment_meta( get_comment_ID(), 'title', true ) ) {
$commenttitle = '<strong>' . esc_attr( $commenttitle ) . '</strong><br/>';
$text = $commenttitle . $text;
}
if( $commentrating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
$commentrating = '<p class="comment-rating"> <img src="'. $plugin_url_path .
'/ExtendComment/images/'. $commentrating . 'star.gif"/><br/>Rating: <strong>'. $commentrating .' / 5</strong></p>';
$text = $text . $commentrating;
return $text;
} else {
return $text;
}
}
It would go something like this. Appending the total for all ratings:
if( !is_admin() )
add_filter( 'the_content', 'content_so_23778986' );
function content_so_23778986( $content )
{
if( !is_single() )
return $content;
# Get all comments from current post
$comms = get_comments( array( 'post_id'=>get_the_ID() ) );
$counter = null;
if( $comms )
{
$total = count( $comms );
# Iterate all comments and add its rating to the counter
foreach( $comms as $c )
{
$rating = (int) get_comment_meta( $c->comment_ID, 'rating', true );
$counter += $rating;
}
# Calculate and print the totals
$counter = '<br />' . $counter / $total . ' de 5';
}
return $content . $counter;
}
Found a function which add to my admin panel one meta-box. It's looks nice, but not enough.
I need at least ten custom fields. How to create them?
The questoins looks stupid, because my knowledge of php are minimal, so do not judge strictly ;). I will be grateful for the solution of this problem or an explanation of how it should work.
function myplugin_add_meta_box() {
$screens = array( 'post', 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function myplugin_meta_box_callback( $post ) {
wp_nonce_field( 'myplugin_meta_box', 'myplugin_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function myplugin_save_meta_box_data( $post_id ) {
if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_meta_box' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
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;
}
}
if ( ! isset( $_POST['myplugin_new_field'] ) ) {
return;
}
$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );
update_post_meta( $post_id, '_my_meta_value_key', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );
If your knowledge of PHP is quite low, there are some great plugins that allow you to do this easily.
If you have a lot of fields to add, I usually find it easier to use the following plugin as ordering fields and pulling them out in themes is a lot easier than doing it manually.
http://wordpress.org/plugins/advanced-custom-fields/