Wordpress Plugin : Multiple values against same setting - php

I am writing a plugin for category discounts. In Plugin Setting page, I have a Category and Discount_percentage fields. I am rending these as followings
function cat_slug_render( ) {
$options = get_option( 'slug-configuration' );
?>
<input type='text' size="50" name='slug-configuration[cat_slug]' value='<?php echo $options['cat_slug']; ?>'>
<?php
}
and defining the option as
add_settings_field(
'cat_slug', //id
'category Slug', //title
'cat_slug_render', // callable
'slug-configuration', // page
'configuration' // section
);
everything else is fine. I can save the settings, can retrieve it, can update it and all.
However, I can save just ONE value. My aim is to save multiple values using the same fields.
But I am confused here how can I do it. My ultimate goal is as follows
input cat slug
Input discount
Press save
this will insert a New record each time this process is done
any guidance or help is highly appreciated!

You can add to [cat_slug] as an array during save by using [] in the name attribute:
function cat_slug_render( ) {
$options = get_option( 'slug-configuration', array() );
?>
<input type='text' size="50" name='slug-configuration[cat_slug][]' value='<?php echo esc_html( $options['cat_slug'][0] ?? '' ); ?>'>
<?php
}
However, you'll have to decide which value should be pre-loaded into the field if you are going to save multiple values. The first? The last? I've added [0] to the value, which should show the first, but if you want the most recent you could do something like:
function cat_slug_render( ) {
$options = get_option( 'slug-configuration', array() );
$last_key = array_key_last( $options );
?>
<input type='text' size="50" name='slug-configuration[cat_slug][]' value='<?php echo esc_html( $options['cat_slug'][$last_key] ?? '' ); ?>'>
<?php
}
Obviously make sure to update your sanitizer function if you try this, and note that value should be secured using esc_html() as well as your preferred method of isset (I've used ?? from PHP 7 or higher) if you want to prevent errors when nothing has been saved.
To display or use the values you've saved, you can use a foreach loop on the [cat_slug] array key:
$options = get_option( 'slug-configuration', array() )[cat_slug] ?? array();
foreach( $options as $option ) {
// Do stuff.
}

Related

Ninja forms - checkbox checked-value issue. Is it possible to modify? Calculation not working

I don't know if this is the correct place to ask, but I'll try. I have an ongoing project with Wordpress (Genesis framework - Agentpress PRO theme) working with Ninja Forms, and am having a slight problem. The web page is: http://www.supercastor.net/wordpress/listings/castellon-65-m2-ytong/
I have a listings page (for each house model). Each listing has metadata that is accessible via a simple function from the genesis framework:
genesis_get_custom_field( 'CUSTOM_FIELD_NAME' );
I would like to have, like the link above has, a list of checkboxes that the user can select/deselect, and the TOTAL value is finally calculated. Everything is working, except that I cannot assign the value of this "custom field" that is from the listing.
I am using Ninja Forms, and after some research, I have come up with the solution of registering a custom field in NF:
function precio_basico_calc_display( $field_id, $data ){
// Get the default_value
if( isset( $data['default_value'] ) ){
$def_value_new = genesis_get_custom_field( '_listing_precio_sort' );
$data['default_value'] = $def_value_new;
$default_value = $data['default_value'];
debug_to_console("Default_value is set to:$default_value");
}else{
$default_value = '';
debug_to_console("Default_value NOT SET");
}
$products_select = genesis_get_custom_field( '_listing_precio_sort' );
}
// Now that $products_select is populated with the listing_price, output a checkbox with the value of the price. ?>
<input type="checkbox" name="ninja_forms_field_<?php echo $field_id;?>" value="<?php echo $products_select;?>" checked="checked" class="ninja-forms-field ninja-forms-field-calc-listen" disabled="disabled">
<?php
}
I also have a small "debug_to_console" function, but this is just as a quick "debugging". I can see that the value is there, but in the calculation it is not set. I have set the default to 40.000, but it should be set to the value for each price (in the link example, should be 19.000). As:
$products_select = genesis_get_custom_field( '_listing_precio_sort' );
And I have also tried the following (field_id 33 is the checkbox in the form):
add_filter( 'ninja_forms_field', 'my_filter_function', 10, 2 );
function my_filter_function( $data, $field_id ){
if( $field_id == 33 ){
$listing_price = genesis_get_custom_field( '_listing_precio_sort' );
$data['default_value'] = $listing_price;
}
return $data;
}
But it isn't working either. I mean, it does display the value (in the console), but not making the calculation correctly.
Help! I just want the calculation (TOTAL) to update correctly for each listing. I thought changing the default_value would do, but it doesn't. I'm lost :(
Thanks!

Wordpress Theme Development

what i'm currently trying to achieve is some simple theme options. What i want to b able todo is;
Under the Wordpress GUI, Theme options section which i've currently got a few setup (with no actions behind them), is to simply "Click a check box which will disable front page widgets, if it's on then show them if it's off disable them"
I understand the logic behind, but i have no idea on how to create something will will return a simple true of false, from the theme-options.php, link it into the front-page.php and use the result from theme-options to be the condition to show said area.
Any help with this would be amazing.
<?php $options = get_option( 'SV_theme_options' ); ?>
<input id="SV_theme_options[option1]" name="SV_theme_options[option1]" type="checkbox" value="1" <?php checked( '1', $options['option1'] ); ?> />
/**
* Sanitize and validate input. Accepts an array, return a sanitized array.
*/
function theme_options_validate( $input ) {
global $select_options, $radio_options;
// Our checkbox value is either 0 or 1
if ( ! isset( $input['option1'] ) )
$input['option1'] = null;
$input['option1'] = ( $input['option1'] == 1 ? 1 : 0 );
// Say our text option must be safe text with no HTML tags
$input['sometext'] = wp_filter_nohtml_kses( $input['sometext'] );
// Our select option must actually be in our array of select options
if ( ! array_key_exists( $input['selectinput'], $select_options ) )
$input['selectinput'] = null;
// Our radio option must actually be in our array of radio options
if ( ! isset( $input['radioinput'] ) )
$input['radioinput'] = null;
if ( ! array_key_exists( $input['radioinput'], $radio_options ) )
$input['radioinput'] = null;
// Say our textarea option must be safe text with the allowed tags for posts
$input['sometextarea'] = wp_filter_post_kses( $input['sometextarea'] );
return $input;
}
Also in the front-page.php I've required_once for this file, tried calling by doing:
echo theme_options_validate( $input['option1' );
however all i get is the word Array returned.
Regards,
Ben
Maybe that's because you made a typo.
You didn't close the bracket
echo theme_options_validate( $input['option1' );
Should be:
echo theme_options_validate( $input['option1'] );

WordPress: Store data from input fields to database and than retrieve it

I have input fields with names like: child1, child[2], child[3] and so on. A user can add as many fields as he wants, its handled with jquery and dynamically ads an input field with [n] in the end of the name.
Now I need to store this data to database in WordPress plugin I work on. And later retrieve this data to display it on the website, and of cause add those field out fields in admin page, where user edits data.
I know how to store one field for example child to the database in WordPress, it would be something like that:
<?php $child = get_post_meta( $post->ID, 'child', true ); ?>
<?php
function save_child_data( $post_id ) {
// Check if exists
if(! isset($_POST['child'])){return;}
// Sanitize
$child_data = sanitize_text_field( $_POST['child'] );
// Store data
update_post_meta( $post_id, 'child', $child_data);
}
add_action( 'save_post', 'save_child_data' );
?>
<!-- Field in admin -->
<input type="text" name="child" id="child" value="<?php echo esc_attr($child); ?>">
<!-- Front office -->
<div>Child: <?php echo get_post_meta( $post->ID, 'child', true ); ?></div>
So my question is how do I handle this array like child[n]?
Or another question maybe it is better to just use child1, child2, child3 and handle it as regular input fields?
So you understand what I mean by dynamically added block here is a jsfiddle link: http://jsfiddle.net/alexchizhov/LC2K6/
Store it as an JSON or serialized string in one field.
http://ch1.php.net/manual/en/function.json-encode.php
http://ch1.php.net/manual/en/function.serialize.php

Show my custom meta data in woocommerce admin page

I have been working with Wordpress and Woocommerce to add a custom meta field to my admin products page. I have everything working fine except that when I save the product, it does not show the info I entered in my meta box.
I checked the database and the data does indeed save, I saw the data I entered in the value and the meta field name was in the meta key. So that leads me to believe everything is working except showing the value on the admin product page once the product has been saved.
I think that the problem lies within one of these two functions but not certain, it could be in the save function though where it calls the update_post_meta.
here is where I think my problem is:
function variable_fields( $loop, $variation_data ) {
?>
<tr>
<td>
<div>
<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
<input type="text" size="5" name="my_custom_field[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_custom_field'][0]; ?>"/>
</div>
</td>
</tr>
<?php
}
function variable_fields_js() {
?>
<tr>
<td>
<div>
<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
<input type="text" size="5" name="my_custom_field[' + loop + ']" />
</div>
</td>
</tr>
<?php
}
This is the function that saves the data, just incase the problem could be in here?
function variable_fields_process( $post_id ) {
if (isset( $_POST['variable_sku'] ) ) :
$variable_sku = $_POST['variable_sku'];
$variable_post_id = $_POST['variable_post_id'];
$variable_custom_field = $_POST['my_custom_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $variable_custom_field[$i] ) ) {
update_post_meta( $variation_id, '_my_custom_field', stripslashes( $variable_custom_field[$i] ) );
}
endfor;
endif;
}
Looking through the code nothing is sticking out to me. Everything is working except when I save the product, the data entered doesnt show (but it is in the database) so Im thinking it could be a conflict with when it is saved, showing the saved values in the fields.
Thanks for your help
Update:
Specifically I think it is this line that is jamming me up:
value="<?php echo $variation_data['_my_custom_field'][0]; ?>"
I know this is a little late but i managed to solve this and wanted to share it with you.
Basically WooCommerce have dropped $variation_data. You will now need to add $variation to your function and get the id. With the ID you can them get the post_meta / custom field. This can be done like so:
function variable_fields( $loop, $variation_data, $variation ) {
$get_variation_id = $variation->ID;
$data_to_get = get_post_meta($get_variation_id, '_my_custom_field', true );
This line:
value="<?php echo $variation_data['_my_custom_field'][0]; ?>"
Then becomes:
value="<?php echo $data_to_get; ?>"
That's it! i hope this helps you and anyone else that comes across this page.
I would recommend trying the Advanced Custom Fields (ACF) plugin, assuming this is for your site and not code to go into a published plugin.
I also started trying to code custom fields into a site, then realised after several pages of code that goes way beyond the business needs of "just adding a field", that the ACF plugin does the same job in ten clicks and two minutes. Sometimes you just have to be pragmatic, and accept that occasionally the best way of winning the debugging game is not to play the coding game in the first place.
Apologies if that is not the answer you or SO is looking for.

Script conflict with adminimize plugin

Thought about asking on wordpress answers, but they would tell me it's a "plugin thing".. If you disagree then feel free to pass it over to them.
I'm using this code in my functions.php which offers a dropdown menu of available categories when a user clicks the new post button. This forces them to choose a category BEFORE the new blank post is created.
The problem is I'm getting "invalid post type" error and have it traced it back to a plugin called "adminimizer".
The new post never gets created, the address bar gets stuck at mysite.com/wp-admin/post-new.php?category_id%5B%5D=4&continue=Continue&post_type= (it should say "post" after the type=.. and I get an error box saying "invalid post type".
I'd love to hear any thoughts on why my script might not be completing. Here's the code I'm using:
//ADD DROPDOWN MENU TO CHOOSE NEW POST CATEGORY (CHOOSE THE CAT ID’S YOU WANT TO APPEAR)
add_filter( 'load-post-new.php', 'wpse14403_load_post_new' );
function wpse14403_load_post_new()
{
$post_type = 'post';
if ( isset( $_REQUEST['post_type'] ) ) {
$post_type = $_REQUEST['post_type'];
}
// Only do this for posts
if ( 'post' != $post_type ) {
return;
}
if ( array_key_exists( 'category_id', $_REQUEST ) ) {
add_action( 'wp_insert_post', 'wpse14403_wp_insert_post' );
return;
}
// Show intermediate screen
extract( $GLOBALS );
$post_type_object = get_post_type_object( $post_type );
$title = $post_type_object->labels->add_new_item;
include( ABSPATH . 'wp-admin/admin-header.php' );
$dropdown = wp_dropdown_categories( array(
'orderby' => 'name',
'include' => '3, 4',
'name' => 'category_id[]',
'hide_empty' => false,
'echo' => false,
) );
$category_label = __( 'Create New' );
$continue_label = __( 'Continue' );
echo <<<HTML
<div class="wrap">
<h2>{$title}</h2>
<form method="get">
<table class="orange">
<tbody>
<tr valign="top">
<th scope="row">{$category_label}</th>
<td>{$dropdown}</td>
</tr>
<tr>
<td></td>
<th><input name="continue" type="submit" class="button-primary" value=" {$continue_label}" /></th>
</tbody>
</table>
<input type="hidden" name="post_type" value="{$post_type}" />
</form>
</div>
HTML;
include( ABSPATH . 'wp-admin/admin-footer.php' );
exit();
}
// This function will only be called when creating an empty post,
// via `get_default_post_to_edit()`, called in post-new.php
function wpse14403_wp_insert_post( $post_id )
{
wp_set_post_categories( $post_id, $_REQUEST['category_id'] );
}
UPDATE / MORE INFO. On further investigation, I changed a bit of my code towards the end from hidden to text. This reveals an input field that is usually automatically filled with the post type "post". The adminimize plugin appears to prevent this from happening, even though I have not set it to hide anything?
<input type="text" name="post_type" value="{$post_type}" />
I guess the easy solution would be just don't use the adminimizer plugin, but it's very useful to keep things simple for new site owners. I've asked the plugin author about this, but don't expect an answer any time soon - thanks
Well it turns out that the plugin author (Frank) offers great support. He spotted there was a problem with this line & simply commented it out. Now everything works as expected :)
//extract( $GLOBALS );

Categories