I have an error "Cannot set property 'onchange' of null" when I try to run this code. Why it shows null if it is not blank?
This code is not mine, I found it in google, but It seems to be working for others.
function woo_product_categories_dropdown( $atts ) {
extract(shortcode_atts(array(
'count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts));
ob_start();
$c = $count;
$h = $hierarchical;
$o = ( isset( $orderby ) && $orderby != '' ) ? $orderby : 'order';
?>
<script type='text/javascript'>
/* <![CDATA[ */
var product_cat_dropdown = document.getElementById("dropdown_product_cat");
function onProductCatChange() {
var urlmenu = document.getElementById( 'menu1' );
if (urlmenu) {
urlmenu.onchange = function()
{
window.open(this.options[ this.selectedIndex ].value,'_self');
};
}
if ( product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value;
}
}
product_cat_dropdown.onchange = onProductCatChange;
/* ]]> */
</script>
<?php
return ob_get_clean();
}
Do you have an element in your html with an id of "menu1"?
If not, you have a few choices:
You would have to create the element with the correct id.
Rename the id of an existing element.
Change the id the script is looking for in the following line:
var urlmenu = document.getElementById( 'newid' );
If you are dealing with a situation where the aforementioned ID may or may not show up in the page, handle the undefined case like such:
on the line which has:
if (urlmenu)
change to:
if (typeof(urlmenu) != "undefined" && urlmenu)
Related
Have been trying to solve this for a couple days and decided to just break down and ask for some insight. I'm basing what I have off of these two solutions:
Change items tax rate in WooCommerce checkout based on radio buttons
Add a dynamic fee based on a select field in WooCommerce Checkout
I'm trying to use a drop down/select to change the tax class on the checkout page of WooCommerce.
I've left a lot alone from the two above examples but am still not getting the results expected. I also need to store & place the delivery location in the admin area & emails but need to get this tax class change issue sorted first.
Below is what I have right now. It seems like it should be working but alas, no joy.
// Add a custom select fields for packing option fee
add_action( 'woocommerce_after_order_notes', 'checkout_shipping_form_packing_addition', 20 );
function checkout_shipping_form_packing_addition( ) {
$domain = 'woocommerce';
echo '<tr class="packing-select"><th>' . __('Pickup Location', $domain) . '</th><td>';
$chosen = WC()->session->get('chosen_packing');
// Add a custom checkbox field
woocommerce_form_field( 'chosen_packing', array(
'type' => 'select',
'class' => array( 'form-row-wide packing' ),
'options' => array(
'' => __("Please select a location...", $domain),
'BELGIUM - LOC' => sprintf( __("BELGIUM - LOC", $domain) ),
'BROOTEN - LOC' => sprintf( __("BROOTEN - LOC", $domain) ),
'OWATONNA - LOC' => sprintf( __("OWATONNA - LOC", $domain) ),
),
'required' => true,
), $chosen );
echo '</td></tr>';
}
// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_shipping_packing_script' );
function checkout_shipping_packing_script() {
// Only checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
WC()->session->__unset('chosen_packing');
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'select#chosen_packing', function(){
var p = $(this).val();
console.log(p);
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
});
</script>
<?php
endif;
}
// Php Ajax (Receiving request and saving to WC session)
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
function woo_get_ajax_data() {
if ( isset($_POST['packing']) ){
$packing = sanitize_key( $_POST['packing'] );
WC()->session->set('chosen_packing', $packing );
echo json_encode( $packing );
}
die(); // Alway at the end (to avoid server error 500)
}
// Add a custom dynamic packaging fee
add_action( 'woocommerce_before_calculate_totals', 'change_tax_class_conditionally', 1000 );
function change_tax_class_conditionally( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$domain = "woocommerce";
$packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
if ( $packing_fee === 'BELGIUM - LOC' ) {
//$label = __("Bag packing fee", $domain);
$tax_class = '5 Percent';
}
if ( $packing_fee === 'BROOTEN - LOC' ) {
//$label = __("Bag packing fee", $domain);
$tax_class = '0 Percent';
}
if ( $packing_fee === 'CHER-MAKE - LOC' ) {
//$label = __("Bag packing fee", $domain);
$tax_class = 'Reduced Rates';
}
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
if( $choice === $field_value ) {
$cart_item['data']->set_tax_class($tax_class);
}
}
}
// Field validation, as this packing field is required
add_action('woocommerce_checkout_process', 'packing_field_checkout_process');
function packing_field_checkout_process() {
// Check if set, if its not set add an error.
if ( isset($_POST['chosen_packing']) && empty($_POST['chosen_packing']) )
wc_add_notice( __( "Please choose a packing option...", "woocommerce" ), 'error' );
}
Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom
I'm building a site within WordPress which will display two rows of images at the start, then on button click, two more, dynamically.
I have four files involved in this process:
case-study-card.php: Which holds the markup for the each card.
home.php: Where the load more button is created.
load-more.js
ajax-loaders.php
However, I'm stumped on where my AJAX is falling apart? I feel as if
/*************/
// load-more.js
/*************/
jQuery(function($){
$('#loadmore').click(function(){
var column_width = $(this).data('column-width');
var max_num_pages = $(this).data('max-num-pages');
var ignore = $(this).data('featured');
var post_type = $(this).data('type');
var button = $(this),
data = {
action:'loadmore',
query: loadmore_params.posts,
page : loadmore_params.current_page,
security : loadmore_params.security
};
$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
console.log ("before sending ajax"); // works
},
success : function( data ){
if( data ) {
console.log("test")
button.text( 'Load More' ).prev().before(data); // insert new posts
loadmore_params.current_page++;
// where to insert new posts...
console.log("now inserting new posts");
$('.case-studies-container').find('.case-card').last().after( data );
console.log("found card");
// if it's the last page in the query, remove the button
if ( loadmore_params.current_page == max_num_pages )
button.remove();
console.log (data);
} else {
// if no data, remove the button as well
button.remove();
}
},
error : function(error){
console.log(error);
}
});
});
});
<!-- In case-study-card.php -->
<div class="case-card" >
<div class="case-card__wrapper">
<h4 class="case-card__title">
Title
</h4>
</div>
</div>
<!-- in home.php
* After looping through and displaying the initial 5 cards, display the button at the bottom
-->
<?php
if ($the_query->found_posts > 5 ){
echo "<div class='case-study__loadmore'><a id='loadmore'>Load more</a>";
}
?>
<!-- ajax-loaders.php -->
<?php
function ajax_handler(){
check_ajax_referer('load_more', 'security');
//prepare arguments for query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
$args['post__not_in'] = explode(',',$_POST['exclude']);
$args['max_num_pages'] = $_POST['max_num_pages'];
$cols = $_POST['columns'];
$type = $_POST['post_type'];
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'ajax_handler'); // wp_ajax_nopriv_{action}
?>
I believe everything after success : function( data ) in load-more.js is not working and I'm not sure why? I also get a admin-ajax.php 400 (Bad Request) error, a file that I have not seen or worked on in this project ...
Edit:
asset-loader.php
wp_localize_script( 'theme', 'loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("load_more")
) );
wp_localize_script( 'theme', 'repeater_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("repeater_field_nonce")
) );
Edit 2:
I believe the ajax handler url : loadmore_params.ajaxurl is working.
When I have url : loadmore_params.ajaxurl the button text changes from "Load more" to "Loading".
When I have url : ajaxurl the button doesn't change beforeSend.
Which makes me think the handler is working fine, but anything within success : function( data ){ isn't working and I'm not sure why.
Place your localize script also so it may be debug properly.
I have a custom taxonomy in WordPress called Case studies.
Home.php is a page. Within home.php I have ran a loop to get all the case studies:
<?php
// only display 5 posts at first, then load 5 more on button click
$args = array('post_type' => 'case-studies', 'posts_per_page' => 5 );
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) {
echo "<div id='customers' class='case-studies-container'>"; // If there are results, create a single div in which all case studies will sit.
// run a loop to get data from all the posts that exist
while ($the_query->have_posts() ) {
$the_query->the_post();
tp_get_part( 'templates/snippets/case-study-card',
array(
'heading' => get_the_title(),
'subheading' => get_field( 'case_study_subheading'),
)
);
}
echo "<div><input type='button' id='loadmore' value='Load more'/></div>
</div>" // case-studies-container closed;
wp_reset_postdata();
} else {
// no posts found
}
?>
On #loadmore button click, I want it to load 5 more posts from the DB and display them. To accomodate this, I have the following JS within *home.php*
<script type="text/javascript">
$(document).ready(function(){
$('#loadmore').click(function(){
// alert('Hello world');
// load more case studies here
jQuery(function($){
var column_width = $(this).data('column-width');
var max_num_pages = $(this).data('max-num-pages');
var ignore = $(this).data('featured');
var post_type = $(this).data('type');
var button = $(this),
data = {
action:'loadmore',
query: loadmore_params.posts, // that's how we get params from wp_localize_script() function
page : loadmore_params.current_page,
security : loadmore_params.security,
columns : column_width,
exclude : ignore,
max_num_pages : max_num_pages,
post_type : post_type
};
$.ajax({
url : loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'Load More' ).prev().before(data); // insert new posts
loadmore_params.current_page++;
$('.case-studies-container').find('.case-card').last().after( data ); // where to insert posts
if ( loadmore_params.current_page == max_num_pages )
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
},
error : function(error){ console.log(error) }
});
});
});
});
</script>
And the following AJAX written in ajax-loaders.php:
<?php
function ajax_handler(){
check_ajax_referer('load_more', 'security');
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
$args['post__not_in'] = explode(',',$_POST['exclude']);
$args['max_num_pages'] = $_POST['max_num_pages'];
$cols = $_POST['columns'];
$type = $_POST['post_type'];
query_posts($args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post(); ?>
<div class="<?php echo ($cols ? 'col-'.$cols : 'col-3') .' '. ($type === 'case-study' ? 'case-studies' : 'article__item'); ?> grid__item" id="<?php echo get_the_id(); ?>">
<?php
tp_get_part( 'templates/snippets/case-study-card',
array(
'filterable' => true,
'post' => $post,
'type' => get_cpt_term(get_the_id(), 'case-studies')
)
);
?>
</div>
<?php
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'ajax_handler'); // wp_ajax_nopriv_{action}
?>
With all these files set up, on button click, nothing happens? If I uncomment out the alert, the alert occurs which means the trigger is occurring, but unsure on where my load more functionality is going wrong?
I am trying to add a WooCommerce categories-dropdown-shortcode, but this seems to not work. I am able to see the drop down, but when i choose a category it doesn't register and nothing happens.
sc: [product_categories_dropdown orderby="title" count="0" hierarchical="0"]
Code that's placed in my functions.php file
<?php
/**
* WooCommerce Extra Feature
* --------------------------
*
* Register a shortcode that creates a product categories dropdown list
*
* Use: [product_categories_dropdown orderby="title" count="0" hierarchical="0"]
*
*/
add_shortcode( 'product_categories_dropdown','woo_product_categories_dropdown' );
function woo_product_categories_dropdown( $atts ) {
extract(shortcode_atts(array(
'count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts));
ob_start();
$c = $count;
$h = $hierarchical;
$o = ( isset( $orderby ) && $orderby != '' ) ? $orderby : 'order';
// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
woocommerce_product_dropdown_categories( $c, $h, 0, $o );
?>
<script type='text/javascript'>
/* <![CDATA[ */
var product_cat_dropdown = document.getElementById("dropdown_product_cat");
function onProductCatChange() {
if ( product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value;
}
}
product_cat_dropdown.onchange = onProductCatChange;
/* ]]> */
</script>
<?php
return ob_get_clean();
}
Update (2019)
Here below is the working code version for this custom product category dropdown shortcode since woocommerce 3 release:
wc_product_dropdown_categories() replace woocommerce_product_dropdown_categories() which was deprecated since woocommerce 3
Modified Javascript/jQuery code.
Some other light changes.
The new working code:
add_shortcode( 'product_categories_dropdown', 'shortcode_product_categories_dropdown' );
function shortcode_product_categories_dropdown( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts( array(
'show_count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts, 'product_categories_dropdown' );
ob_start();
wc_product_dropdown_categories( array(
'show_count' => $atts['show_count'],
'hierarchical' => $atts['hierarchical'],
'orderby' => ( isset($atts['orderby']) && empty($atts['orderby']) ? $atts['orderby'] : 'order' ),
) );
?>
<script type='text/javascript'>
jQuery(function($) {
$('.dropdown_product_cat').change(function(){
if( $(this).val() !=='' ) {
location.href = '<?php echo home_url(); ?>/?product_cat='+$(this).val();
}
});
});
</script>
<?php
return ob_get_clean();
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE example:
1) Inside a Page or post content text Editor (or a text widget):
[product_categories_dropdown orderby="title" count="0" hierarchical="0"]
2) On a php template or code:
echo do_shortcode("[product_categories_dropdown orderby='title' count='0' hierarchical='0']");
Original answer:
If you read the comments for the source of this code that you have picked here, they were some errors and they found some turn around recently.
So the correct updated code seems to be this one:
/**
* WooCommerce Extra Feature Shortcode
* --------------------------
*
* Register a shortcode that creates a product categories dropdown list
*
* Use: [product_categories_dropdown orderby="title" count="0" hierarchical="0"]
*
*/
add_shortcode( 'product_categories_dropdown', 'woo_product_categories_dropdown' );
function woo_product_categories_dropdown( $atts ) {
extract(shortcode_atts(array(
'show_count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts));
ob_start();
$c = $count;
$h = $hierarchical;
$o = ( isset( $orderby ) && $orderby != '' ) ? $orderby : 'order';
// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
woocommerce_product_dropdown_categories( $c, $h, 0, $o );
?>
<script type='text/javascript'>
/* <![CDATA[ */
var product_cat_dropdown = jQuery(".dropdown_product_cat");
function onProductCatChange() {
if ( product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value;
}
}
product_cat_dropdown.onchange = onProductCatChange;
/* ]]> */
</script>
<?php
return ob_get_clean();
}
But it will not work, as woocommerce_product_dropdown_categories() is a buggy function that is deprecated. See this reference about.
May be you could try to use this plugin instead, for that purpose.
For anyone still stuck on this then here is the currently working solution:
/**
* WooCommerce Extra Feature Shortcode
* --------------------------
*
* Register a shortcode that creates a product categories dropdown list
*
* Use: [product_categories_dropdown orderby="title" count="0" hierarchical="0"]
*
*/
add_shortcode( 'product_categories_dropdown', 'woo_product_categories_dropdown' );
function woo_product_categories_dropdown( $atts ) {
extract(shortcode_atts(array(
'show_count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts));
ob_start();
$c = $count;
$h = $hierarchical;
$o = ( isset( $orderby ) && $orderby != '' ) ? $orderby : 'order';
// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
wc_product_dropdown_categories( $c, $h, 0, $o );
?>
<script type='text/javascript'>
/* <![CDATA[ */
var product_cat_dropdown = jQuery(".dropdown_product_cat");
product_cat_dropdown.change(function() {
if ( product_cat_dropdown.val() !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.val();
}
});
/* ]]> */
</script>
<?php
return ob_get_clean();
}