Overriding woocommerce shipping calculator in child theme - php

I have overridden the woocommerce shipping calculator and it works. However, when I change countries, the 'State' input field appears when I have set that as a hidden field. If I then change back to my home country, Australia, the State field remains, but becomes a dropdown and is populated with the States of Australia. This field is part of the original theme's shipping-calculator.php, not my child theme one.
I'm not sure how this is happening since my child theme works fine until I change countries. I am trying to include the use of the AddressFinder widget into my cart shipping calculator when the customer is from Australia, and not use it when the customer is from another country.
defined( 'ABSPATH' ) || exit;
do_action( 'woocommerce_before_shipping_calculator' ); ?>
<script>
(function(){
var cartwidget, initAF = function(){
cartwidget = new AddressFinder.Widget(
document.getElementById('address_field'),
'<AddressFinder Key Here>',
'AU',
{
"address_params": {}
}
);
cartwidget.on("result:select", function(fullAddress, metaData) {
var combinedAddressLine1And2;
if ( metaData.address_line_2 ) {
combinedAddressLine1And2 = metaData.address_line_1 + ', ' + metaData.address_line_2
} else {
combinedAddressLine1And2 = metaData.address_line_1
}
if ( document.getElementById("calc_shipping_country").value == "Australia" ) {
document.getElementById('calc_shipping_address_1').value = combinedAddressLine1And2;
document.getElementById('calc_shipping_state').value = metaData.state_territory;
document.getElementById('calc_shipping_postcode').value = metaData.postcode;
} else {
document.getElementById('calc_shipping_address_1').value = '';
document.getElementById('calc_shipping_state').value = '';
document.getElementById('calc_shipping_postcode').value = '';
}
//window.alert(document.getElementById('calc_shipping_address_1').value);
document.getElementById('calc_shipping_city').value = metaData.locality_name;
});
};
function downloadAF(f){
var script = document.createElement('script');
script.src = 'https://api.addressfinder.io/assets/v3/widget.js';
script.async = true;
script.onload=f;
document.body.appendChild(script);
};
document.addEventListener("DOMContentLoaded", function () {
downloadAF(initAF);
});
})();
function country_updated() {
if ( document.getElementById("calc_shipping_country").value == "Australia") {
document.getElementById("address_field").type = 'text';
document.getElementById("calc_shipping_city").type = 'hidden';
} else {
document.getElementById("calc_shipping_city").type = 'text';
document.getElementById("address_field").type = 'hidden';
}
}
</script>
<form class="woocommerce-shipping-calculator" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">
<?php printf( '%s', esc_html( ! empty( $button_text ) ? $button_text : __( 'Calculate shipping', 'woocommerce' ) ) ); ?>
<section class="shipping-calculator-form" style="display:none;">
<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_country', true ) ) : ?>
<p class="form-row form-row-wide" id="calc_shipping_country_field">
<select name="calc_shipping_country" id="calc_shipping_country" class="country_to_state country_select" onchange="country_updated()">
<option value=""><?php esc_html_e( 'Select a country…', 'woocommerce' ); ?></option>
<?php
foreach ( WC()->countries->get_shipping_countries() as $key => $value ) {
echo '<option value="' . esc_attr( $key ) . '"' . selected( WC()->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
}
?>
</select>
</p>
<?php endif; ?>
<p class="form-row form-row-wide" id="shipping_address_field">
<input type="text" placeholder="<?php esc_attr_e( 'Enter Address Here', 'woocommerce' ); ?>" id="address_field" name="address_field" placeholder="Enter address here" class="address-search">
</p>
<p class="form-row form-row-wide" id="calc_shipping_address_field_1">
<input type="hidden" name="calc_shipping_address_1" id="calc_shipping_address_1" />
</p>
<p class="form-row form-row-wide" id="calc_shipping_city_field">
<input type="hidden" name="calc_shipping_city" id="calc_shipping_city" />
</p>
<p class="form-row form-row-wide" id="calc_shipping_state_field">
<input type="hidden" name="calc_shipping_state" id="calc_shipping_state" />
</p>
<p class="form-row form-row-wide" id="calc_shipping_postcode_field">
<input type="hidden" name="calc_shipping_postcode" id="calc_shipping_postcode" />
</p>
<p><button type="submit" name="calc_shipping" value="1" class="button"><?php esc_html_e( 'Update', 'woocommerce' ); ?></button></p>
<?php wp_nonce_field( 'woocommerce-shipping-calculator', 'woocommerce-shipping-calculator-nonce' ); ?>
</section>
</form>
<?php do_action( 'woocommerce_after_shipping_calculator' ); ?>
When the customer is from Australia - it should display the country select input and an address input box - which has the AddressFinder widget on it. When the customer is from another country, it should display the country select and the city input field. Instead, when another country is selected, the state field shows as well. And when changing back to Australia, the State field remains.

I figured out the issue. In the 'Country' select, I had left it's class as: class="country_to_state country_select" - so this was obviously populating and calling the State input field. I also realised my javascript should have been checking the country select value for "AU" not "Australia".

Related

Change postcode field in Cart page ( Shipping Calculator ) to a dropdown

I would like to make a dropdown field when somebody tries to type post code in the shipping calculator, at cart page, so he can choose the field, rather than type it.
I have managed to make it at the checkout field, looking at how other people did it at StackOverflow.
This is the code I have put in function.php and it works at checkout:
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_postcode_field' );
function custom_override_default_postcode_field( $address_fields ) {
// Your postcodes array
$postcode_array = array(
'70101' => "70101",
'70202' => "70202",
'70220' => "70220",
'70223' => "70223",
'89245' => "89245",
'89247' => "89247"
);
$address_fields['postcode']['type'] = 'select';
$address_fields['postcode']['options'] = $postcode_array;
return $address_fields;
}
Then I have put shipping-calculator.php in my theme woocommerce cart php file and I can not figure out how to make a dropdown field at Cart.
This is the code for typing in postcode from woocommerce an shipping-calculator.php:
<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_postcode', true ) ) : ?>
<p class="form-row form-row-wide" id="calc_shipping_postcode_field">
<input type="text" class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_postcode() ); ?>" placeholder="<?php esc_attr_e( 'Postcode / ZIP', 'woocommerce' ); ?>" name="calc_shipping_postcode" id="calc_shipping_postcode" />
</p>
<?php endif; ?>
How do I make it to be a dropdown, please?
<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_postcode', true ) ) : ?>
<p class="form-row form-row-wide" id="calc_shipping_postcode_field">
<select name="calc_shipping_postcode" id="calc_shipping_postcode">
<option value=""><?php _e( 'PostCode;', 'woocommerce' ); ?></option>
<?php
$postcode_array = array(
'70101' => "70101",
'70202' => "70202",
'70220' => "70220",
'70223' => "70223",
'89245' => "89245",
'89247' => "89247"
);
foreach ( $postcode_array as $key => $value ) {
?>
<option value="<?php echo $key; ?>" <?php selected( esc_attr( WC()->customer->get_shipping_postcode() ), $key, 1 ) ?>><?php echo $value; ?></option>
<?php
}
?>
</select>
</p>
<?php endif; ?>
Modify this section in template override

How to get Wordpress frontent widget get/post example working on the front end and back end?

I was unable to get my wordpress widget to post forms correctly. I took the advice on this website and researched the issue (see relevant links at the bottom of the post) to see what the problem was. The first issue was that I could not use "name" for a field. I needed to make sure that the posted name was unique. If not, Wordpress would bring me to a "Site Not Found" which was really cryptic.
The key to figuring this out was to start with this example:
https://www.w3schools.com/php/php_forms.asp
I literally copied and pasted that example into the widget function, of course taking out the html head and tail business. It did not work because it was posting to "name" which already existed. Also, the file reference for Wordpress did not start in the plugin directory, but rather the wordpress directory; so it ended up looking in the wrong place for the action.php file that is run after the submit is made. Look carefully at the URL address bar when the post is made to see if the action is actually getting to the right place. Finally, I adjusted the address, and everything worked like in the example; however, it left the main Wordpress page. So I was stuck.
I put back "" as the action page. I tried the GET method; that did not work for me (and I am still not sure why, but I should adjust it and check it out because GET is preferable for this application; it allows bookmarks); it ended up (thank G-d) that the "post" method worked. (Just now, I changed all occurrences of "post" to "get" and all instances of "POST" to "GET" and it is working as expected. I was having a problem with GET where the URL was being formed correctly and then I could not access it. That problem was I was nesting PHP. I removed all the nested PHP. Along the route, I updated the initial slider value which was not set correctly.
And finally it works!
Starting Code:
public function widget( $args, $instance ) {
/* include "thiswidget.php"; */ /*disable for now*/
/* Include the widget($args, $instance) function body */
/* include "businesspartnerships.php"; */ /*Original works fine with id update */
static $recommended_ex_no = 3;
static $example_run = 4;
$example_max = 4;
$example_min = 0;
$this_widg_id = $this->id; /* Get the widget ID to be the unique ID Key */
$default_slider_value = 3; /*Default slider value if nothing new has been posted */
if ($example_run > 0) { /*Provide a slider to select examples */
/*See http://foundation.zurb.com/sites/docs/v/5.5.3/components/range_slider.html */
/*See http://www.html5tutorial.info/html5-range.php */
/*See https://www.w3schools.com/php/php_forms.asp */
?><p> Recommended View Example Number: <?php echo $recommended_ex_no ?></p>
<!-- See: http://stackoverflow.com/questions/11788005/how-to-get-fetch-html5-range-sliders-value-in-php -->
<form action="" method="post">
<input type="range" min="<?php echo $example_min;?>" max="<?php echo $example_max;?>" step="1" value="<?php echo $set_slider_value ?>" id="<?php echo $this_widg_id; ?>" name="<?php echo $this_widg_id; ?>" onchange='document.getElementById("text_<?php echo $this_widg_id; ?>").value = "Slider Value = " + document.getElementById("<?php echo $this_widg_id; ?>").value;'/>
<br><center><input type="text" style="text-align: center" name="text_<?php echo $this_widg_id; ?>" id="text_<?php echo $this_widg_id; ?>" value="Slider Value = <?php echo $set_slider_value ?>" disabled /></center>
<br />
<center><input style="text-align: center" type="submit" value="Submit" /></center>
</form>
<?php
$this_widg_id = esc_attr( $this->id) ; /* Get the widget ID to be the unique ID Key */
echo "The key is : "; echo esc_attr( $this->id); echo "<br><br>";
if(isset($_POST[esc_attr( $this->id)])){
echo '<br> isset below get <br>';
echo "<center>The example selected is: ".$_POST[esc_attr( $this->id)]." </center>";
// Your Slider value is here, do what you want with it. Mail/Print anything..
$example_run = $_POST[esc_attr( $this->id)];
$set_slider_value = $_POST[esc_attr( $this->id)]; /*If the value has been posted, then show it.*/
} else {
/* $set_slider_value = $default_slider_value; */ /* Slider value is initially set to default. */
}
}
/* Try https://www.w3schools.com/php/php_forms.asp example here, since form update was not working before */
?>
<!-- <form action="wp-content/plugins/carousel_edit_url_for_newspro/welcome_get.php" method="post"> -->
<form action="" method="post">
Name: <input type="text" name="thisexname"><br>
<!-- E-mail: <input type="text" name="email"><br> -->
<input type="submit">
</form>
<?php
if (isset($_POST[esc_attr("thisexname")])){
echo 'Welcome '; echo $_POST["thisexname"]; echo "<br>";
}
?>
<?php
/*Setup example runs; an example run of 0 does not run! */
if ($example_run > 0) {
echo '<p>Example content being viewed currently is now example number '.$example_run.':';
}
...
Intermediate code (full Widget Function):
public function widget( $args, $instance ) {
/* include "thiswidget.php"; */ /*disable for now*/
/* Include the widget($args, $instance) function body */
/* include "businesspartnerships.php"; */ /*Original works fine with id update */
static $recommended_ex_no = 3;
static $example_run = 4;
$example_max = 4;
$example_min = 0;
$this_widg_id = $this->id; /* Get the widget ID to be the unique ID Key */
$default_slider_value = 3; /*Default slider value if nothing new has been posted */
if ($example_run > 0) { /*Provide a slider to select examples */
/*See http://foundation.zurb.com/sites/docs/v/5.5.3/components/range_slider.html */
/*See http://www.html5tutorial.info/html5-range.php */
/*See https://www.w3schools.com/php/php_forms.asp */
?><p> Recommended View Example Number: <?php echo $recommended_ex_no ?></p>
<!-- See: http://stackoverflow.com/questions/11788005/how-to-get-fetch-html5-range-sliders-value-in-php -->
<form action="" method="get">
<input type="range" min="<?php echo $example_min;?>" max="<?php echo $example_max;?>" step="1" value="<?php echo $set_slider_value ?>" id="<?php echo $this_widg_id; ?>" name="<?php echo $this_widg_id; ?>" onchange='document.getElementById("text_<?php echo $this_widg_id; ?>").value = "Slider Value = " + document.getElementById("<?php echo $this_widg_id; ?>").value;'/>
<br><center><input type="text" style="text-align: center" name="text_<?php echo $this_widg_id; ?>" id="text_<?php echo $this_widg_id; ?>" value="Slider Value = <?php echo $default_slider_value ?>" disabled /></center>
<br />
<center><input style="text-align: center" type="submit" value="Submit" /></center>
</form>
<?php
$this_widg_id = esc_attr( $this->id) ; /* Get the widget ID to be the unique ID Key */
echo "The key is : "; echo esc_attr( $this->id); echo "<br><br>";
if(isset($_GET[esc_attr( $this->id)])){
echo '<br> isset below get <br>';
echo "<center>The example selected is: ".$_GET[esc_attr( $this->id)]." </center>";
// Your Slider value is here, do what you want with it. Mail/Print anything..
$example_run = $_GET[esc_attr( $this->id)];
$set_slider_value = $_GET[esc_attr( $this->id)]; /*If the value has been posted, then show it.*/
} else {
/* $set_slider_value = $default_slider_value; */ /* Slider value is initially set to default. */
}
}
/* Try https://www.w3schools.com/php/php_forms.asp example here, since form update was not working before */
?>
<!-- <form action="wp-content/plugins/carousel_edit_url_for_newspro/welcome_get.php" method="post"> -->
<form action="" method="get">
Name: <input type="text" name="thisexname"><br>
<!-- E-mail: <input type="text" name="email"><br> -->
<input type="submit">
</form>
<?php
if (isset($_GET[esc_attr("thisexname")])){
echo 'Welcome '; echo $_GET["thisexname"]; echo "<br>";
}
?>
<?php
/*Setup example runs; an example run of 0 does not run! */
if ($example_run > 0) {
echo '<p>Example content being viewed currently is now example number '.$example_run.':';
}
if ($example_run == 1) {
echo '<p>Example Business Partnerships Begins</p>';
include "businesspartnerships.php"; /*full copy*/
echo '<p>Example BP Ends</p>';
}
elseif ($example_run == 2) {
echo '<p>Example for Business Begins</b>';
include "businesscarousel/business_head.php"; /*content before the loop*/
include "businesscarousel/business_loop.php"; /*the loop*/
include "businesscarousel/business_tail.php"; /*content after the loop*/
echo '<p>Example for Business Ends</b>';
}
elseif ($example_run == 3) {
echo '<p>Example for Books Begins</b>';
include "bookscarousel/books.php";
echo '<p>Example for Books Ends</b>';
}
elseif ($example_run == 4) {
echo '<p>Example for Looped Books Begins</b>';
include "bookscarousel/books_head_vars.php";
include "bookscarousel/books_head.php";
include "bookscarousel/books_loop_vars.php";
include "bookscarousel/books_loop.php";
include "bookscarousel/books_tail_vars.php";
include "bookscarousel/books_tail.php";
echo '<p>Example for Looped Books Ends</b>';
}
}
I finally cleaned up the code a little bit, taking out the examples and just running with the essentials (verified that this basically worked):
/**
* Front-end display of widget.
*
* #see WP_Widget::widget()
*
* #param array $args Widget arguments.
* #param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
/* include "thiswidget.php"; */ /*disable for now*/
/* Include the widget($args, $instance) function body */
/* include "businesspartnerships.php"; */ /*Original works fine with id update */
$example_run = 4; /*Set to 0 to disable all widget output */
$example_max = 4;
$example_min = 0;
$recommended_ex_no = 4;
$default_slider_value = 4; /*Default slider value if nothing new has been posted */
$this_widg_id = $this->id; /* Get the widget ID to be the unique ID Key */
if ($example_run > 0) { /*Provide a slider to select examples */
?><p> The Recommended Example Number To View is Example Number <?php echo $recommended_ex_no ?>.</p>
<!-- See: http://stackoverflow.com/questions/11788005/how-to-get-fetch-html5-range-sliders-value-in-php -->
<form action="" method="get">
<input type="range" min="<?php echo $example_min;?>" max="<?php echo $example_max;?>" step="1" value="<?php echo $set_slider_value ?>" id="<?php echo $this_widg_id; ?>" name="<?php echo $this_widg_id; ?>" onchange='document.getElementById("text_<?php echo $this_widg_id; ?>").value = "Slider Value = " + document.getElementById("<?php echo $this_widg_id; ?>").value;'/>
<br><center><input type="text" style="text-align: center" name="text_<?php echo $this_widg_id; ?>" id="text_<?php echo $this_widg_id; ?>" value="Slider Value = <?php echo $default_slider_value ?>" disabled /></center>
<br />
<center><input style="text-align: center" type="submit" value="Submit Slider Value" /></center>
</form>
<?php
$this_widg_id = esc_attr( $this->id) ; /* Get the widget ID to be the unique ID Key */
echo '<br><br><center><p style="text-align: center">This example widget instance is entitled, "';
echo esc_attr( $this->id); echo '".</p></center>';
if(isset($_GET[esc_attr( $this->id)])){
/* echo "<center>The example selected is: ".$_GET[esc_attr( $this->id)]." </center>"; */ /*Activate to debug */
// Your Slider value is here, do what you want with it. Mail/Print anything..
$example_run = $_GET[esc_attr( $this->id)];
$set_slider_value = $_GET[esc_attr( $this->id)]; /*If the value has been posted, then show it.*/
} else {
$set_slider_value = $default_slider_value; /* Slider value is initially set to default. */
}
} /*End if example is >0 */
/* If not working, adapt https://www.w3schools.com/php/php_forms.asp example here, since form update was not working before */
/*Setup example runs; an example run of 0 does not run! */
if ($example_run > 0) {
echo '<center><p style="text-align: center">The example content being viewed currently is now example number '.$example_run.':</p>';
}
if ($example_run == 1) {
echo '<p>Example Business Partnerships Begins</p>';
include "businesspartnerships.php"; /*full copy*/
echo '<p>Example BP Ends</p>';
}
elseif ($example_run == 2) {
echo '<p>Example for Business Begins</b>';
include "businesscarousel/business_head.php"; /*content before the loop*/
include "businesscarousel/business_loop.php"; /*the loop*/
include "businesscarousel/business_tail.php"; /*content after the loop*/
echo '<p>Example for Business Ends</b>';
}
elseif ($example_run == 3) {
echo '<p>Example for Books Begins</b>';
include "bookscarousel/books.php";
echo '<p>Example for Books Ends</b>';
}
elseif ($example_run == 4) {
echo '<p>Example for Looped Books Begins</b>';
include "bookscarousel/books_head_vars.php";
include "bookscarousel/books_head.php";
include "bookscarousel/books_loop_vars.php";
include "bookscarousel/books_loop.php";
include "bookscarousel/books_tail_vars.php";
include "bookscarousel/books_tail.php";
echo '<p>Example for Looped Books Ends</b>';
}
}
Also I had to make sure that the double quote " was not being used where the better ' quote unquote ' should be used.
Any advice to do this better?
And the next part of the question: how is this done on the back-end in the widgets appearance part of the admin screen?
The code I have for the back-end functions is (two-parts):
public function form( $instance ) {
/*
$title - site title
$url_config - private key to website or local file for include
$category_name_textbox - name of the category used for the widget in the textbox
$category_name - name of the category used for the widget
$posts_to_show - number of posts to show
*/
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
$url_config = ! empty( $instance['url_config'] ) ? $instance['url_config'] : esc_html__( 'Display All', 'text_domain' );
$category_name_textbox = ! empty( $instance['category_name_textbox'] ) ? $instance['category_name_textbox'] : esc_html__( 'uncategorized', 'text_domain' );
$category_name = ! empty( $instance['$category_name'] ) ? $instance['$category_name'] : esc_html__( 'uncategorized', 'text_domain' );
$posts_to_show = ! empty( $instance['$posts_to_show'] ) ? $instance['posts_to_show'] : esc_html__( '4', 'text_domain' );
include "form_html.php";
}
The include "form_html.php" is included near the end of "public function form( $instance ) " to make the code more readable and also to highlight the issue. Its contents are here:
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p><label for="<?php echo esc_attr( $this->get_field_id('url_config' ) ); ?>"><?php esc_attr_e( 'URL Config:', 'text_domain' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'url_config' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'url_config' ) ); ?>" type="text" value="<?php echo esc_attr( $url_config ); ?>">
</p>
</p><label for="<?php echo esc_attr( $this->get_field_id('category_name_textbox' ) ); ?>"><?php esc_attr_e( 'Category Name:', 'text_domain' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'category_name_textbox' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'category_name_textbox' ) ); ?>" type="text" value="<?php echo esc_attr( $category_name_textbox ); ?>">
</p>
<p>
<label><?php _e( 'Category', 'newsmag-pro' ); ?> :</label>
<select name="<?php echo esc_attr( $this->get_field_name( 'newsmag_category' ) ); ?>"
id="<?php echo esc_attr( $this->get_field_id( 'newsmag_category' ) ); ?>">
<option value="" <?php if ( empty( $instance['newsmag_category'] ) ) {
echo 'selected="selected"';
} ?>><?php _e( '– Select a category –', 'newsmag-pro' ) ?></option>
<?php
$categories = get_categories( 'hide_empty=0' );
foreach ( $categories as $category ) { ?>
<option
value="<?php echo esc_attr( $category->slug ); ?>" <?php selected( esc_attr( $category->slug ), $instance['newsmag_category'] ); ?>><?php echo esc_attr( $category->cat_name ); ?></option>
<?php } ?>
</select>
</p>
<p>Selected Category: <? echo $instance['newsmag_category'] ?></p>
<label class="block" for="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ); ?>">
<span class="customize-control-title">
<?php _e( 'Posts to Show', 'newsmag-pro' ); ?> :
</span>
</label>
<input type="text" name="<?php echo esc_attr( $this->get_field_name( 'show_post' ) ); ?>" class="rl-slider"
id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ); ?>"
value="<?php echo esc_attr( $instance['show_post'] ); ?>" />
<div id="slider_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>" data-attr-min="4"
data-attr-max="12" data-attr-step="1" class="ss-slider"></div>
<script>
jQuery(document).ready(function ($) {
$('[id="slider_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ); ?>"]').slider({
value: <?php echo esc_attr( $instance['show_post'] ); ?>,
range: 'min',
min : 4,
max : 12,
step : 1,
slide: function (event, ui) {
$('[id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ); ?>"]').val(ui.value).keyup();
}
});
$('[id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').on('focus', function(){
$('[id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').trigger('blur');
});
$('[id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').val($('[id="slider_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').slider("value"));
$('[id="input_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').change(function () {
$('[id="slider_<?php echo esc_attr( $this->get_field_id( 'show_post' ) ) ?>"]').slider({
value: $(this).val()
});
});
});
</script>
<?php
So what is going wrong on the back-end? I can select the drop-down and it does not update anything. And I can adjust the slider bar, but then I cannot reference its value later to save its value. Any ideas how to solve the back-end website management aspect of this problem?
Because I am just registering, the references are limited to two. So you can find the more complete reference list at:
http://newyorkbusinessreview.com/wordpress/technology/stephen-elliott/technical-programming-questions/
By the way, if you go to the main website:
http://www.newyorkbusinessreview.com/
The main site currently redirects while still under construction to:
http://www.newyorkbusinessreview.com/wordpress/
I may have the plugin front-end disabled to not bring down the site while I am still working on the issues.
I basically copied and pasted the part of the code that had to do with the slider and the text box, just modifying the names and ID's slightly. On the back end it is easy to output values in a text box. That seems to have solved it. The slider now works on the back end and it updates the text box also inside the widget form there!
If any additional detail is wanted, please let me know so I can provide code samples if desired.

Echo Selected Value Wordpress

I'm stuck with this. I can't get the selected option to display the selected item in the backend of Wordpress. It saves to the database and I can echo it out on the front end. Pulling my hair out now.
<?php add_action( 'add_meta_boxes', 'dynamic_add_custom_box' );
/* Do something with the data entered */
add_action( 'save_post', 'dynamic_save_postdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function dynamic_add_custom_box() {
add_meta_box(
'dynamic_sectionid',
__( 'Plot Status', 'myplugin_textdomain' ),
'dynamic_inner_custom_box',
'house_type');
}
/* Prints the box content */
function dynamic_inner_custom_box() {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' );
?>
<div id="meta_inner">
<?php
//get the saved meta as an arry
$plots = get_post_meta($post->ID,'plots',true);
$c = 0;
if ( count( $plots ) > 0 ) {
foreach( $plots as $plotno ) {
if ( isset( $plotno['title'] ) || isset( $plotno['plotno'] ) || isset( $plotno['development'] ) ) {
printf( '
<p>Plot Number: <input type="text" name="plots[%1$s][title]" value="%2$s" />
Status : <select name="plots[%1$s][plotno]" value="%3$s">
<option value="Not Released" '. selected( 'plots[%1$s][plotno]', "Not Released" ).'>Not Released</option>
<option value="Available" '. selected( 'plots[%1$s][plotno]', "Available" ) .'>Available</option>
<option value="Reserved" '. selected( 'plots[%1$s][plotno]', "Reserved" ) .'>Reserved</option>
<option value="Sold" '. selected( 'plots[%1$s][plotno]', "Sold" ) .'>Sold</option>
</select>
Development : <input type="text" name="plots[%1$s][development]" value="%4$s" />
<span class="remove" style="color:red;cursor:pointer;padding-left:10px;">%5$s</span></p>', $c, $plotno['title'], $plotno['plotno'], $plotno['development'], __( 'Remove' ) );
$c = $c +1;
}
}
}
?>
<span id="here"></span>
<div class="button">
<span class="add"><?php _e('Add Plot Number'); ?></span></div>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
$(".add").click(function() {
count = count + 1;
$('#here').append('<p> Plot Number: <input type="text" name="plots['+count+'][title]" value="" /> Status : <select name="plots['+count+'][plotno]" value=""><option value="" >Not Released</option><option value="">Available</option><option value="">Reserved</option> <option value="">Sold</option> </select> Development : <input type="text" name="plots['+count+'][development]" value="" /> <span style="remove" >Remove</span></p>' );
return false;
});
$(".remove").live('click', function() {
$(this).parent().remove();
});
});
</script>
</div><?php
}
What I've done is I've tried to edit this by adding a drop down select option. tutorial
I did this in script. Its working
add_action( 'add_meta_boxes', 'dynamic_add_custom_box' );
/* Do something with the data entered */
add_action( 'save_post', 'dynamic_save_postdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function dynamic_add_custom_box() {
add_meta_box( 'dynamic_sectionid', __( 'Plot Status', 'myplugin_textdomain' ), 'dynamic_inner_custom_box','post');
}
/* Prints the box content */
function dynamic_inner_custom_box() {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' );
?>
<div id="meta_inner">
<?php
//get the saved meta as an arry
$plots = get_post_meta($post->ID,'plots',true);
$c = 0;
if ( count( $plots ) > 0 ) {
foreach( $plots as $plotno ) {
if ( isset( $plotno['title'] ) || isset( $plotno['plotno'] ) || isset( $plotno['development'] ) ) {
printf( '
<p>Plot Number: <input type="text" name="plots[%1$s][title]" value="%2$s" />
Status : <select name="plots[%1$s][plotno]" class="plotnoclass_%1$s">
<option value="Not Released">Not Released</option>
<option value="Available">Available</option>
<option value="Reserved">Reserved</option>
<option value="Sold">Sold</option>
</select>
Development : <input type="text" name="plots[%1$s][development]" value="%4$s" />
<span class="remove" style="color:red;cursor:pointer;padding-left:10px;">%5$s</span></p>', $c, $plotno['title'], $plotno['plotno'], $plotno['development'], __( 'Remove' ) );
echo "<script>jQuery(\".plotnoclass_$c\").val('".$plotno['plotno']."');</script>";
$c = $c +1;
}
}
}
?>
<span id="here"></span>
<div class="button">
<span class="add"><?php _e('Add Plot Number'); ?></span></div>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
$(".add").click(function() {
count = count + 1;
$('#here').append('<p> Plot Number: <input type="text" name="plots['+count+'][title]" value="" /> Status : <select name="plots['+count+'][plotno]" value=""><option value="" >Not Released</option><option value="">Available</option><option value="">Reserved</option> <option value="">Sold</option> </select> Development : <input type="text" name="plots['+count+'][development]" value="" /> <span style="remove" >Remove</span></p>' );
return false;
});
$(".remove").live('click', function() {
$(this).parent().remove();
});
});
</script>
</div><?php
}

default value not getting displayed in input field wordpress

I have written code for creating theme options
but default values not getting displayed in text field
Also settings saved message also not getting displayed
Thank you
<?php
// Default options values
$xyz_options = array(
'footer_copyright' => '© ' . date('Y') . ' ' . get_bloginfo('name'),
'facebook'=>'http://www.facebook.com/'
);
if ( is_admin() ) : // Load only if we are viewing an admin page
function xyz_register_settings() {
// Register settings and call xyz initiation functions
register_setting( 'xyz_theme_options', 'xyz_options', 'xyz_validate_options' );
}
add_action( 'admin_init', 'xyz_register_settings' );
function xyz_theme_options() {
// Add theme options page to the admin menu
add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'theme_options', 'xyz_theme_options_page' );
}
add_action( 'admin_menu', 'xyz_theme_options' );
// Function to generate options page
function xyz_theme_options_page() {
global $xyz_options;
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false; // This checks whether the form has just been submitted. ?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . get_current_theme() . __( ' Options' ) . "</h2>";
// This shows the page's name and an icon if one has been provided ?>
<?php if ( false !== $_REQUEST['updated'] ) : ?>
<div class="updated fade"><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; // If the form has just been submitted, this shows the notification ?>
<form method="post" action="options.php">
<?php $settings = get_option( 'xyz_options', $xyz_options ); ?>
<?php settings_fields( 'xyz_theme_options' );
/* This function outputs some hidden fields required by the form,
including a nonce, a unique number used to ensure the form has been submitted from the admin page
and not somewhere else, very important for security */ ?>
<table class="form-table">
<tr valign="top">
<th scope="row">
<label for="facebook">Facebook url</label>
</th>
<td>
<input id="facebook" name="xyz_options[facebook]" type="text" value="<?php esc_attr_e($settings['facebook']); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">
<label for="footer_copyright">Footer Text 1</label>
</th>
<td>
<input id="footer_copyright" name="xyz_options[footer_copyright]" type="text" value="<?php esc_attr_e($settings['footer_copyright']); ?>" />
</td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="Save Options" />
</p>
</form>
</div>
<?php
}
function xyz_validate_options( $input ) {
global $xyz_options;
$settings = get_option( 'xyz_options', $xyz_options );
}
endif; // EndIf is_admin()
I have wriiten above code.
Please help
Thank you
I tested your code and the default values are being displayed correctly.
Doing a var_dump($_REQUEST); shows what's the problem with the update message, we have to check simpy for $_REQUEST['settings-updated'].
You can remove the is_admin() checking, as admin_init and admin_menu only run on admin.
The validation function should be something like this, validating each input field and returning a clean array with sanitized values:
function xyz_validate_options( $input ) {
$new_input = array();
if( isset( $input['facebook'] ) )
$new_input['facebook'] = esc_url( $input['facebook'] );
if( isset( $input['footer_copyright'] ) )
$new_input['footer_copyright'] = esc_attr( $input['footer_copyright'] );
return $new_input;
}

Trying to send a hidden input value to next page

I am trying to tweak Wordpress Jigoshop according to my customer's needs and I got a bit stuck. What I need is: when a product variation is selected, some additional options appear in the form of radio buttons which customers must chose. I've managed to get everything working, but what I need now is to send the selected radio button to the cart, checkout and so on when the submit button is clicked.
I am trying to use their product customization function to do this and their function is:
if (!function_exists('jigoshop_product_customize_panel')) {
function jigoshop_product_customize_panel() {
global $_product;
if ( isset( $_POST['Submit'] ) && $_POST['Submit'] == 'Save Personalization' ) {
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom_products[$_POST['customized_id']] = trim( wptexturize( $_POST['jigoshop_customized_product'] ));
jigoshop_session::instance()->customized_products = $custom_products;
}
if ( get_post_meta( $_product->ID , 'customizable', true ) == 'yes' ) :
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$_product->ID] ) ? $custom_products[$_product->ID] : '';
$custom_length = get_post_meta( $_product->ID , 'customized_length', true );
$length_str = $custom_length == '' ? '' : sprintf( __( 'You may enter a maximum of %s characters.', 'jigoshop' ), $custom_length );
echo '<div class="panel" id="tab-customize">';
echo '<p>' . apply_filters('jigoshop_product_customize_heading', __('Enter your personal information as you want it to appear on the product.<br />'.$length_str, 'jigoshop')) . '</p>';
?>
<form action="" method="post">
<input type="hidden" name="customized_id" value="<?php echo esc_attr( $_product->ID ); ?>" />
<?php
if ( $custom_length == '' ) :
?>
<textarea
id="jigoshop_customized_product"
name="jigoshop_customized_product"
cols="60"
rows="4"><?php echo esc_textarea( $custom ); ?>
</textarea>
<?php else : ?>
<input
type="text"
id="jigoshop_customized_product"
name="jigoshop_customized_product"
size="<?php echo $custom_length; ?>"
maxlength="<?php echo $custom_length; ?>"
value="<?php echo esc_attr( $custom ); ?>" />
<?php endif; ?>
<p class="submit"><input name="Submit" type="submit" class="button-alt add_personalization" value="<?php _e( "Save Personalization", 'jigoshop' ); ?>" /></p>
</form>
<?php
echo '</div>';
endif;
}
}
I tried modifying their function to suit my needs and this is what I've come up with (where get_cod is the id and name of the hidden input and "Adauga in cos" is the value of my submit button):
if (!function_exists('salveaza_cod_material')) {
function salveaza_cod_material() {
global $_product;
if ( isset( $_POST['submit']) && $_POST('submit') == 'Adauga in cos') {
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom_products[$_POST['customized_id']] = trim( wptexturize( $_POST['get_cod'] ));
jigoshop_session::instance()->customized_products = $custom_products;
}
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$_product->ID] ) ? $custom_products[$_product->ID] : '';
}}
However the value isn't sent to the next page. Can anybody please help? Cheers!
Here's an update containing more of the code:
<form action="<?php echo esc_url( $_product->add_to_cart_url() ); ?>" class="variations_form cart" method="post">
<fieldset class="variations">
<?php foreach ( $attributes as $name => $options ): ?>
<?php $sanitized_name = sanitize_title( $name ); ?>
<div>
<span class="select_label"><?php echo jigoshop_product::attribute_label('pa_'.$name); ?></span>
<select id="<?php echo esc_attr( $sanitized_name ); ?>" name="tax_<?php echo $sanitized_name; ?>">
<option value=""><?php echo __('Choose an option ', 'jigoshop') ?>…</option>
<?php foreach ( $options as $value ) : ?>
<?php if ( taxonomy_exists( 'pa_'.$sanitized_name )) : ?>
<?php $term = get_term_by( 'slug', $value, 'pa_'.$sanitized_name ); ?>
<option value="<?php echo esc_attr( $term->slug ); ?>"><?php echo $term->name; ?> </option>
<?php else : ?>
<option value="<?php echo esc_attr( sanitize_title( $value ) ); ?>"><?php echo $value; ?></option>
<?php endif;?>
<?php endforeach; ?>
</select>
</div>
<?php endforeach;?>
</fieldset>
<div id="piele-neagra" class="colors" style="display:none">
<ul class="materiale">
<li><input type="radio" name="piele-neagra" value="L73">
<p><img class="alignnone size-full wp-image-155" title="L73" src="http://www.scaune-directoriale.ro/wp-content/uploads/materiale/piele-neagra/L73.gif" alt="L73" width="72" height="72" /></p>
</li>
</ul>
</div>
<div id="stofa-mf" class="colors" style="display:none">
<ul class="materiale">
<li><input type="radio" name="tapiterie" value="MF01" />
...
<div id="stofa-rg" class="colors" style="display:none"> Stofa RG</div>
<div class="clear"></div>
<span id="cod_material"><?php echo esc_attr( $custom ); ?></span>
<span><?php echo trim( wptexturize( $_POST['get_cod'] )); ?></span>
<div class="single_variation"></div>
<?php do_action('jigoshop_before_add_to_cart_form_button'); ?>
<div class="variations_button" style="display:none;">
<input type="hidden" name="variation_id" value="" />
<input type="hidden" name="customized_id" value="<?php echo esc_attr( $_product->ID ); ?>" />
<input type="hidden" id="get_cod" name="get_cod" value="" />
<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
<div class="quantity"><input name="quantity" value="1" size="4" title="Qty" class="input-text qty text" maxlength="12" /></div>
<input type="submit" id="submit_cart" class="button-alt" value="<?php esc_html_e('Add to cart', 'jigoshop'); ?>" />
</div>
<?php do_action('salveaza_cod_material'); ?>
<?php do_action('jigoshop_add_to_cart_form'); ?>
</form>
And this is the section of the cart that receives the value:
if ( !empty( $values['variation_id'] )) {
$product_id = $values['variation_id'];
} else {
$product_id = $values['product_id'];
}
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$product_id] ) ? $custom_products[$product_id] : '';
if ( ! empty( $custom_products[$product_id] ) ) :
?>
<dl class="customization">
<dt class="customized_product_label"><?php echo apply_filters('jigoshop_customized_product_label', __('Personal: ','jigoshop') ); ?></dt>
<dd class="customized_product"><?php echo esc_textarea( $custom ); ?></dd>
</dl>
<? php
endif;
?>
It's just a typo: in if ( isset( $_POST['submit']) && $_POST('submit') == 'Adauga in cos'), replace $_POST('submit')by $_POST['submit']

Categories