例如,WP\\u查询仅用于获取标准post数据。不会提取WC等插件的其他数据。
在theme的函数中放置以下内容。php并将javascript保存到单独的php文件中。快速测试使用WC默认样本产品。
// in theme\'s functions.php
// before init, no products is prepared if just direct call in functions.php, so to have quick test, need to place inside a init
add_action( \'init\', \'ws365398_simple_test\' );
function ws365398_simple_test() {
add_action(\'wp_enqueue_scripts\', \'ws365398_enqueue_scripts\', 101);
add_action( \'wp_ajax_my_action\', \'get_products\' );
add_action( \'wp_ajax_nopriv_my_action\', \'get_products\' );
}
// actions for ajax
function get_products()
{
if( !empty( $_POST[\'category\'] ) ) {
$cat_id = $_POST[\'category\'];
} else {
$cat_id = 19; // default change to yours, in the test case ensure it have something by default
}
$args = array(
\'status\' => \'publish\',
\'ignore_sticky_posts\' => 1,
\'posts_per_page\' => \'12\',
\'tax_query\' => array(
\'relation\' => \'AND\', // relation of 2 taxonomy queries
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'term_id\', //This is optional, as it defaults to \'term_id\'
\'terms\' => $cat_id,
\'operator\' => \'IN\' // Possible values are \'IN\', \'NOT IN\', \'AND\'.
),
array(
\'taxonomy\' => \'product_visibility\',
\'field\' => \'slug\',
\'terms\' => \'exclude-from-catalog\', // Possibly \'exclude-from-search\' too
\'operator\' => \'NOT IN\'
)
)
);
$query = new WC_Product_Query($args);
$products = $query->get_products();
// convert to array data before pushing to json
$product_arr = [];
foreach ($products as $key => $product) {
$product_arr[] = $product->get_data();
}
// echo json_encode($product_arr);
wp_send_json_success( $product_arr ); // with success flag and use directly
wp_die();
}
// enqueue ajax script
function ws365398_enqueue_scripts()
{
wp_enqueue_script(\'test-custom-scripts\', get_theme_file_uri(\'ws365398-test-ajax.php\'), array(), \'t\' . time(), true);
}
<?php
// ws365398-test-ajax.php
/** Load WordPress Bootstrap */
// change to your path
require_once( \'/project/wp-load.php\' );
header("Content-type: text/javascript");?>
function test_ajax() {
let myData = {
action: \'my_action\',
};
jQuery.post(\'<?php echo admin_url( \'admin-ajax.php\' );?>\', myData, function (response) {
if (response.success == true) {
console.log(response);
}
});
}
要进行测试,只需为您的环境准备具有正确路径的上述文件。跑
test_ajax()
在浏览器检查器中,您将看到如下内容: