How to call shortcode in wordpress through a select?

1

I have a page inside my website in wordpress + woocommerce which has two selects, and after selecting the two, I would like in a DIV below to call the product by shortcode. The problem is that you probably need a refresh.

HTML

<select class='turno'>
<option value=''>Selecione</option>
<option value='[products skus="a1'>manha</option>
<option value='[products skus="a2'>tarde</option>
<option value='[products skus="a3'>noite</option>   
</select>
<br><br>
<select class='hora'>
<option value=''>Selecione</option>
<option value='[products skus="a1'>1</option>
<option value='[products skus="a2'>2</option>
<option value='[products skus="a3'>3</option>   
</select>
<br><br>
<div><span class="turnoescolhido"></span><span class="horaescolhido"></span>"]</div>

JAVA SCRIPT

 $(document).ready(function(){
 $('.turno').on('change', function(){
 $('.turnoescolhido').text($(this).val());
 });

 $('.hora').on('change', function(){
 $('.horaescolhido').text($(this).val());
 });
 });
    
asked by anonymous 09.02.2017 / 23:42

1 answer

0

You can do a partial update of page content using AJAX.

Quite simply, you would put something like this on your page or js file:

$('.hora').on('change', function(){
    var url = 'http://meusite/wp-admin/admin-ajax.php',
        dados = {
            "action": "products", // nome do shortcode
            "shortcode": $(this).val() // shortcode completo [products...]
        };

    // carrega valor do shortcode no elemento html
    $('.horaescolhido').load(url, dados);

});

And in your plugin or theme:

<?php
// essa é a função que é executada quando usuario não está logado
function wp_ajax_nopriv_products_func() {
    wp_ajax_products_func();
}

// essa é executada quando o usuário está logado
function wp_ajax_products_func() {
    $shortcode = isset($_REQUEST['shortcode']) ? $_REQUEST['shortcode'] : '';

    // para do_shortcode() devemos passar o valor completo do shortcode
    // exemplo [products sku="a1"]
    echo do_shortcode($shortcode)

    // esse die é muito importante
    die; 
}

// registra as funções que irão atender a requisição
// o identificador da função deve ser wp_ajax_ + valor_do_action
// e/ou wp_ajax_nopriv_ + valor_do_action
add_action('wp_ajax_nopriv_products', 'wp_ajax_nopriv_products_func', 1);
add_action('wp_ajax_products', 'wp_ajax_products_func', 1);

?>

Some references:

18.05.2017 / 02:35