Join 2 search queries in wordpress Ajax function - wordpress

Hi I have tried everything to join the results of a common search with a sku search but nothing seems to work , it will either show the common search or the sku, not both, any help woulf be appreciated
if (!function_exists('yolo_result_search_callback')) {
function yolo_result_search_callback() {
ob_start();
$yolo_options = yolo_get_options();
$posts_per_page = 8;
if (isset($yolo_options['search_box_result_amount']) && !empty($yolo_options['search_box_result_amount'])) {
$posts_per_page = $yolo_options['search_box_result_amount'];
}
$post_type = array();
if (isset($yolo_options['search_box_post_type']) && is_array($yolo_options['search_box_post_type'])) {
foreach($yolo_options['search_box_post_type'] as $key => $value) {
if ($value == 1) {
$post_type[] = $key;
}
}
}
$keyword = $_REQUEST['keyword'];
if ( $keyword ) {
$search_query = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $keyword,
'posts_per_page' => $posts_per_page + 1,
'compare' => 'LIKE',
'relation' => 'OR',
)
)
);
$search_query = array(
's' => $keyword,
'order' => 'DESC',
'orderby' => 'date',
'post_status' => 'publish',
'post_type' => $post_type,
'posts_per_page' => $posts_per_page + 1,
);
$search = new WP_Query($search_query);
$newdata = array();
if ($search && count($search->post) > 0) {
$count = 0;
foreach ( $search->posts as $post ) {
if ($count == $posts_per_page) {
$newdata[] = array(
'id' => -2,
'title' => '<i class="wicon icon-outline-vector-icons-pack-94"></i> ' . esc_html__('View More','yolo-motor') . '',
'guid' => '',
'date' => null,
);
break;
}
$newdata[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'guid' => get_permalink( $post->ID ),
'date' => mysql2date( 'M d Y', $post->post_date ),
);
$count++;
}
}
else {
$newdata[] = array(
'id' => -1,
'title' => esc_html__( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'yolo-motor' ),
'guid' => '',
'date' => null,
);
}
ob_end_clean();
echo json_encode( $newdata );
}
die(); // this is required to return a proper result
}
add_action( 'wp_ajax_nopriv_result_search', 'yolo_result_search_callback' );
add_action( 'wp_ajax_result_search', 'yolo_result_search_callback' );
}

After playing around all day, I came up with the solution, maybe it can help someone else
if (!function_exists('yolo_result_search_callback')) {
function yolo_result_search_callback() {
ob_start();
$yolo_options = yolo_get_options();
$posts_per_page = 8;
if (isset($yolo_options['search_box_result_amount']) && !empty($yolo_options['search_box_result_amount'])) {
$posts_per_page = $yolo_options['search_box_result_amount'];
}
$post_type = array();
if (isset($yolo_options['search_box_post_type']) && is_array($yolo_options['search_box_post_type'])) {
foreach($yolo_options['search_box_post_type'] as $key => $value) {
if ($value == 1) {
$post_type[] = $key;
}
}
}
$keyword = $_REQUEST['keyword'];
if ( $keyword ) {
$search_query = array(
'post_type' => $post_type,
'meta_query' => array(
array(
'key' => '_sku',
'value' => $keyword,
'posts_per_page' => $posts_per_page + 1,
'compare' => 'LIKE',
'relation' => 'OR',
)
)
);
$search_query1 = array(
's' => $keyword,
'order' => 'DESC',
'orderby' => 'date',
'post_status' => 'publish',
'post_type' => $post_type,
'posts_per_page' => $posts_per_page + 1,
);
$search = new WP_Query($search_query);
$search1 = new WP_Query($search_query1);
$newdata = array();
if ($search && count($search->post) > 0) {
$count = 0;
foreach ( $search->posts as $post ) {
if ($count == $posts_per_page) {
$newdata[] = array(
'id' => -2,
'title' => '<i class="wicon icon-outline-vector-icons-pack-94"></i> ' . esc_html__('View More','yolo-motor') . '',
'guid' => '',
'date' => null,
);
break;
}
$newdata[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'guid' => get_permalink( $post->ID ),
'date' => mysql2date( 'M d Y', $post->post_date ),
);
$count++;
}
}
else {
if ($search1 && count($search1->post) > 0) {
$count = 0;
foreach ( $search1->posts as $post ) {
if ($count == $posts_per_page) {
$newdata[] = array(
'id' => -2,
'title' => '<i class="wicon icon-outline-vector-icons-pack-94"></i> ' . esc_html__('View More','yolo-motor') . '',
'guid' => '',
'date' => null,
);
break;
}
$newdata[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'guid' => get_permalink( $post->ID ),
'date' => mysql2date( 'M d Y', $post->post_date ),
);
$count++;
}
}
else {
$newdata[] = array(
'id' => -1,
'title' => esc_html__( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'yolo-motor' ),
'guid' => '',
'date' => null,
);
}
}
ob_end_clean();
echo json_encode( $newdata );
}
die(); // this is required to return a proper result
}
add_action( 'wp_ajax_nopriv_result_search', 'yolo_result_search_callback' );
add_action( 'wp_ajax_result_search', 'yolo_result_search_callback' );
}

Related

WooCommerce custom pagination is not fetching products according to post per page option value

WooCommerce pagination is not fetching products according to posts per page option value. It shows different products when click on pagination link, sometimes show correct number of products on click of pagination link but some time not. Same query is working for all custom pagination.
Here is my code:
public function render()
{
global $wp_query, $wp_rewrite;
$args= [];
$ordering_args =[];
$pagination_args =[];
$taxonomy = 'product_cat';
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => absint(get_option('posts_per_page')),
);
if (isset($_POST['orderby'])) {
if ('price-desc' === $_POST['orderby']) {
$args['orderby'] = 'price';
$args['order'] = 'DESC';
} elseif ('price' === $_POST['orderby']) {
$args['orderby'] = 'price';
$args['order'] = 'ASC';
} elseif ('date' === $_POST['orderby']) {
$args['orderby'] = 'date';
$args['order'] = 'DESC';
} else {
$args['orderby'] = $_POST['orderby'];
$args['order'] ='';
}
$ordering_args = WC()->query->get_catalog_ordering_args($args['orderby'], $args['order']);
$args['orderby'] = $ordering_args['orderby'];
$args['ordering_args'] = $ordering_args;
$args['order'] = $ordering_args['order'];
if ($ordering_args['meta_key']) {
$args['meta_key'] = $ordering_args['meta_key'];
}
}else{
$ordering_args = WC()->query->get_catalog_ordering_args();
$args['orderby'] = $ordering_args['orderby'];
$args['ordering_args'] = $ordering_args;
$args['order'] = $ordering_args['order'];
if ($ordering_args['meta_key']) {
$args['meta_key'] = $ordering_args['meta_key'];
}
}
if (isset($_POST['paged'])) {
$args['paged'] = absint($_POST['paged']);
if (1 < absint($_POST['paged'])) {
$args['paged'] = absint($_POST['paged']);
}
$pagination_args = array(
'total' => wc_get_loop_prop('total_pages'),
'current' =>absint($_POST['paged']),
);
$args['limit'] = isset($args['posts_per_page']) ? intval($args['posts_per_page']) : intval(get_option('posts_per_page'));
if (empty($args['offset'])) {
$args['offset'] = 1 < $args['paged'] ? ($args['paged'] - 1) * $args['limit'] : 0;
}
}
if (!empty($args['meta_query'])) {
if (!empty($_POST['rating'])) {
$args['meta_query']['relation'] ='AND';
$rating = $_POST['rating'];
$args['meta_query'][]= array(
'key' => '_wc_average_rating',
'value' => array( (int)$rating[0], (int)$rating[1] ),
'compare' => 'BETWEEN',
'type' => 'numeric'
);
}
} else {
if (!empty($_POST['rating'])) {
$rating = $_POST['rating'];
$args['meta_query']= array(
array(
'key' => '_wc_average_rating',
'value' => array( (int)$rating[0], (int)$rating[1] ),
'compare' => 'BETWEEN',
'type' => 'numeric'
)
);
}
}
if (!empty($_POST['product-cata'])) {
$category = $_POST['product-cata'];
$args['tax_query']= array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => (int)$category
)
);
}else{
if (!empty($_POST['category'])) {
$category = $_POST['category'];
$args['tax_query']= array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => (int)$category
)
);
}
}
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) {
ob_start();
// do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
while ($wp_query->have_posts()) {
$wp_query->the_post();
/**
* Hook: woocommerce_shop_loop.
*/
do_action('woocommerce_shop_loop');
echo wc_get_template_part('content', 'product');
}
woocommerce_product_loop_end();
//do_action('woocommerce_after_shop_loop');
wp_reset_postdata();
$_RESPONSE['posted_data'] =$_POST;
$_RESPONSE['products'] = ob_get_contents();
ob_end_clean();
if (isset($_POST['paged'])) {
$paged = (int) $_POST['paged'];
$base = $_POST['link'].'page/%#%';
$pagination_args = array(
'base' => $base,
'total' => (int)$wp_query->max_num_pages,
'per_page' => (int)get_option('posts_per_page'),
'current' => (int) max(1, $paged),
'format' => '',
);
$_RESPONSE['pagination'] = $this->custom_woocommerce_pagination($pagination_args);
$_RESPONSE['result_counts'] = $this->custom_result_count($pagination_args);
} else {
$base = $_POST['link'].'page/%#%';
$pagination_args = array(
'base' => $base,
'total' =>(int) $wp_query->max_num_pages,
'per_page' =>(int) get_option('posts_per_page'),
'current' => (int) max(1, 1),
'format' => '',
);
$_RESPONSE['pagination'] = $this->custom_woocommerce_pagination($pagination_args);
$_RESPONSE['result_counts'] = $this->custom_result_count($pagination_args);
}
$_RESPONSE['args'] = $args;
$_RESPONSE['pagination_args'] = $pagination_args;
} else {
ob_start();
do_action('woocommerce_no_products_found');
$_RESPONSE['products'] = ob_get_contents();
$_RESPONSE['args'] = $args;
ob_end_clean();
}
echo json_encode($_RESPONSE);
die();
}
Any help will appreciate. I am using this in ajax post method.
/*Display only in stock*/
$args['meta_query'][]= [
'key' => '_stock_status',
'value' => 'instock'
];
/*Display only visible product*/
$args['tax_query'][]= [
'taxonomy' => 'product_visibility',
'terms' => array( 'exclude-from-catalog' ),
'field' => 'name',
'operator' => 'NOT IN',
];

How can i display custom post type **posts** list in elementor select control

How can i display custom post type posts list in elementor select control
This is my code =>
I have used this but this shows post categories not post title
$options = array();
$posts = get_posts( array(
'post_type' => 'digital_card'
) );
foreach ( $posts as $key => $post ) {
setup_postdata( $post );
$options[$post->ID] = get_the_title();
}
$this->add_control(
'show_elements',
[
'label' => __( 'Select Posts', 'plugin-domain' ),
'label_block' => ('bool'),
'type' => \Elementor\Controls_Manager::SELECT,
'multiple' => true,
'options' => $options,
]
);
Try the below code.
$options = array();
$posts = get_posts( array(
'post_type' => 'digital_card'
) );
foreach ( $posts as $key => $post ) {
$options[$post->ID] = get_the_title($post->ID);
}
public static function getLocations()
{
$posts = get_posts(array('post_type' => 'location'));
$allPosts = array();
foreach ($posts as $key => $post) {
array_push(
$allPosts,
array(
'map_latitude' => $post->post_author,
'pin_title' => $post->post_title,
)
);
}
return $allPosts;
}
$this->add_control(
'id',
array(
'label' => __('Location Map Pins', 'textdomain'),
'type' => Controls_Manager::REPEATER,
'default' => Hip_Maps_Elementor_Widget::getLocations(),
'fields' => $repeater->get_controls(),
'title_field' => '{{{ pin_title }}}',
'prevent_empty' => false,
)
);

Sending variable to search page

I`ve made this action:
add_action( 'init', 'advanced_search_query' );
function advanced_search_query( $query ) {
if ( isset($_GET['make']) && isset($_GET['model']) && isset($_GET['fuel']) ) {
$all_products = [];
$inner_cats = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $_GET['model']]);
foreach ($inner_cats as $cat) {
if ($_GET['fuel'] == 0)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Diesel']);
elseif ($_GET['fuel'] == 1)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Benzin']);
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => $fuel_cat[0]->term_id,
'operator' => 'IN',
)
)
);
$products = get_posts( $args );
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
}
}
}
}
}
Now what I am strugling with is sending the $all_products to my search page and loop them. Tried to redirect to the search page like wp_safe_recirect('domain.com?s=""') with empty s parameter and use the all_results there. Also tried to set the variable as global but again couldnt reach it.
Did you try the following?
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
?>
<script>window.location.href="domain.com?s=''"</script>
<?php
}
}

Filter with Advansed custom fields, Wordpress

I have filter in my website:
My filter form
Filtering algorithm is:
Filtering algorithm
PHP code for this algorithm:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'work',
'field_2' => 'visa'
);
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
if(is_admin()) return;
if(!$query->is_main_query()) return;
$meta_query = $query->get('meta_query');
$tax_query = $query->get('tax_query');
$k = 0;
foreach($GLOBALS['my_query_filters'] as $key => $name) {
if(empty($_GET[$name])) continue;
$value = explode(',', $_GET[$name]);
foreach($value as $item) {
$meta_query[$k] = array(
'key' => $name,
'value' => $item,
'type' => 'CHAR',
'compare' => 'LIKE'
);
$k++;
}
}
if($_GET['cat']) {
$tax_query[] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_GET['cat'],
'operator' => 'IN'
)
);
$query->set('tax_query', $tax_query);
}
$query->set('meta_query', $meta_query);
}
But I need change filtering algorithm to:
New filtering algorithm
I do not know much WP_Query(). Can you hellp me edit $meta_query?
I changed filter to:
function my_pre_get_posts( $query ) {
if(is_admin()) return;
if(!$query->is_main_query()) return;
$meta_query = $query->get('meta_query');
$tax_query = $query->get('tax_query');
foreach($GLOBALS['my_query_filters'] as $key => $name) {
if(empty($_GET[$name])) continue;
$meta_query['relation'] = 'AND';
$meta_query_inner['relation'] = 'OR';
$value = explode(',', $_GET[$name]);
$k = 0;
foreach($value as $item) {
$meta_query_inner[$k] = array(
'key' => $name,
'value' => $item,
'type' => 'CHAR',
'compare' => 'LIKE'
);
$k++;
}
$meta_query[] = $meta_query_inner;
}
if($_GET['cat']) {
$tax_query[] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_GET['cat'],
'operator' => 'IN'
)
);
$query->set('tax_query', $tax_query);
}
$query->set('meta_query', $meta_query);
}
It seems to work :)

Drupal Submit handler is not called from theme function

I am actually trying to build up a draggable table, but for some reason after implementing the theme_function, my submit handler is no longer getting called.
This is what my Code actually looks like:
function he_ministerienschalter_theme($existing, $type, $theme, $path) {
$themes = array(
'he_ministerienschalter_admin_form' => array(
'render element' => 'element',
),
);
return $themes;
}
/**
* Implements the ministerschalter admin form
*/
function he_ministerienschalter_admin_form($form, &$form_state, $form_id, $item) {
$domainnames = he_ministerienschalter_domainselect();
$count = 0;
$form['ressortswitch'] = array(
'#prefix' => '<div id="curve-attributes">',
'#suffix' => '</div>',
'#tree' => TRUE,
'#theme' => 'he_ministerienschalter_admin_form',
);
foreach ($domainnames as $key => $domainname) {
$form['ressortswitch'][$key]['domainID-'.$key] = array(
'#type' => 'value',
'#value' => $domainname['domain_id'],
);
$form['ressortswitch'][$key]['domainname-'.$key] = array(
'#type' => 'item',
'#title' => $domainname['sitename'],
'#size' => 60,
'#maxlength' => 128,
);
$form['ressortswitch'][$key]['domainshort-'.$key] = array(
'#type' => 'textfield',
'#default_value' => $domainname['sitename'],
);
$form['ressortswitch'][$key]['weight-'.$key] = array(
'#type' => 'textfield',
'#default_value' => !empty($domainname['domain_weight']) ? $domainname['domain_weight'] : '0',
'#size' => 3,
'#attributes' => array('class' => array('item-row-weight')),
);
$count++;
}
$form['ressortswitch']['count'] = array(
'#type' => 'hidden',
'#value' => $count,
);
$form['ressortswitch']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Settings'),
);
return $form;
}
/**
* Theme callback for the he_ministerienschalter_admin_form
*/
function theme_he_ministerienschalter_admin_form($variables) {
$element = $variables['form'];
drupal_add_tabledrag('ressortswitch_table', 'order', 'sibling', 'item-row-weight');
$header = array(
t('Domainname'),
t('Domainshort'),
t('Weight')
);
$element_items = array();
foreach($element['ressortswitch'] as $id => $record) {
if(is_int($id)) {
$element_items[] = $record;
}
}
$rows = array();
foreach ($element_items as $id => $item) {
$domainNAME[$id] = $item['domainname-'.$id];
$domainSHORT[$id] = $item['domainshort-'.$id];
$domainWEIGHT[$id] = $item['weight-'.$id];
$rows[] = array(
'data' => array(
drupal_render($domainNAME[$id]),
drupal_render($domainSHORT[$id]),
drupal_render($domainWEIGHT[$id]),
),
'class' => array('draggable'),
);
}
$output = theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => 'ressortswitch_table'),
));
$output .= drupal_render($element['ressortswitch']['submit']);
return $output;
}
/**
* Implements hook_form_submit
*/
function he_ministerienschalter_admin_form_submit($form, &$form_state, $item) {
db_delete('he_ministerienschalter')
->execute();
$count_domains = $form_state['values']['ressortswitch']['count'];
$count = 0;
// dpm($form_state);
dpm($form_state);
while($count < $count_domains) {
db_insert('he_ministerienschalter')
->fields(array(
'domain_id' => $form_state['values']['ressortswitch'][$count]['domainID-'.$count],
'domain_short' => $form_state['values']['ressortswitch'][$count]['domainshort-'.$count],
'domain_weight' => $form_state['values']['ressortswitch'][$count]['weight-'.$count]
))
->execute();
$count++;
}
drupal_set_message('Eingabe gespeichert');
}
Any idea how to solve that?
I Updated my theme function like this and now it works like a charm :-)
$output .= drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);

Resources