How to use images to change dropdown selection? - javascript

what I'm trying to accomplish is to have image thumbnails replace the dropdown box in a woocommerce variation product page. The way I went to trying to get that to work is when a user clicks on an variation product image, the (will be hidden) dropdown box will change to the correct value just as if the user had interacted with the dropdown box itself. the file I'm working with is variable.php.
Here is a snippet of the code. All my custom codes start with the option tag loop just before the closing Select tag.
$loop = 0; foreach ( $attributes as $name => $options ) : $loop++; $countimg = 0;?>
<select id="<?php echo esc_attr( sanitize_title( $name ) ); ?>" name="attribute_<?php echo sanitize_title( $name ); ?>" >
<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>…</option>
<?php
if ( is_array( $options ) ) {
if ( isset( $_REQUEST[ 'attribute_' . sanitize_title( $name ) ] ) ) {
$selected_value = $_REQUEST[ 'attribute_' . sanitize_title( $name ) ];
} elseif ( isset( $selected_attributes[ sanitize_title( $name ) ] ) ) {
$selected_value = $selected_attributes[ sanitize_title( $name ) ];
} else {
$selected_value = '';
}
// Get terms if this is a taxonomy - ordered
if ( taxonomy_exists( $name ) ) {
$orderby = wc_attribute_orderby( $name );
switch ( $orderby ) {
case 'name' :
$args = array( 'orderby' => 'name', 'hide_empty' => false, 'menu_order' => false );
break;
case 'id' :
$args = array( 'orderby' => 'id', 'order' => 'ASC', 'menu_order' => false, 'hide_empty' => false );
break;
case 'menu_order' :
$args = array( 'menu_order' => 'ASC', 'hide_empty' => false );
break;
}
$terms = get_terms( $name, $args );
$count = 1;
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) )
continue;
echo '<option id="' . $count . '" value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
$count++;}
} else {
foreach ( $options as $option ) {
echo '<option id="' . $count . '" value="' . esc_attr( sanitize_title( $option ) ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
$count++;}
}
}
?>
</select>
<div>
<?php foreach ( $available_variations as $available_variation ) {
$countimg++;
$image_links = $available_variation['image_link'];
echo '<img id="' . $countimg . '" src="' . $image_links . '" onclick="selectVariationOption(this.id)" style="height:65px; margin-bottom:5px;">';
}?>
</div>
<script>
function selectVariationOption(clicked_id) {
document.getElementById("<?php echo esc_attr( sanitize_title( $name ) ); ?>").selectedIndex = clicked_id;
}
</script>
<?php
if ( sizeof($attributes) == $loop )
echo '<a class="reset_variations" href="#reset">' . __( 'Clear selection', 'woocommerce' ) . '</a>';
?>
<?php endforeach;?>
</div>
</div>
What I did here was I added a numerical ID to the option tags and increases with each additional option available. I then showed the available image variations and added a numerical ID that looped to match the corresponding option ID. Finally, I used a simple javascript that when an image is clicked, the dropdown box changes to the correct selectedIndex. The problem is, the page doesn't react to the changes as if the dropdown box was directly interacted with. In short, nothing happens but the dropdown box changing visual value. I want it so that clicking on the image would be the exact same as clicking on an option in the dropdown box.
Let me know if you need more clarification or information. Thanks in advance!

Using the Variation Swatches and Photos plugin worked. Just had to go in and edit the plugin's variable.php to show all the information that was missing from my original variable.php file. Now I just have to spend a couple hours editing each product.

Related

Search query with filter

Thanks to the help of stack overflow I was able to make my filter work(Ajax filter for wordpress) but now I want to add a search input that search the titles of my posts (a custom post type called 'Contratistas').
So I have a few questions:
My form for my filter has POST, but the search (i've seen examples) always has GET, so, should I have two separete forms? If so, is there a way for submiting my search without a button? this is my code:
<form id="searchform" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="text" class="search-field mb-3" name="s" placeholder="Search" value="<?php echo get_search_query(); ?>">
<input type="submit" value="Search" class="mb-3">
</form>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<div class="titulo mb-3">
<h3>Región</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroRegion"><option value="">Seleccione una región</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<div class="titulo my-3">
<h3>Industrias</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'industria', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroIndustria"><option value="">Seleccione una industria</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button class="my-3 filtrar">Filtrar</button>
<button>Limpiar filtros</button>
<input type="hidden" name="action" value="myfilter">
</form>
As you can see i have two buttons but i only want the last one ('Filtrar')
I have no idea how to implement the search with the filters so that i can put my results in the same fashion as the one i get from the dropdowns.
Here is my filter:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista'
);
if (!empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria'])) {
$args['tax_query'] = array();
if (!empty($_POST['filtroRegion'])) {
$args['tax_query'][] = array(
'taxonomy' => 'region',
'terms' => $_POST['filtroRegion']
);
}
if (!empty($_POST['filtroIndustria'])) {
$args['tax_query'][] = array(
'taxonomy' => 'industria',
'terms' => $_POST['filtroIndustria']
);
}
if (count($args['tax_query']) > 1) {
$args['tax_query']['relation'] = 'AND';
}
}
$query = new WP_Query($args);
And my JQuery:
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: $('#filter :input').filter(function(index, element) { return $(element).val() != ''; }).serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('.filtrar').text('Procesando...'); // changing the button label
},
success: function(data) {
filter.find('.filtrar').text('Filtrar'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
}
}
Any help or guidance will be very appreciated. Thanks
I got it! Here's my working code in case somebody else needs it!
The answer was VERY simple! I only had to add this:
's' => $_POST['s']
Here is my function
function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista',
's' => $_POST['s'],
);
//Same code as before:
if( !empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria']) ){
$args['tax_query'] = array();
if(!empty($_POST['filtroRegion']) ){
$args['tax_query'][] = array(
'taxonomy' => 'region',
'terms' => $_POST['filtroRegion']
);
}
}
$query = new WP_Query( $args );
//my post
And my form:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<h3>Buscar</h3>
<input type="text" class="search-field mb-3" name="s" placeholder="Busqueda por nombre" value="<?php echo get_search_query(); ?>">
<div class="titulo mb-3">
<h3>Región</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroRegion"><option value="">Seleccione una región</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>

Solving a PHP which does not store an input?

The context:
On my website users can customize clothing products. Along the customer funnel, it is asked to the user to input a quantity. This quantity is then used when our team receives the order to generate a quote. Nevertheless, it appears that the quantity is not stored as it always returns 1, even when the user inputs another number e.g. 100. I cannot find a way to solve this.
Below you will find code parts that include the quantity dimension. If you see any corrections to be made feel free to mention them.
add_filter( 'wc_add_to_cart_message_html', 'epopey_wc_add_to_cart_message_html', 10, 3);
function epopey_wc_add_to_cart_message_html ( $message, $products, $show_qty ){
$titles = array();
if ( ! is_array( $products ) ) {
$products = array( $products => 1 );
}
if ( ! $show_qty ) {
$products = array_fill_keys( array_keys( $products ), 1 );
}
foreach ( $products as $product_id => $qty ) {
/* translators: %s: product name */
$titles[] = apply_filters( 'woocommerce_add_to_cart_qty_html', ( $qty > 1 ? absint( $qty ) . ' × ' : '' ), $product_id ) . apply_filters( 'woocommerce_add_to_cart_item_name_in_quotes', sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) ), $product_id );
$count += $qty;
}
$titles = array_filter( $titles );
Backorder notification
if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
echo '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'norebro' ) . '</p>';
}
?>
</h4>
</td>
<td class="product-quantity" data-title="<?php esc_html_e( 'Quantity', 'norebro' ); ?>">
<?php
if ( $_product->is_sold_individually() ) {
$product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
} else {
$product_quantity = woocommerce_quantity_input( array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
'min_value' => '0'
), $_product, false );
}
echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
?>
</td>
email details to customer
<td class="td" style="text-align:<?php echo esc_attr( $text_align ); ?>; vertical-align:middle; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;">
<?php
$qty = $item->get_quantity();
$refunded_qty = $order->get_qty_refunded_for_item( $item_id );
if ( $refunded_qty ) {
$qty_display = '<del>' . esc_html( $qty ) . '</del> <ins>' . esc_html( $qty - ( $refunded_qty * -1 ) ) . '</ins>';
} else {
$qty_display = esc_html( $qty );
}
echo wp_kses_post( apply_filters( 'woocommerce_email_order_item_quantity', $qty_display, $item ) );
?>
</td>
order details
<td class="product-quantity">
<?php echo apply_filters( 'woocommerce_order_item_quantity_html', ' <strong class="product-quantity">' . sprintf( '%s', $item->get_quantity() ) . '</strong>', $item ); ?>
</td>
</tr>
<?php if ( $show_purchase_note && $purchase_note ) : ?>
<tr class="product-purchase-note">
<td colspan="2"><?php echo wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ); ?></td>
Table with order details
<table class="woo-my-orders-table woo-details woo-my-content">
<thead>
<tr>
<th class="product-name"><?php esc_html_e( 'Product', 'norebro' ); ?></th>
<th class="product-quantity"><?php esc_html_e( 'Quantity', 'norebro' ); ?></th>
</tr>
</thead>
<tbody>
<?php
foreach( $order->get_items() as $item_id => $item ) {
$product = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
wc_get_template( 'order/order-details-item.php', array(
'order' => $order,
'item_id' => $item_id,
'item' => $item,
'show_purchase_note' => $show_purchase_note,
'purchase_note' => $product ? get_post_meta( $product->get_id(), '_purchase_note', true ) : '',
'product' => $product,
) );
}
?>
<?php do_action( 'woocommerce_order_items_table', $order ); ?>
</tbody>
</table>
Congrats if you read until here, hope there is enough details. Thanks for your time and help.
Edit #1
Could the below code lines be a starting point to solve the problem ?
HTML
<div type="submit" class="wc-proceed-to-checkout" onClick="quantitySubmit(this.form)">
Valider le devis
JS
function quantitySubmit(form){
return (form.submit()){
window.location.href = "https://epopey.co/validation-du-devis/"
}
else {
text = "Please input a number"
}
}
The page that allows a change in quantity isn't updating the cart when it moves to the validate quote page. The button that was added to link to that page doesn't first perform the woo commerce cart update. See below:
The input of type submit must be "clicked" so the page can post back to itself and update the cart before the browser is redirected to the new page.
I'd recommend a simple javascript function in the onclick attribute of the div (class = wc-proceed-to-checkout) that submits the form and returns true/false on success/failure and allows redirection to "https://epopey.co/validation-du-devis/" for success and gives whatever error message you decide on failure.
To redirect in JS: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
If you need help writing the javascript to submit your form and handle the return value, search for answers on this site, I know they exist/also on Google.
There are numerous other ways to solve this as well - hard to give a best practice answer without knowing your code base/the structure of the theme. Hopefully identifying the problem is enough for you to solve on your own.
TLDR; your validate quote button overrides a default submission button to update the cart with increased/decreased quantities. Make sure the form on this page posts before the page is redirected to the next, or you'll lose the changed quantities.

Wordpress unable to save featured image

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.
I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

Wysiwyg is not working in the group field wordpress codestar framwork

I am trying to add one+ more item with Wysiwyg editor in group field with codestar framework metabox option,but it is not working . I tried to figure out solution,but i found that when i rename class of below hidden section, it hidden section get's appear and it works or editor function works correctly for this current item only. but also when i delete this hidden section with saving two or more item ....
Hidden Section:
echo '<div class="cs-group cs-group-'. $el_class .'-adding hidden">';
echo '<h4 class="cs-group-title">'. $acc_title .'</h4>';
echo '<div class="cs-group-content">';
foreach ( $fields as $field ) {
$field['sub'] = true;
$unique = $this->unique .'[_nonce]['. $this->field['id'] .']['. $last_id .']';
$field_default = ( isset( $field['default'] ) ) ? $field['default'] : '';
echo cs_add_element( $field, $field_default, $unique );
}
echo '<div class="cs-element cs-text-right cs-remove">
<a href="#" class="button cs-warning-primary cs-remove-group">'.
esc_html__( 'Remove', 'cs-framework' ) .'</a>
</div>';
echo '</div>';
echo '</div>';
Appeared Full Section:
echo '<div class="cs-groups cs-group-'. $el_class .'-addings hiddens">';
echo '<h4 class="cs-group-title">'. $acc_title .'</h4>';
echo '<div class="cs-group-content">';
foreach ( $fields as $field ) {
$field['sub'] = true;
$unique = $this->unique .'[_nonce]['. $this->field['id'] .']['. $last_id .']';
$field_default = ( isset( $field['default'] ) ) ? $field['default'] : '';
echo cs_add_element( $field, $field_default, $unique );
}
echo '<div class="cs-element cs-text-right cs-remove">
<a href="#" class="button cs-warning-primary cs-remove-group">'.
esc_html__( 'Remove', 'cs-framework' ) .'</a>
</div>';
echo '</div>';
echo '</div>';
echo '<div class="cs-groups cs-accordion">';
if( ! empty( $this->value ) ) {
foreach ( $this->value as $key => $value ) {
$title = ( isset( $this->value[$key][$field_id] ) ) ? $this->value[$key][$field_id] : '';
if('page_type_section' == $field_id) {
$title = get_the_title($this->value[$key][$field_id]);
}
if ( is_array( $title ) && isset( $this->multilang ) ) {
$lang = cs_language_defaults();
$title = $title[$lang['current']];
$title = is_array( $title ) ? $title[0] : $title;
}
$field_title = ( ! empty( $search_id ) ) ? $acc_title : $field_title;
echo '<div class="cs-group cs-group-'. $el_class .'-'. ( $key + 1 ) .'">';
echo '<h4 class="cs-group-title">'. $field_title .': '. $title .'</h4>';
echo '<div class="cs-group-content">';
foreach ($fields as $field ) {
$field['sub'] = true;
$unique = $this->unique . '[' . $this->field['id'] . ']['.$key.']';
$value = ( isset( $field['id'] ) && isset( $this->value[$key][$field['id']] ) ) ? $this->value[$key][$field['id']] : '';
echo cs_add_element( $field, $value, $unique );
}
echo '<div class="cs-element cs-text-right cs-remove">
<a href="#" class="button cs-warning-primary cs-remove-group">'.
esc_html__( 'Remove', 'cs-framework' ) .'</a>
</div>';
echo '</div>';
echo '</div>';
}
}
echo '</div>';
echo ''. $this->field['button_title'] .'';
echo wp_kses_post($this->element_after());
for the first item it works correctly, others not work. i have also inspected it, with inspect option. For the first item it is getting classes id or other thing, but then for the others are not getting or working.Any help...
I solved.
Open cs-framework/fields/wysiwyg/wysiwyg.php
// Replace
wp_editor( $field_value, $field_id, $settings );
// to with
wp_editor( $field_value, $field_id.rand(0,20), $settings );

Custom taxonomies Dropdown without a Submit Button using JavaScript

I Developing one project and I stuck in small thing which is very small for PHP Expert :D Which i'm not
I'm Trying to make Dropdown list of Custom taxonomies which work on select go to that Custom taxonomies page.
But After lot of search I found Solution But not doing action to go to the selected Custom taxonomies
First I found
<?php wp_dropdown_categories( 'taxonomy=my_custom_taxonomy' ); ?>
Second I found
function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
$terms = get_terms( $taxonomy );
if ( $terms ) {
printf( '<select name="%s" class="postform">', esc_attr( $taxonomy ) );
foreach ( $terms as $term ) {
printf( '<option value="%s">%s</option>', esc_attr( $term->slug ), esc_html( $term->name ) );
}
print( '</select>' );
}
}
Which I can use when I insert in any page code billow
<?php fjarrett_custom_taxonomy_dropdown( 'my_custom_taxonomy' ); ?>
Credit
https://frankiejarrett.com/2011/09/create-a-dropdown-of-custom-taxonomies-in-wordpress-the-easy-way/
BUT I DON'T KNOW NOW HOW I GONNA MAKE IT WORKING
Hope you can help me to find solution that from above any one solution can I able to make select and go thing.
Thanks in advance
POSSIBLE ANSWER - 1
I Found Possible Answer
<form id="category-select" class="category-select" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<?php
$args = array(
'show_option_none' => __( 'Select category' ),
'show_count' => 1,
'orderby' => 'name',
'name' => 'cat',
'echo' => 0,
'taxonomy' => 'MyCustomTaxonomys',
'value_field' => 'slug'
);
?>
<?php $select = wp_dropdown_categories( $args ); ?>
<?php $replace = "<select$1 onchange='return this.form.submit()'>"; ?>
<?php $select = preg_replace( '#<select([^>]*)>#', $replace, $select ); ?>
<?php echo $select; ?>
<noscript>
<input type="submit" value="View" />
</noscript>
</form>
It Give me URL
www.website.com/?cat=xxx where xxx is my custom taxonomy
But I Want URL
www.website.com/cat/xxx where xxx is my custom taxonomy
Is it possible?
You
could use something like this :
<?php
function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
$terms = get_terms( $taxonomy );
if ( $terms ) {
printf( '<select name="%s" class="postform">', esc_attr( $taxonomy ) );
foreach ( $terms as $term ) {
printf( '<option value="%s" data-location="%s">%s</option>', esc_attr( $term->slug ), get_term_link(term_id), esc_html( $term->name ) );
}
print( '</select>' );
}
}
?>
Then use your javascript code to redirect depending on the value of the attribute data-location
I did it this way like you say with PHP with wordpres:
<?php function click_taxonomy_dropdown($taxonomy, $title) { ?>
<select name="<?php echo $taxonomy;?>" id="<?php echo $taxonomy;?>">
<option value="-1"><?php echo $title;?></option>
<?php
$terms = get_terms($taxonomy);
foreach ($terms as $term) {
$link = get_term_link( $term, $taxonomy );
if($term->parent == 0){
printf( '<option class="level-1" value="'.$link.'">%s</option>', $term->name );
}
}
echo '</select>';
?>
<?php } ?>
And then with JS:
var dropdown1=document.getElementById("yourtaxonomy");
function onCatChange1(){
if(dropdown1.options[dropdown1.selectedIndex].value>"")
location.href=dropdown1.options[dropdown1.selectedIndex].value
}
The JS just get the ID of your select and then go to value when options are selected
AT End I Found One Alternate Working Solution Writing here so it will help someone needful
<?php
$categories = get_categories('taxonomy=xxxx');
$select = "<select name='' id='cat' class='postform'>n";
$select.= "<option value='-1'>Select category</option>n";
foreach($categories as $category){
if($category->count > 0){
$select.= "<option value='".$category->slug."'>".$category->name."
</option>";
}
}
$select.= "</select>";
echo $select;
?>
<script type="text/javascript">
<!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if (dropdown.options[dropdown.selectedIndex].value != -1) {
location.href = "<?php echo home_url();?>/yyyy/" + dropdown.options[dropdown.selectedIndex].value + "/";
}
}
dropdown.onchange = onCatChange;
-->
</script>
JUST SET Proper XXXX and YYYY Value and solve.
Credit: John B. Hartley
http://www.johnbhartley.com/2012/custom-taxonomy-category-dropdown/
Again Thank you all for your efforts

Categories