javascriptphpwordpresswoocommerceflexslider

Change FlexSlider options on mobile in Woocommerce


By default on single product page enabled option 'controlNav' = 'thumbnails'. It's ok for desktop. But on mobile i want to be 'controlNav' = true (dots). I tried to do it with ajax, but I think I need somehow refresh that fragment with flex slides to apply filter. I cant get it.

in JS file:

if (window.matchMedia('(max-width: 800px)').matches) {
      
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            data: { action: 'mobile_slider'},
            type: 'POST'
        })
        .then(res => console.log('works', res))
    }

in functions.php:

function hellenik_change_slider_mobile()
{
    add_filter('woocommerce_single_product_carousel_options', 'hellenik_update_woo_flexslider_options');

    function hellenik_update_woo_flexslider_options($options)
    {

        $options['smoothHeight'] = true;
        $options['controlNav'] = true;
        $options['animation'] = "slide";
        $options['slideshow'] = false;



        return $options;
    }
    
    wp_die();
}
add_action('wp_ajax_mobile_slider', 'hellenik_change_slider_mobile');
add_action('wp_ajax_nopriv_mobile_slider', 'hellenik_change_slider_mobile');

Solution

  • The following that uses WooCommerce dedicated woocommerce_single_product_carousel_options filter hook and using WordPress wp_is_mobile() conditional tag:

    add_filter( 'woocommerce_single_product_carousel_options', 'filter_single_product_carousel_options' );
    function filter_single_product_carousel_options( $options ) {
        if ( wp_is_mobile() ) {
            $options['smoothHeight'] = true; // Already "true" by default
            $options['controlNav'] = true; // Option 'thumbnails' by default
            $options['animation'] = "slide"; // Already "slide" by default
            $options['slideshow'] = false; // Already "false" by default
        }
        return $options;
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.

    See WooCommerce related default settings for woocommerce_single_product_carousel_options hook:

    'flexslider' => apply_filters( 'woocommerce_single_product_carousel_options',
        array(
            'rtl'            => is_rtl(),
            'animation'      => 'slide',
            'smoothHeight'   => true,
            'directionNav'   => false,
            'controlNav'     => 'thumbnails',
            'slideshow'      => false,
            'animationSpeed' => 500,
            'animationLoop'  => false, // Breaks photoswipe pagination if true.
            'allowOneSlide'  => false,
        )
    ),
    

    Documentation: WordPress Developer Resources - wp_is_mobile() conditional function