Wordpress Ajax custom taxonomy - javascript

i currently have a wordpress with a custom post type and a custom taxonomy attached to this. ( jobs_category ).
I have the build listing out the categories from this taxonomy like so:
<?php
$taxonomy = 'jobs_category';
$tax_terms = get_terms($taxonomy);
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) {?>
<li id="cat-<?php echo $tax_term->term_id; ?>">
<?php echo $tax_term->name; ?>
</li>
<? } ?>
</ul>
I have then used the following in my functions file:
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts( $args );
ob_start ();
foreach ( $posts as $p ) { ?>
<div id="post-<?php echo $post->ID; ?>">
<h1 class="posttitle"><?php the_title(); ?></h1>
<div id="post-content">
<?php the_excerpt(); ?>
</div>
</div>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
To do the AJAX with the following JS:
<script>
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
jQuery("#loading-animation-2").show();
var ajaxurl = '/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter", cat: catID },
success: function(response) {
jQuery("#category-post-content").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
My question is how do i get it to use the custom taxonomy categories? Im not 100% sure because i've never done it before.
Any help would be great.
Thanks

You have to use tax_query instead of cat. While category is used for native Wordpress taxonomy, so it won't work for custom taxonomies.
Replace your array $args to this:
$args = array (
'tax_query' => array(
array(
'taxonomy' => 'jobs_category',
'field' => 'term_id',
'terms' => array( $cat_id )
)
),
'post_type' => 'jobs', // <== this was missing
'posts_per_page' => 10,
'order' => 'DESC'
);

Related

How to display woocommerce product category in tabs

I'm trying to create a page with Woocommerce product category in tabs.
My tab menus are working, but i need to run a query in each tab content area to the corresponding category.
But when I click on each tab, the tab content shows all posts from the category not the belonging to the current tab. I didn't get the problem which is appearing, please can help me to solve the issue
Here is my code:
<?php
echo '<ul class="nav nav-tabs" role="tablist">';
$args = array(
'post_type' => 'product',
'posts_per_page' => 100,
'product_cat' => $category->slug,
'hide_empty'=> 1,
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_terms( 'product_cat', $args );;
foreach($categories as $category) {
echo '<li><a href="#' . $category->slug.'" role="tab" data-toggle="tab">' .
$category->slug.'('. $category->count .')</a></li>';
$cat_name = $category->slug;
}
echo '</ul>';
echo '<div class="tab-content">';
foreach($categories as $category) {
echo '<div class="tab-pane" id="' . $category->slug.'">';
?>
<?php
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<?php
endwhile;
wp_reset_postdata();
?>
<?php
echo '</div>';
}
?>
The issue is that it displays all post of every category. I stuck on it..Please help
First, you have to get all categories and after that, you have to start a loop of categories and inside that loop get all products by category. check below code.
<?php
function load_scripts() {
wp_enqueue_style( 'jquery-ui-css', get_template_directory_uri().'/assets/css/jquery-ui.css', '' );
wp_enqueue_script( 'jquery-ui-js', get_template_directory_uri().'/assets/js/jquery-ui.js', array('jquery'), time() , false);
}
add_action('wp_enqueue_scripts', 'load_scripts');
function show_product_categories_tabs( $args ){
$atts = shortcode_atts( array(
'' => '',
), $atts, 'show_product_categories_tabs' );
ob_start();
?>
<div id="tabs">
<ul>
<?php
$categories = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => 1,
) );
foreach ( $categories as $key => $cat ) { ?>
<li><?php echo $cat->name; ?></li>
<?php } ?>
</ul>
<?php foreach ( $categories as $key => $cat ) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 100,
'product_cat' => $cat->slug,
'hide_empty' => 1,
'orderby' => 'name',
'order' => 'ASC'
);
?>
<div id="<?php echo $cat->slug; ?>">
<?php
$products = new WP_Query( $args );
if( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; wp_reset_postdata(); endif; ?>
</div>
<?php } ?>
</div>
<script>
( function( $ ) {
$( "#tabs" ).tabs();
$("#tabs ul li").delegate('a', 'click', function(e){
e.preventDefault();
return false;
});
} )(jQuery);
</script>
<?php
$html = ob_get_clean();
return $html;
}
add_shortcode( 'show_product_categories_tabs', 'show_product_categories_tabs', 10, 1 );
?>
Tested and works.

Passing arrays with ajax to custom endpoints

I am using ajax to send data to a custom rest endpoint. I am doing this because i'm creating a filter function on my WP site.
Now I am stuck trying to get the tax_query to work with my array of terms collected with JS on the front end. No matter what I do I cant seem to get this to work, and I am strongly suspecting this is only a minor error that I keep overlooking...
Just to clarify, the ajax sends the request successfully but the query returns all posts no matter what.
Here is the checkboxes used on the front end:
<div class="form-group">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'utst', 'hide_empty' => false, 'orderby' => 'name' ) ) ) :
foreach ( $terms as $term ) :
echo '<div class="form-check">';
echo '<label class="form-check-label" for="'.$term->slug.'"><input class="form-check-input" type="checkbox" id="'.$term->slug.'" name="utstyrAr[]" value="'.$term->term_id.'"> '.$term->name.'</label>'; // ID of the category as the value of an option
echo '</div>';
endforeach;
endif;
?>
</div>
The JS (ajax function):
filterOppdrag(fiOppdrag) {
var utst = [];
var utstyrArray = document.getElementsByName("utstyrAr[]");
for (var i = 0; i < utstyrArray.length; i++) {
if(utstyrArray[i].type =='checkbox' && utstyrArray[i].checked == true) utst.push(utstyrArray[i].value);
}
console.log(utst);
$.ajax({
url: the.root + '/wp-json/myfilter/v1/filter',
type: 'GET',
data: {
'checkUtst' : utst,
},
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
And the wp_query (php):
function myFilter ($data) {
$checkUtst = sanitize_text_field($data['checkUtst']);
//Main $args
$args = array(
'post_type' => 'ml_opp', // Query only "ml_opp" custom posts
'post_status' => 'publish', // Query only posts with publish status
'orderby' => 'date', // Sort posts by date
'order' => 'ASC' // ASC or DESC
);
// for taxonomies / utstyr
if( isset( $utstyr ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
This returns all the posts regardless of terms no matter what I pass through. I get no error messages and yes I have tested so that there is value in the array when I send it to the query. But what happens to it on the road there, I dont know. That's why i figure that Its probably just a rookie mistake I am making here.
Any help would be greatly appreciated!
Have you tried removing the wrapping array and not using a key?
$args = array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
);

How to combine the functionality of a list with a textbox

Right now I have a form that I created in cakephp and it works fine but the problem I am running into is that we run queries off of the type in the database and there have been some user errors with spelling so I would like to have a list with the most common types that you can select from but if it is not in the list you can still type in something different.
I found this jquery autocomplete combobox that works great but I am not able to enter something that is not in the list. http://jqueryui.com/autocomplete/#combobox
I don't know if you need to see my form or not but I will post it anyway
<?php
echo $this->Form->create( 'Credential', array( 'class' => 'popup_form' ) );
echo $this->Form->hidden( 'account_id', array( 'value' => $account_id ) );
echo $this->Form->hidden( 'user_id', array( 'value' => $currentUser['User']['id'] ) );
echo $this->Form->hidden( 'created', array( 'value' => date("Y-m-d H:i:s") ) );
echo $this->Form->hidden( 'modified', array( 'value' => date("Y-m-d H:i:s") ) );
echo '<br/><br/>';
echo $this->Form->input( 'type', array( 'div' => false, 'label' => false, 'placeholder' => 'Account Type' ) );
echo '<br/><br/>';
echo $this->Form->input( 'url', array( 'div' => false, 'label' => false, 'placeholder' => 'URL' ) );
echo '<br/><br/>';
echo $this->Form->input( 'username', array( 'div' => false, 'label' => false, 'placeholder' => 'Username' ) );
echo '<br/><br/>';
echo $this->Form->input( 'password', array( 'div' => false, 'label' => false, 'placeholder' => 'Password' ) );
echo '<br/><br/>';
echo $this->Js->submit( 'Create Credential', array( 'div' => false, 'class' => 'button white medium', 'before' => 'return submitForm();', 'success' => "$('#qtip-add_account_credential').hide();", 'complete' => 'loadTasks();' ) );
echo '<br/><br/>';
echo $this->Form->end();
?>
<script type="text/javascript">
function submitForm(){
var x = document.getElementById("CredentialType").value;
if (x == null || x == "") {
alert("Account Type must be filled out");
return false;
}
else {
return true;
}
}
</script>
I am a backend developer and would love any help I could get on the front end. Thanks.
What you are searching for is a datalist (new in HTML5):
http://www.w3schools.com/tags/tag_datalist.asp
It provides an form input with a predefined list of options, which appears as soon as the user's input matches one of the entries.
BUT: it seems not to be supported in Safari
In your case it would look like that:
<input name="type" list="AccountTypes" placeholder="Account Type">
<datalist id="AccountTypes">
<option value="admin">
<option value="user">
<option value="something else">
</datalist>

DataTables Server Side Processing Adding html content select tag not triggering javascript

I have implemented successfully the datatables server side processing on one of my tables just that the $('.select_users').change(function(event){ doesn't work anymore on my select tab, despite the fact it shows correctly. When I try to select an option from the select tag it should action to the jquery function but it doesn't.
EDIT 28 NOV 2014
I have found that there is an issue with the events and server side processing:
http://www.datatables.net/examples/advanced_init/events_live.html.
So how can I convert script BLOCK #1 to match the script from the above link.
I added the
$('#dataTables-ss').on('click', 'tr', function () {
var name = $('td', this).eq(0).text();
alert( 'You clicked on '+name+'\'s row' );
} );
And this was getting triggered.
BLOCK #1 => Jquery - on change of select it should trigger this function
$('.select_users').change(function(event){
var selected_value = this.value;
var id = $(this).find('option:selected').attr('class');
var id = id.split('-');
var select_id = id[1];
$.ajax({
type: 'post',
url: 'includes/ajax.html',
data: {
action: 'confirm_notconfirm_subscribers',
selected_value: selected_value,
select_id: select_id
},
success: function(data) {
$('#message').html(data).fadeIn(1000).fadeOut(1000);
},
error: function() {
$("#result").html('There was an error');
}
});
});
BLOCK #2 => PHP important part
public function read_subscriber_table() {
$table = 'subscribers';
$primaryKey = 'ID';
$columns = array(
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'email', 'dt' => 2 ),
array( // issue is here in the third array where I create the select string.
'db' => 'confirmed',
'dt' => 3,
'formatter' => function( $d, $row ) {
if ($d == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($d !== '1') { $selected = 'selected'; } else { $selected = ''; }
$string = '<select class="select_users form-control" name="status-users">
<option class="opt-'.$row["ID"].'" value="1" '.$selected.'>Confirmed</option>
<option class="opt-'.$row["ID"].'" value="0" '.$selected.'>Not Confirmed</option>
</select>';
return $string;
}
),
array(
'db' => 'date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'd-m-Y', strtotime($d));
}
),
array(
'db' => 'ID',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '<input type="checkbox" class="checkbox_subscribers" value="'.$d.'" >';
}
)
);
$sql_details = $this->dtss_processing();
require( 'ssp.class.php' );
$result = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns );
$start=$_REQUEST['start'] + 1;
foreach($result['data'] as &$res){
$res[0]=(string)$start;
$start++;
}
echo json_encode($result);
}
BLOCK #3 => Datatables initialized script
$(document).ready(function() {
$('#dataTables-ss').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "includes/data_tables.html?action=read_subscriber_table",
"aaSorting": [[4, 'desc']]
} );
} );
BLOCK #4 => EDIT - before implementing server side the function was looking like this and it was working well.
public function read_subscriber_table() {
$col_names = array('ID', 'name', 'email', 'confirmed', 'date');
$this->read_table('subscribers', $col_names);
$i = 0;
foreach ($this->results as $item) {
$i++;
if ($item->confirmed == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($item->confirmed !== '1') { $selected = 'selected'; } else { $selected = ''; }
?>
<tr id="tablerow-<?php echo $item->ID; ?>">
<td><?php echo $i; ?></td>
<td><?php echo $item->name; ?></td>
<td><?php echo $item->email; ?></td>
<td>
<select class="select_users form-control" name="status-users">
<option class="opt-<?php echo $item->ID; ?>" value="1" <?php echo $selected ?>>Confirmed</option>
<option class="opt-<?php echo $item->ID; ?>" value="0" <?php echo $selected ?>>Not Confirmed</option>
</select>
</td>
<td><?php echo $item->date; ?></td>
<td><input type="checkbox" class="checkbox_subscribers" value="<?php echo $item->ID; ?>" ></td>
</tr>
<?php
}
?>
<?php
}
Follwing on from comments...
Using that updated code as a starting point, change $('#dataTables-ss').on('click', 'tr', function () { to $('#dataTables-ss').on('change', '.select_users', function(event){

How to change img srs attr on hover in WordPress with jQuery

I have following code.
This code is from my theme-options.php file.
and I am still working on it and I develop this all.
function social_icons() {
$icons = array (
'facebook'=>__('Facebook','responsivetheme'),
'google'=>__('Google','responsivetheme'),
'instagram'=>__('Instagram','responsivetheme'),
'linkedin'=>__('Linkedin','responsivetheme'),
'pinterest'=>__('Pinterest','responsivetheme'),
'rss'=>__('RSS','responsivetheme'),
'stumbleupon'=>__('Stumbleupon','responsivetheme'),
'twitter'=>__('Twitter','responsivetheme'),
'vimeo'=>__('Vimeo',''),
'youtube'=>__('Youtube','responsivetheme')
);
$iconsHover = array (
'facebook-h'=>__('Facebook','responsivetheme'),
'google-blank-h'=>__('Google','responsivetheme'),
'instagram-blank-h'=>__('Instagram','responsivetheme'),
'linkedin-blank-h'=>__('Linkedin','responsivetheme'),
'pinterest-h'=>__('Pinterest','responsivetheme'),
'rss-h'=>__('RSS','responsivetheme'),
'stumbleupon-blank-h'=>__('Stumbleupon','responsivetheme'),
'twitter-h'=>__('Twitter','responsivetheme'),
'vimeo-blank-h'=>__('Vimeo',''),
'youtube-h'=>__('Youtube','responsivetheme')
);
?>
<?php
$theme_options = get_option('new_theme_options',false);
$theme_values = unserialize($theme_options);
$icons_options = get_option('social_settings_responsivetheme_options');
$icons_values = unserialize($icons_options);
?>
<?php
foreach( $icons as $key => $value ) :
if (!empty ($theme_values[$key])) :
?>
<img class="" src="<?php echo template_dir('/icons/'.esc_attr( $key ).'.png');?>" alt="<?php echo esc_html( $value )?>" width="<?php echo $icons_values['width'];?>" height="<?php echo $icons_values['height'];?>" />
<?php endif;//END !empty ($theme_values) ?>
<?php foreach ($iconsHover as $key2 => $value2 ): ?>
<script type="text/javascript">
$(document).ready(function(){
var templateDirectory = "<?php echo get_template_directory_uri(); ?>";
$('.social_icons .<?php echo esc_html($value2); ?> img').hover(
function (){
$(this).attr('src', templateDirectory + '/icons/<?php echo esc_attr($key2); ?>.png');
},
function () {
$(this).attr('src', templateDirectory + '/icons/<?php echo esc_attr($key); ?>.png');
});
});//END document
</script>
<?php endforeach;//END foreach $iconsHover?>
<?php endforeach;//END foreach ?>
<?php
}//END social_icons()?>
The problem is when I hover on icons the hover img works but when on mouse out the normal img should still remains, it doesn't.
It replaces all imgs to 'youtube-h' .
How to do that?
Sorry my comment wasn't clear enough.
By putting them in nested loops, you're outputting every possible combination ('facebook', 'facebook-h'), ('facebook', 'google-blank-h'), ('facebook', 'instagram-blank-h')... ('youtube', 'vimeo-blank-h'), ('youtube', 'youtube-h').
What I meant by putting them all in one array was something like this:
$icons = array (
array(
'off' => 'facebook',
'hover' => 'facebook-h',
'label' =>__('Facebook','responsivetheme')
),
array(
'off' => 'google',
'hover' => 'google-blank-h',
'label' =>__('Google','responsivetheme')
),
array(
'off' => 'instagram',
'hover' => 'instagram-blank-h',
'label' =>__('Instagram','responsivetheme')
),
array(
'off' => 'linkedin',
'hover' => 'linkedin-blank-h',
'label' =>__('Linkedin','responsivetheme')
),
array(
'off' => 'pinterest',
'hover' => 'pinterest-h',
'label' =>__('Pinterest','responsivetheme')
),
array(
'off' => 'rss',
'hover' => 'rss-h',
'label' =>__('RSS','responsivetheme')
),
array(
'off' => 'stumbleupon',
'hover' => 'stumbleupon-blank-h',
'label' =>__('Stumbleupon','responsivetheme')
),
array(
'off' => 'twitter',
'hover' => 'twitter-h',
'label' =>__('Twitter','responsivetheme')
),
array(
'off' => 'vimeo',
'hover' => 'vimeo-blank-h',
'label' =>__('Vimeo','responsivetheme')
),
array(
'off' => 'youtube',
'hover' => 'youtube-h',
'label' =>__('Youtube','responsivetheme')
)
);
Then you only need one loop, something like this:
foreach ($icons as $icon) {
}
and you can use $icon['off'], $icon['hover'], and $icon['label'] as appropriate inside that.

Categories