Custom taxonomies Dropdown without a Submit Button using JavaScript - 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

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;
?>

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 );

getElementById returns empty from WP Variable

So I have this widget that I coded base on wordpress standard. I declared a sort of variables to be use both backend and frontend purposes.
public function widget( $args, $instance ) {
global $post;
$sid = $instance['id'];
$name = $instance['name'];
$args = array( 'post_type' => 'content_manager','post_id' => $sid);
$query = new WP_Query( $args );
echo $args['before_widget'];
echo $args['after_widget'];
}
public function form( $instance ) {
global $post;
$args = array( 'post_type' => 'content_manager'); ....
$loop = new WP_Query( $args );
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
$sid = ! empty( $instance['id'] ) ? $instance['id'] : esc_html__( 'New ID', 'text_domain' );
$name = ! empty( $instance['name'] ) ? $instance['name'] : esc_html__( 'Empty Content', 'text_domain' );
I am using the variables to get the values in javascript
<script>
function defineValue(sel)
{
var title = sel.options[sel.selectedIndex].text;
var id = sel.options[sel.selectedIndex].value;
document.getElementById("<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>").value = title;
document.getElementById("<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>").value = id;
document.getElementById("<?php echo esc_attr( $this->get_field_name( 'name' ) ); ?>").value = title;
}
</script>
When I load the widget, the inputs and other options displays the names and IDs but in Javascript returns empty unless If I save it first.
I tried to test it
<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>
and this is the result
widget-content-loader-__i__-id
Why is that happen?
Notes:
First Inputs and other elements have ids and other attributes from that variables when I check in the DOM
<input class="widefat" name="widget-content-loader[21][title]" id="widget-content-loader-21-title" value="New title" type="text">
From this this script:
<input
class="widefat"
name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
type="text"
id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
value="<?php echo esc_attr( $title ); ?>">
Thanks in advance
Javascript cant get value unless it is loaded into DOM,
Make sure that the elements are loaded before calling definevalue()

Can you remove wordpress post tags with js/php after certain date (ACF date time picker)?

So my website lists upcoming film screenings in my area.
I'm using the ACF date time picker to only show posts/film screenings that are in the future in the wordpress loop.
I have tags filtering the results dynamically using ajax (thanks to https://www.bobz.co/ajax-filter-posts-tag/) except there are tags that aren't relevant to the results because they belong to posts that are older than the current date (past screenings).
*For example on the website, the 'animated film festival' is still coming up with the other tags.
I don't know if it's possible to delete a posts tags with PHP (within the post template while it loops through other posts) - and to delete the posts tags if the ACF date time field for that post is older than the current date.
I haven't found much luck googling this and I am a bit of a noob so...
This is my site: http://pigcine.pamrosel.com/
This is what I'm doing in my functions.php file at the moment:
// Get all tags and display
function tags_filter() {
$tax = 'post_tag';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '' . $term->name . ' ';
} ?>
</div>
<?php endif; }
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'tag' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => -1,
'meta_key' => 'datetime',
'orderby' => array(
'datetime' => 'ASC'
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while($query->have_posts()) : $query>the_post();
$today = date('Y-m-d H:i:s', strtotime('+9 hours'));
$event_date = get_field('datetime');
if (strtotime($today) <= strtotime($event_date)) {
?>
<div class="sl">
<div class="sl_closed">
<div class="col-2-8"><div class="modulepad">
<p><?php the_field('datetime'); ?></p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_title(); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["directors"]); ?>
</p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_field('location_name'); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["countries"]) . " "; echo $movie["released"] . " "; echo implode(", ", $movie["runtime"]); ?>
</p>
</div></div>
</div><!--SL_CLOSED-->
<?php } endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');

How to use images to change dropdown selection?

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.

Categories