As the title explains, I am trying to add infinite custom fields for two things:
1.Name
2.Bio
Now i tried adding 1000 custom fields and upon update it showed me just 471, There's no way it exceeds and i tried this on my local environment as well as the online but same results
// Adding the metaboxes
add_action( 'add_meta_boxes', 'add_employee_meta' );
/* Saving the data */
add_action( 'save_post', 'employee_meta_save' );
/* Adding the main meta box container to the post editor screen */
function add_employee_meta() {
add_meta_box(
'employee-details',
'Employee Details',
'employee_details_init',
'post');
}
/*Printing the box content */
function employee_details_init() {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'employee_nonce' );
?>
<div id="employee_meta_item">
<?php
//Obtaining the linked employeedetails meta values
$employeeDetails = get_post_meta($post->ID,'employeeDetails',true);
$c = 0;
if ( count( $employeeDetails ) > 0 && is_array($employeeDetails)) {
foreach( $employeeDetails as $employeeDetail ) {
if ( isset( $employeeDetail['name'] ) || isset( $employeeDetail['bio'] ) ) {
printf( '<p>Name<input type="text" name="employeeDetails[%1$s][name]" value="%2$s" /> Package : <textarea name="employeeDetails[%1$s][bio]" rows="4" cols="50" >%3$s</textarea>%4$s</p>', $c, $employeeDetail['name'], $employeeDetail['bio'], 'Remove' );
$c = $c +1;
}
}
}
?>
<span id="output-package"></span>
<?php _e('Add Employee Details'); ?>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
$(".add_package").click(function() {
count = count + 1;
$('#output-package').append('<p> Name <input type="text" name="employeeDetails['+count+'][name]" value="" /> bio : <textarea name="employeeDetails['+count+'][bio]" rows="4" cols="50" ></textarea><?php echo "Remove"; ?></p>' );
return false;
});
$(document.body).on('click','.remove-package',function() {
$(this).parent().remove();
});
});
</script>
</div><?php
}
/* Save function for the entered data */
function employee_meta_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// Verifying the nonce
if ( !isset( $_POST['employee_nonce'] ) )
return;
if ( !wp_verify_nonce( $_POST['employee_nonce'], plugin_basename( __FILE__ ) ) )
return;
// Updating the employeeDetails meta data
$employeeDetails = $_POST['employeeDetails'];
update_post_meta($post_id,'employeeDetails',$employeeDetails);
}
Have anyone tried adding a lot of custom fields and was there such limit as of what i am facing right now ?
Is there any way we can actually use any number of custom fields without this sort of restriction that i am having right now ?
You can hard code it without a plugin by adding this to you functions.
add_filter( 'postmeta_form_limit' , 'customfield_limit_increase' );
function customfield_limit_increase( $limit ) {
$limit = 1000;
return $limit;
}
I would think you could possibly end up with a performance issue going overboard with this.
Also you could run into a php limitation even with the ACF plugin mentioned above. (in PHP 5.3.9) If that is the case you can add this to your .htaccess file...
php_value max_input_vars 3000
Related
HI first of thanks and i love this community . I stuck in problem where i want to store the image/item ID in localhost wordpress database instead of image path. I tried everything but failed. Well i am newbie in wordpress so i need a help.
suppose my image/item id is like:---- http://localhost/wpmegameta/wp-admin/upload.php?item=45
databse path:----http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
and i want to store only 45 in database
Wordpress database Screenshot
and I want to store only 45 in database like this ---
wp_nonce_field( 'case_study_bg_submit', 'case_study_bg_nonce' );
$lacuna2_stored_meta = get_post_meta( $post->ID ); ?>
<p>
<label for="case-study-bg" class="lacuna2-row-title">Practice Area Icon Image</label>
<img style="max-width:200px;height:auto;" id="meta-image-preview" src="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
<input type="text" name="meta-image" id="meta-image" class="meta_image" value="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
<input type="button" id="meta-image-button" class="button" value="Choose or Upload an Image" />
</p>
<script>
jQuery('#meta-image-button').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
jQuery('#meta-image').val(attachment.url);
jQuery('#meta-image-preview').attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open();
return false;
});
</script>
<?php
}
/**
* Add Case Study background image metabox to the back end of Case Study posts
*/
function lacuna2_add_meta_boxes() {
add_meta_box( 'case-study-bg', 'Game Image', 'lacuna2_case_study_bg', 'post', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'lacuna2_add_meta_boxes' );
/**
* Save background image metabox for Case Study posts
*/
function save_case_study_bg_meta_box($post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'case_study_bg_nonce' ] ) && wp_verify_nonce( $_POST[ 'case_study_bg_nonce' ], 'case_study_bg_submit' ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-image' ] ) ) {
update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
}
}
add_action( 'save_post', 'save_case_study_bg_meta_box' );
In wordpress
Image /Item ID==45
Image Path== http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
i want to store the image/item ID in wordpress database like=45
i think it's stander to store the image URL ,
but if you want to store just the id do that is to create a table contain all images URL's
and contains tow columns : ID,URL
hope this useful .
I am trying to add a meta box, following a tutorial. I have triple checked the code that it matches that of the tutorial (in which case, the meta box data IS saving), but on mine, it is not saving. This is my code.
<?php
/*
Plugin Name: Custom Post Meta Box
Plugin URI: http://acetronaut.com
Description: Demonstrates how to implement a custom posts meta box into
wordpress
Version: 1.0.0
Author: Acetronaut
Author URI: http://acetronaut.com
License: GPL2
*/
function acetrnt_add_admin_styles() {
wp_enqueue_style( 'acetrnt-admin', plugins_url( 'custom-post-meta-box/css/admin.css' ) );
}
add_action( 'admin_enqueue_scripts', 'acetrnt_add_admin_styles' );
function acetrnt_add_meta_box() {
add_meta_box(
'acetrnt_audio', // The ID for the meta box
'Add MP3', //The title of the meta box
'acetrnt_display_meta_box', //The function for rendering the markup
'post', // We'll only be displaying this on post pages
'side', //Where the meta box should appear
'core' // The priority of where the meta box whould be displayed
);
}
add_action( 'add_meta_boxes', 'acetrnt_add_meta_box' );
function acetrnt_display_meta_box( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'acetrnt_nonce_field' ); ?>
<label id="mp3-title" for="mp3-title">Title of MP3</label>
<input type="text" id="mp3-title" name="mp3-title" value="<?php echo esc_attr( get_post_meta( $post->ID, true ) ); ?>" placeholder="Your Song By Elton John" />
<label id="mp3-file" for="mp3-file">MP3 File</label>
<input type="file" id="mp3-file" name="mp3-file" value="" />
<?php
}
function acetrnt_save_meta_box_data( $post_id ) {
if ( acetrnt_user_can_save( $post_id, 'acetrnt-nonce-field' ) ) {
if ( isset( $_POST['mp3-title'] ) && 0 < count( strlen( trim( $_POST['mp3-title'] ) ) ) ) {
$mp3_title = $_POST['mp3-title'];
update_post_meta( $post_id, 'mp3-title', $mp3_title );
}
}
}
add_action( 'save_post', 'acetrnt_save_meta_box_data' );
function acetrnt_user_can_save( $post_id, $nonce ) {
// Is this an autosave?
$is_autosave = wp_is_post_autosave( $post_id );
// Is this a revision?
$is_revision = wp_is_post_revision( $post_id );
// Is the nonce valid?
$is_valid_nonce = ( isset( $_POST[ $nonce] ) && wp_verify_nonce( $_POST[ $nonce ], plugin_basename( __FILE__ ) ) );
// Return true if the user is able to save the file
return ! ( $is_autosave || $is_revision ) && $is_valid_nonce;
}
?>
I am banging my head against the wall as to the culprit. Is there anything in my code that is wrong? I have also tried dropping out of php and using regular html code, but that does not work.
I am trying to make a ajax function to make users pay half the price of total amount, on custom cash on delivery method. When user selects yes or no radio button total amount is changed accordingly.
This: Link is a great example what I am trying to follow but I need to make it as a ajax call.
Here's how I added new fields before payment block:
add_action("woocommerce_review_order_before_payment", "new_buttons");
function new_buttons(){
echo '<div id="cash-on-delivery-wrap" class="cash-on-delivery-wrap">';
echo '<h5>Cash on delivery: </h5><div style="clear:both"></div>';
echo '<h6>Pay half 50%</h6><div style="clear:both"></div>';
echo '<div class="cod_button_wrap">';
echo '<label><input type=radio value="no" name="new-cod" checked/>No</label>';
echo '<label><input type=radio value="yes" name="new-cod" />Yes</label>';
echo '</div>';
echo '</div>';
}
Here is the JS:
jQuery(document).ready(function(){
jQuery("form.checkout").on("change", "#cash-on-delivery-wrap input",
function(){
var data = {
action: 'change_cod',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery( 'form.checkout' ).serialize()
};
jQuery.post( ajaxurl, data, function( response )
{
jQuery( 'body' ).trigger( 'update_checkout' );
});
});
});
Here is the function:
function custom_cart_total() {
$current_state = $_POST['post_data'];
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if($current_state=='yes'){
WC()->cart->total *= 0.50;
}else{
WC()->cart->total;
}
exit;
}
add_action( 'wp_ajax_nopriv_change_cod', 'custom_cart_total' );
add_action( 'wp_ajax_change_cod', 'custom_cart_total' );
Cant seem to make it work, what am I missing here.
Note: The code in the linked answer, is only changing the displayed total amount in cart and checkout, but doesn't change it for real.
This answer is also changing the displayed checkout total amount. We need another function hooked in the order creation process, to update the total amount.
For Wordpress Ajax you need to register your script in an external JS file that you will upload in your active theme folder inside a js subfolder. Let say that this external file name will be pay_half.js.
1) Here is the function that will do that registration and will enable WordPress Ajax functionality:
add_action( 'wp_enqueue_scripts', 'ajax_change_shipping' );
function ajax_change_shipping() {
// Only on front-end and checkout page
if( is_admin() || ! is_checkout() ) return;
// Get the Path to the active theme or child theme or plugin folder
# $path = plugin_dir_url( __FILE__ ); // A plugin
# $path = get_template_directory_uri(); // A Normal theme
$path = get_stylesheet_directory_uri(); // A child theme
// Define the subfolder name
$subfolder = 'js';
// Define the file name
$filename = 'pay_half.js';
// Reference name of the script (should be unique)
$handle = 'pay-half';
// Set the ajaxurl parameter used in your script
$data = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
// The variable name whichwill contain the data
$name = 'pay_half';
// Registering the javascript file and enqueues it.
wp_enqueue_script( $handle, $path."/$subfolder/$filename", array( 'jquery' ), '1.0', true );
// Localizing the registered script (Here using Ajax)
wp_localize_script( $handle, $name, $data );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
2) Now the Javascript/jQuery external file (named: pay_half.js):
jQuery(document).ready(function ($) {
var selectHalf = '#cash-on-delivery-wrap input[type="radio"]',
paymentMethod = 'input[name^="payment_method"]',
codWrap = $('.cash-on-delivery-wrap'),
cartGTotal = $('input#cart_gtotal').val(),
codPartial;
// Detecting payment method on load to show/hide cod custom options
if( $(paymentMethod+':checked').val() == 'cod' )
codWrap.show("fast");
else
codWrap.hide("fast");
// Live detecting choosen payment method to show/hide cod custom options
$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
if ( $(paymentMethod+':checked').val() == 'cod' ) {
codWrap.show("fast");
} else {
codWrap.hide("fast");
$('#cash-on-delivery-wrap input#cod-options_no').prop('checked', true);
}
$(document.body).trigger("update_checkout");
// console.log($(paymentMethod+':checked').val());
});
// The "Cod" custom options (ajax)
$(selectHalf).click(function(){
if($(selectHalf+':checked' ).val() == 'yes' ) codPartial = 'yes';
else codPartial = 'no';
$.ajax({ // This does the ajax request
url: pay_half.ajaxurl,
type : 'post',
data: {
'action':'cod_partial_payment', // Name of the php function
'cod_partial' : codPartial // Passing this variable to the PHP function
},
success:function(data) {
// Displaying the price (Ajax)
$( 'table.shop_table > tfoot > tr.order-total > td > strong > span' ).html(data.price_html);
if(codPartial == 'yes')
$('input#cart_remaining').val(data.price_remaining);
else
$('input#cart_remaining').val(0);
$(document.body).trigger("wc_fragment_refresh");
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
3) The Display of your custom fields (revisisted).
I have added 2 hidden fields with the total amount and the remaining amount to pay.
add_action( 'woocommerce_review_order_before_payment', 'cod_payment_options', 10 );
function cod_payment_options(){
echo '<style>.cod-button-options label{display:inline-block; margin:0 6px;}</style>
<div id="cash-on-delivery-wrap" class="cash-on-delivery-wrap">
<h3>' . __( 'Cash on delivery option' ) . '</h3>';
woocommerce_form_field( 'cod-options', array(
'type' => 'radio',
'class' => array('form-row-wide', 'cod-button-options'),
'label' => __( '<b>Pay half (50%): </b>' ),
'required' => false,
'options' => array(
'no' => __( 'No' ),
'yes' => __( 'Yes' ),
)
), 'no' );
// Some additional hidden fields
echo '<input type="hidden" id="cart_gtotal" name="cart_gtotal" value="'. WC()->cart->total .'">
<input type="hidden" id="cart_remaining" name="cart_remaining" value="0" />
</div>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
4) The driven php function (Wordpress Ajax):
add_action( 'wp_ajax_nopriv_cod_partial_payment', 'cod_partial_payment' );
add_action( 'wp_ajax_cod_partial_payment', 'cod_partial_payment' );
function cod_partial_payment() {
if( ! isset($_POST['cod_partial']) ) return;
$current_state = $_POST['cod_partial'];
$remaining = 0;
if( $current_state == 'yes' ){
WC()->cart->total /= 2;
}
WC()->session->set( 'total', WC()->cart->total );
$response = array(
'price_html' => wc_price( WC()->cart->total ),
'price_remaining' => WC()->cart->total,
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
die(); // Always (to avoid an error 500)
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
5) All Other php functions (Update order amount, save metadata, display a message):
// Replacing the total amount when COD option is enabled
add_action( 'woocommerce_checkout_create_order', 'cod_options_change_order_total_ammount', 10, 2 );
function cod_options_change_order_total_ammount( $order, $data ) {
if ( ! empty( $_POST['cod-options'] ) && $_POST['cod-options'] == 'yes' ) {
$remaining = sanitize_text_field( $_POST['cart_remaining'] );
$total = WC()->cart->total - floatval($remaining);
WC()->session->set( 'total', $total );
$order->set_total( $total );
}
}
// Updating order meta data for Cod selected option
add_action( 'woocommerce_checkout_update_order_meta', 'cod_options_update_order_meta', 10, 1 );
function cod_options_update_order_meta( $order_id ) {
if ( ! empty( $_POST['cod-options'] ) && $_POST['cod-options'] == 'yes' ) {
update_post_meta( $order_id, '_cod_remaining_amount', sanitize_text_field( $_POST['cart_remaining'] ) );
update_post_meta( $order_id, '_cod_partial_paid_amount', sanitize_text_field( $_POST['cart_gtotal'] - $_POST['cart_remaining'] ) );
}
update_post_meta( $order_id, '_cod_partial_payment_option', sanitize_text_field( $_POST['cod-options'] ) );
}
// Displaying the remaining amount to pay in a custom message on Order received page (thank you)
add_action( 'woocommerce_thankyou_cod', 'cod_options_woocommerce_thankyou', 10, 1 );
function cod_options_woocommerce_thankyou( $order_id ) {
if( get_post_meta( $order_id, '_cod_partial_payment_option', true ) == 'yes' ){
$ra = '<span style="color:#96588a;">'.wc_price( get_post_meta( $order_id, '_cod_remaining_amount', true )).'</span>';
?>
<ul class="woocommerce-order-overview woocommerce-thankyou-cod-options order_details">
<li class="woocommerce-order-overview__remaining_total order">
<strong><?php echo __("There is a remaining amount of $ra to pay on this order."); ?></strong>
</li>
</ul>
<?php
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on Woocommerce 3+ and works.
I've created a Custom Post Type 'media-page-items' that I'm attempting to add meta boxes to. Currently the meta boxes are showing but not saving to the database. I've tried a few different approaches on it and none of them seem to save to database.
Debug is turned on but no errors are being thrown currently that I can see.
Any help is much appreciated!
//add article link to media page item
add_action( 'admin_menu', 'gruman_article_link_create' );
add_action( 'save_post', 'gruman_article_link_save', 10, 2 );
function gruman_article_link_create() {
add_meta_box( 'gruman-article-link', 'Article Link', 'gruman_article_link', 'media-page-items', 'advanced', 'high' );
}
function gruman_article_link( $post ) {
// retrieve the _gruman_article_title current value
$current_article_link = get_post_meta( $post->ID, '_gruman_article_link', true );
?>
<p>
<label>Article Link</label>
<br />
<input name="gruman-article-link" id="article-link" style="width: 97%;"><?php $current_article_link; ?>/>
<input type="hidden" name="gruman_article_link_nonce" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
</p>
<?php }
function gruman_article_link_save( $post_id ) {
// verify taxonomies meta box nonce
if ( !isset( $_POST['gruman_article_link_nonce'] ) || !wp_verify_nonce( $_POST['gruman_article_link_nonce'], basename( __FILE__ ) ) ){
return $post_id;
}
// return if autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
return $post_id;
}
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ){
return $post_id;
}
// store article title value
if ( isset( $_REQUEST['gruman-article-link'] ) ) {
update_post_meta( $post_id, '_gruman_article_link', sanitize_text_field( $_POST['gruman-article-link'] ) );
}
}
In wp_create_nonce you are using plugin_basename( __FILE__ ).
And when you verifying nonce you use basename( __FILE__ ) as action name.
Those values are not the same. First one will return something like my-plugin/my-plugin.php and the second will be my-plugin.php
That is why I believe wp_verify_nonce returns False and your data is not saved.
I'm using a plugin on Woocommerce that adds a new metabox with editable quantity number fields onto the admin back-end.
My theme allows for front-end product posting and so I want to add bring some of these fields to the front-end.
I have managed to add the fields in my template file by using :
<?php
$min = get_post_meta( $post->ID, '_wpbo_minimum', true );
$max = get_post_meta( $post->ID, '_wpbo_maximum', true );
?>
<label for="_wpbo_minimum">Minimum Quantity</label>
<input type="number" name="_wpbo_minimum" value="<?php echo $min; ?>" />
<label for="_wpbo_maximum">Maximum Quantity</label>
<input type="number" name="_wpbo_maximum" value="<?php echo $max; ?>" />
Both fields are showing on my front-end product edit form and getting their values from the backend if these were previously filled in.
But now I am struggling with updating and saving the fields with updated values
from front-end or saving new values from front-end if these values were not previously filled in.
I spent hours finding some tutorial on this, I think I should be concentrating on the following code :
update_post_meta($post->ID, '_wpbo_minimum', $_POST['_wpbo_minimum']);
update_post_meta($post->ID, '_wpbo_maximum', $_POST['_wpbo_maximum']);
But I can't figure out if this is correct and where should this code be placed in order to save or update my fields.
I tried placing a function into my functions.php file that looks like this :
/* Update Minimum Qty field */
add_action('save_post', 'save_min_qty');
function save_min_qty($post_id)
{
if(get_post_type($post_id) != "VA_LISTING_PTYPE")
return;
$min = get_post_meta( $post->ID, '_wpbo_minimum', true );
if ( isset( $_POST['_wpbo_minimum'] )) {
$min = $_POST['_wpbo_minimum'];
}
if( isset( $_POST['_wpbo_minimum'] )) {
if ( $min != 0 ) {
$min = wpbo_validate_number( $min );
}
update_post_meta(
$post_id,
'_wpbo_minimum',
strip_tags( $min )
);
}
But this just doesn't seem to be the winner.
Would you be please able to point me to the right direction ?
Below is the code from the actual original plugin that creates metabox in the back-end, I am not sure if it's any relevant to what I need to do in front-end and what part of this and where should I be using it :
<?php
if ( ! class_exists( 'IPQ_Quantity_Meta_Boxes' ) ) :
class IPQ_Quantity_Meta_Boxes {
public function __construct() {
add_action( 'save_post', array( $this, 'save_quantity_meta_data' ) );
}
/* Handle Saving Meta Box Data */
public function save_quantity_meta_data( $post_id ) {
// Validate Post Type
if ( ! isset( $_POST['post_type'] ) or $_POST['post_type'] !== 'product' ) {
return;
}
// Validate User
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Verify Nonce
if ( ! isset( $_POST["_wpbo_product_rule_nonce"] ) or ! wp_verify_nonce( $_POST["_wpbo_product_rule_nonce"], plugin_basename( __FILE__ ) ) ) {
return;
}
// Update Rule Meta Values
if ( isset( $_POST['_wpbo_minimum'] )) {
$min = $_POST['_wpbo_minimum'];
}
if( isset( $_POST['_wpbo_minimum'] )) {
if ( $min != 0 ) {
$min = wpbo_validate_number( $min );
}
update_post_meta(
$post_id,
'_wpbo_minimum',
strip_tags( $min )
);
}
/* Make sure Max > Min */
if( isset( $_POST['_wpbo_maximum'] )) {
$max = $_POST['_wpbo_maximum'];
if ( isset( $min ) and $max < $min and $max != 0 ) {
$max = $min;
}
update_post_meta(
$post_id,
'_wpbo_maximum',
strip_tags( wpbo_validate_number( $max ) )
);
}
}
}
endif;
Everything is correct except that you are checking for the wrong post_type - it should be "product" not "VA_LISTING_PTYPE". Your function hooked to save_post is returning early because the post type is not correct.
Incorrect
if(get_post_type($post_id) != "VA_LISTING_PTYPE")
return;
Correct
if (get_post_type($post_id) != "product"){
// bail early if we aren't updating a WooCommerce Product
return;
}
You can see the same check in the plugin you are extending here:
https://github.com/wpbackoffice/woocommerce-incremental-product-quantities/blob/master/includes/class-ipq-product-meta-box.php#L222