Created
May 9, 2024 11:11
-
-
Save dantetesta/5566a2cf0c2e120c88bb598e8e1a5dfe to your computer and use it in GitHub Desktop.
Popula Select com Produtos do Woocommerce com Nome do Produto no Text e Permalink no Value - WORDPRESS + JETFORMBUILDER
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## HOOK WORDPRESS | |
<?php | |
function wpscripts_get_woocommerce_products() { | |
if (!class_exists('WooCommerce')) { | |
wp_send_json_error('WooCommerce não está instalado.'); | |
} | |
$args = array( | |
'status' => 'publish', | |
'type' => 'simple', // Ajuste para incluir outros tipos se necessário | |
'limit' => -1, // Busca todos os produtos; ajuste conforme necessário | |
'return' => 'objects' | |
); | |
$products = wc_get_products($args); | |
$product_data = array(); | |
foreach ($products as $product) { | |
$product_data[] = array( | |
'name' => $product->get_name(), | |
'permalink' => $product->get_permalink() | |
); | |
} | |
wp_send_json_success($product_data); | |
} | |
add_action('wp_ajax_wpscripts_get_products', 'wpscripts_get_woocommerce_products'); | |
add_action('wp_ajax_nopriv_wpscripts_get_products', 'wpscripts_get_woocommerce_products'); | |
<script> | |
jQuery(document).ready(function() { | |
var endpoint = '/wp-admin/admin-ajax.php?action=wpscripts_get_products'; | |
jQuery.get(endpoint, function(response) { | |
if (response.success) { | |
var select = jQuery('#cursos'); | |
select.empty(); // Limpa os options existentes | |
response.data.forEach(function(product) { | |
select.append(jQuery('<option></option>').val(product.permalink).text(product.name)); | |
}); | |
select.change(function() { | |
var selectedText = jQuery(this).find('option:selected').text(); | |
jQuery('input[name="nome_curso"]').val(selectedText); | |
}); | |
} else { | |
console.error('Não foi possível carregar os produtos: ', response.data); | |
} | |
}); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment