How to call shortcode in wordpress through a select?

Asked

Viewed 304 times

1

i have a page inside my site in wordpress+Woocommerce that has two selects, and after selecting the two, I would like it in a DIV below to call the product by shortcode. The problem is 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());
 });
 });

1 answer

0

It is possible to do a partial update of the page contents by 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:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.