I have a live search function which fetches WooCommerce products in realtime.
It works perfectly in the front end, however I notice there is a conflict which blocks my WordPress Editor plugin- Brizy from loading within the CMS.
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
Therefore I edit the function to allow me to edit pages:
function ajax_fetch() {
if ( isset( $_GET[ Brizy_Editor::prefix('-edit-iframe') ] ) || isset( $_GET[ Brizy_Editor::prefix('-edit') ] ) ) {
return;
}
?>
<script type="text/javascript">
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
</script>
<?php
}
My update means I can use my page editor, but now my search function doesn’t work.
How can I adjust my code so my search still works correctly and I can load the page editor in the CMS?
Added for context: The second half of my query in functions.php(unchanged in both statements)
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) : $count = 1; while( $the_query->have_posts() ): $the_query->the_post();
if ( $count %4 == 1 ) {
echo '<div class="row"">';
}
global $product;
$product = get_product( get_the_ID() ); //set the global product object
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h4>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_post_thumbnail();?></a></h4>
<p><?php echo $product->get_price_html(); ?></p>
<?php
if( $text = get_field( 'product_overlay_text', $product->get_id() ) ){
echo '<p class="prod-overlay prod-overlay-text">' . $text . '</p>';
}
?>
<?php woocommerce_template_loop_add_to_cart(); //ouptput the woocommerce loop add to cart button ?>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
Front end script
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Your numbers will show here</div>
<script>
function fetch(){
$.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
function(response){
$('#datafetch').append(response);
console.log(result);
});
}
</script>