WordPress running two queries together - php

This is an events website that handles the location of each event relative to the users location and displays the distance in search results.
I'm using the WP GeoQuery extension to allow me to query based on distance. However, it doesn't work well with things like tax_query. So, I'm wondering if there's a way of running the WP_GeoQuery to query for events within a certain distance, then run the result of that through the normal Wp_Query to get it to filter for the correct taxonomies and other arguments?
Here's the Geo Query:
$url = "http://freegeoip.net/json/". $_SERVER['REMOTE_ADDR'] .'';
$geo = json_decode(file_get_contents($url), true);
$geo_query = new WP_GeoQuery(array(
// location stuff
'latitude' => $geo[latitude], // User's Latitude (optional)
'longitude' => $geo[longitude], // User's Longitude (optional)
// radius breaks the query if using tax_query too
'radius' => 25 // Radius to select for in miles (optional)
));
And here's the normal WP_Query:
// add query for title
function title_filter( $where, &$wp_query ) {
global $wpdb;
if ( $search_term = $wp_query->get( 'title_like' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
}
return $where;
}
add_filter( 'posts_where', 'title_filter', 10, 2 );
// dates to and from
function date_from( $from ) {
$from = str_replace("meta_key = 'date_%_start-date'", "meta_key LIKE 'date_%_start-date'", $from);
return $from;
}
add_filter('posts_where', 'date_from');
function date_to( $to ) {
$to = str_replace("mt1.meta_key = 'date_%_end-date'", "mt1.meta_key LIKE 'date_%_end-date'", $to);
return $to;
}
add_filter('posts_where', 'date_to');
// convert date to yyyymmdd
$date1 = str_replace('/', '-', $_POST['when']);
$when = date("Ymd", strtotime($date1));
$date2 = str_replace('/', '-', $_POST['when-2']);
$when2 = date("Ymd", strtotime($date2));
?>
<h1>Search</h1>
<div class="events">
<?php $args = array(
// general
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => 2,
'paged' => $paged,
// what input
'title_like' => $_POST['what'],
// category filter
'tax_query' => array(
array(
'taxonomy' => 'main-cat',
'field' => 'slug',
'terms' => $_POST['main-cat']
)
),
// date filter
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_%_start-date',
'value' => $when,
'compare' => '>=',
'type' => 'DATE'
),
array (
'key' => 'date_%_end-date',
'value' => $when2,
'compare' => '<=',
'type' => 'DATE'
)
),
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );
$wp_query->query('posts_per_page=2&post_type=event'.'&paged='.$paged);
When used individually they work fine. But I'm not sure how I can run one of them, then use the result to put through the other query. Is this even possible?

Related

How do I query related product post title instead of whole post object array the WordPress query?

How do I query related product post title instead of the whole post object array in my WordPress query below?
$product_search = $_GET['s'];
$related_product = get_field( 'related_products' ); // This is an ACF relationship field so I can link products to articles and display teh related article in search.php from the product page
$knowledge_args = array(
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
'key' => $related_product, // How do I query related product post title instead of whole post object array?
'value' => $product_search,
'compare' => 'LIKE'
)
);
$relatedProductArticles = new WP_Query($knowledge_args);
You could do that by manipulating the sql "WHERE" clause.
Create a custom function that does the filtering for you!
Add the argument that our custom function is looking for
Add the filter right before the custom WP_Query
Remove the filter after WP_Query
So you could write a the custom function in your functions.php like so:
function related_products_title_filter($where, $wp_query)
{
global $wpdb;
if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
}
return $where;
}
Add a custom argument to the arguments:
$knowledge_args = array(
'my_custom_search_filter_title' => $product_search, // This is the custom argument that our function is looking for
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $related_product,
'value' => $product_search,
'compare' => 'LIKE'
)
)
);
Add the filter right before the custom WP_Query:
add_filter('posts_where', 'related_products_title_filter', 10, 2);
Remove the filter after WP_Query
remove_filter('posts_where', 'related_products_title_filter', 10, 2);
So your entire code would be something like this:
function related_products_title_filter($where, $wp_query)
{
global $wpdb;
if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
}
return $where;
}
$product_search = sanitize_text_field($_GET['s']);
$related_product = get_field( 'related_products' );
$knowledge_args = array(
'my_custom_search_filter_title' => $product_search,
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $related_product,
'value' => $product_search,
'compare' => 'LIKE'
)
)
);
add_filter('posts_where', 'related_products_title_filter', 10, 2);
$relatedProductArticles = new WP_Query($knowledge_args);
remove_filter('posts_where', 'related_products_title_filter', 10, 2);
Let me know if you were able to get it to work!

How to search by meta and custom taxonomy name - wordpress search?

I am building a ajax search that uses wp_query and I need to be able to filter using custom meta and custom taxonomy names. I've gotten the custom meta part working but cannot get it to filter using the taxonomy names. What I've got so far -
$useCustomJoins = false;
add_action( 'pre_get_posts', function( $q )
{
if( $title = $q->get( '_meta_or_title' ) )
{
add_filter( 'get_meta_sql', function( $sql ) use ( $title )
{
global $wpdb;
// Only run once:
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// Modified WHERE
$sql['where'] = sprintf(
" AND ( %s OR %s ) ",
$wpdb->prepare( "{$wpdb->posts}.post_title like '%%%s%%'", $title),
mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
);
return $sql;
});
}
});
add_filter('posts_join', array('CrownResources', 'filterPostsJoin'), 10, 2);
add_filter('posts_where', array('CrownResources', 'filterPostsWhere'), 10, 2);
add_filter('posts_groupby', array('CrownResources', 'filterPostsGroupby'), 10, 2);
public static function filterPostsJoin($join, $query) {
global $wpdb, $useCustomJoins;
if($useCustomJoins || (is_main_query() && is_search())) {
$join .= "
LEFT JOIN
(
{$wpdb->term_relationships}
INNER JOIN
{$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
INNER JOIN
{$wpdb->terms} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
)
ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id ";
}
return $join;
}
public static function filterPostsWhere($where, $query) {
global $wpdb, $useCustomJoins;
if($useCustomJoins || (is_main_query() && is_search())) {
$userWhere = self::getUserPostsWhere();
$queryS = !empty(get_query_var('s')) ? get_query_var('s') : get_query_var('_meta_or_title');
$where .= " OR (
{$wpdb->term_taxonomy}.taxonomy IN('resource_pregnancy_taxonomy', 'resource_counseling_taxonomy', 'resource_classes_taxonomy', 'resource_supplies_taxonomy', 'resource_clothing_taxonomy', 'resource_food_taxonomy', 'resource_housing_taxonomy', 'resource_medical_taxonomy', 'resource_substance_taxonomy', 'adoption_taxonomy', 'employment_taxonomy')
AND
{$wpdb->terms}.name LIKE '%".esc_sql($queryS)."%'
{$userWhere}
)";
}
return $where;
}
protected static function getUserPostsWhere() {
global $wpdb;
$userId = get_current_user_id();
$sql = '';
$status = array("'publish'");
if(0 !== $userId) {
$status[] = "'private'";
$sql .= " AND {$wpdb->posts}.post_author = ".absint($userId);
}
$sql .= " AND {$wpdb->posts}.post_status IN( ".implode(',', $status)." ) ";
return $sql;
}
public static function filterPostsGroupby($groupby, $query) {
global $wpdb, $useCustomJoins;
if($useCustomJoins || (is_main_query() && is_search())) {
$groupby = "{$wpdb->posts}.ID";
}
return $groupby;
}
usage:
global $post, $useCustomJoins;
$original_post = $post;
// query for resource
$queryArgs = array(
'post_type' => 'resource',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'post_status' => 'publish'
);
//if taxonomies
if (!empty($atts['taxonomies'])){
$queryArgs['tax_query'] = array();
foreach ($atts['taxonomies'] as $tax){
$queryArgs['tax_query'][] = array(
'taxonomy' => $tax['name'],
'field' => 'term_id',
'terms' => $tax['terms'],
'operator' => 'AND',
);
}
}
// filter by meta as well as title
$meta_query = array();
$meta_query[] = array(
'key' => 'resource_description',
'value' => $atts['search'],
'compare' => 'LIKE'
);
$meta_query[] = array(
'key' => 'resource_address',
'value' => $atts['search'],
'compare' => 'LIKE'
);
$meta_query[] = array(
'key' => 'resource_date_time',
'value' => $atts['search'],
'compare' => 'LIKE'
);
$meta_query[] = array(
'key' => 'resource_phone',
'value' => $atts['search'],
'compare' => 'LIKE'
);
$meta_query[] = array(
'key' => 'resource_email',
'value' => $atts['search'],
'compare' => 'LIKE'
);
$meta_query[] = array(
'key' => 'resource_website',
'value' => $atts['search'],
'compare' => 'LIKE'
);
//if there is more than one meta query 'or' then
if(count($meta_query) > 1) {
$meta_query['relation'] = 'OR';
}
//if there's a search
if (!empty($atts['search'])){
// $queryArgs['s'] = $atts['search'];
$queryArgs['_meta_or_title'] = $atts['search']; //not using 's' anymore
$queryArgs['meta_query'] = $meta_query;
$useCustomJoins = true;
}
$resourceQuery = new \WP_Query($queryArgs);
$useCustomJoins = false;
Any idea on how to get them working together? I can get the meta filter to search properly but once I add the taxonomy it still filters but not correctly.

Wordpress search and Filter API for IOS and Android

I am working on a project to apply filters on wordpress post...I have created JSON Output and Now I need to apply 5 filters that are as follows..
1. All
2. Today
3. WeekEnd
4. Next Seven Days
5. Date wise
Flow of the whole process...GEt Posts data in JSON--> Fetch This Data --> Create Filters---> User can Then Search as well as filter Data Further with normal wordpress functions....But I am not able to work out for fetching out posts by applying the Next Seven days filter and weekEnd..as the issue seems to be at my way of fetching the posts...What I am doing for now is
Code for Next Seven Days or last seven days...
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
//require_once("config.php" );
require_once("incformfunctions.php");
if($_SERVER['REQUEST_METHOD'] == "GET"){
$numberposts = isset($_REQUEST['numberposts']) ? $_REQUEST['numberposts'] : "-1";
$posttype = isset($_REQUEST['posttype']) ? $_REQUEST['posttype'] : "";
$securitycode = $_REQUEST['securitycode'];
$mode = $_REQUEST['mode']? $_REQUEST['mode'] : "ALL";
$taxonomy='art_categories';
if($securitycode == $secret)
{
$category_data=array();
if($mode=='recommended') //to get recommended post of posttype category
{
$args= array(
'numberposts' => 100,
'category' => 0,
'orderby' => 'date',
'order' => 'DESC',
'include' => array(),
'exclude' => array(),
'meta_key' => '',
'meta_value' =>'',
'post_type' => 'events', //post name
'suppress_filters' => true,
'date_query' => array(
array(
'key' => 'event_start_date', //custom name start date
'after' => '1 week ago'
),
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_editors_choice', //custom name event editor
'value' => true
),
'relation' => 'AND',
array(
'key' => 'event_recommended', //custom name event recommended
'value' => true
),
),
);
}
$myposts = get_posts( $args); // get all value in array
if($myposts) {
foreach ( $myposts as $post ) : setup_postdata( $post ); //and using foreach loop show all post type field
$image= get_the_post_thumbnail_url();
$featured_image =wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
$start_date= get_post_meta($post->ID,'event_start_date',true);
$start_date=date('F j, Y', strtotime($start_date));
$end_date = get_field('event_end_date', $post->ID, false);
$end_date=date('F j, Y', strtotime($end_date));
$event_type = get_field('event_type', $post->ID, true);
$event_venue = get_field('event_venue', $post->ID, true);
$event_venue_address = get_field('event_venue_address', $post->ID, true);
$latitude = get_field('event_venue_latitute', $post->ID, true);
$longitude = get_field('event_venue_longitude', $post->ID, true);
$description_long = get_field('event_description_long', $post->ID, true);
$description_short = get_field('event_description_short', $post->ID,
true);
$gallery_address = get_field('gallery_address', $post->ID,
true);
if($gallery_address==false)
{
$gallery_address="";
}
$event_gallery = get_post_meta($post->ID,'gallery_address', true);
$venue_address= get_field('venue_address',$event_gallery,true);
$venue_postcode= get_field('venue_postcode',$event_gallery,true);
$venue_city= get_field('venue_city',$event_gallery,true);
$venue_location= get_field('venue_location',$event_gallery,true);
if($venue_location==false)
{
$venue_location="";
}
$venue=get_post_custom($post->ID);
$category=get_the_category($post->ID); //category
$excerpt=get_the_excerpt( $post );
$posttypes=get_post_type( $post );
$category_data[] = array('id' => get_the_ID (),'title' => get_the_title(),'excerpt' =>$excerpt,'featured_image' =>$featured_image,'image' =>$image,'event_type' =>$event_type,'event_venue' =>$event_venue,'event_venue_address' =>$event_venue_address,'event_latitude' =>$latitude,'event_longitude' =>$longitude,'start_date' =>$start_date,'end_date' =>$end_date,'posttypes' =>$posttypes,'tags'=>$tags,'description_long'=>$description_long,'description_short'=>$description_short,'venue'=>$event_gallery,'gallery_address'=>$gallery_address,'venue_address'=>$venue_address,'venue_postcode'=>$venue_postcode,'venue_city'=>$venue_city,'venue_location'=>$venue_location); // getting in all post array formate
wp_reset_postdata();
endforeach;
$data = $category_data;
$errcode=100;
$errstr='success';
}
else {
$errcode=-1;
$errstr='Post not found please check again..';
}
}
//for securitycheck
if ($securitycode !=$secret or $securitycode=='')
{
$errstr="unauthorise access";
}//end
}
else{
$errcode=-2;
$errstr='Request method not accepted';
}
#mysql_close($conn);
/ Output header /
#header('Content-type: application/json');
echo json_encode(array('errcode'=>$errcode,'errstr'=>$errstr,'data'=>$data)); // json create
die();
Any Help on what I am doing wrong??

Pass multiple arguments to WP_Query

I'm clearly not doing this right. Any help would be greatly appreciated. Essentially i am pulling nearby zip codes and city names to a search that is being done. i then want to use WP_Query to pull the WordPress post types matching those zip codes and city names. I'm not super familiar with WordPress, so it is highly likely i'm way off base on how to do this:
$url = "http://www.zipcodeapi.com/rest/OeAp3k78myEhBy0oqSlQSlUWOt6N7TjW8Tlbdtkz1YRCwS1WKmNDIHzwbFjizCeI/radius.json/" . $searchbox . "/100/km";
$response = file_get_contents($url);
$json = json_decode($response);
$post_type = 'location';
$citysearcharray = array();
$zipsearcharray = array();
$searcharray = array();
foreach($json->zip_codes as $nearbyzip)
{
$citysearcharray[] = array(
'key' => 'city',
'value' => $nearbyzip->city,
'compare' => '='
);
$zipsearcharray[] = array(
'key' => 'zip_code',
'value' => $nearbyzip->zip_code,
'compare' => '='
);
}
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'caller_get_posts'=> 1,
'posts_per_page' => 10,
'meta_query' => array(
'relation' => 'OR',
$citysearcharray,
$zipsearcharray));
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$count=0;
echo '<ul class="location">';
while ($my_query->have_posts()) : $my_query->the_post();
...
Amy i putting the $args together correctly?
TIA
In your foreach, instead of adding new full values to your arrays
$zipsearcharray
and
$citysearcharray
have the value key as an array so:
'value' => array(array of cities)
then change
compare => 'IN'

Get All WP Posts older than 15 minutes

I would like to filter the WP_Query to retrive all woocommerce order (post_type = shop_order) with particular status that are older than 15 minutes.
I.e. All posts that have been last modified on or before (now - 15 minutes ) // Hope I'm clear.
Below What I've tried
function filter_where($where = '') {
//posts in the last 15 minutes
$where .= " AND post_modified > '" . date('Y-m-d', strtotime('INTERVAL 15 MINUTE')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
$args = array(
'post_type' => 'shop_order',
'post_status' => 'publish',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => array('completed')
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
print_r("<pre>");
print_r($order);
print_r("</pre>");
endwhile;
However that returns all record, Seems like have to modify the $where query, how can i achieve that ?
Do you need to filter the posts_where? Can't you just use date query parameters? In your case, specifically before.
$args = array(
'date_query' => array(
array(
'before' => '15 minutes ago'
'inclusive' => true,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
I can't test this right now, so can't verify if it would work. If you are modifying an archive then you should definitely adjust the query via pre_get_posts in lieu of creating new query.
try this change date('Y-m-d', strtotime('INTERVAL 15 MINUTE')) to date('Y-m-d H:i:s', strtotime('-15 minutes'))
function filter_where($where = ''){
//posts in the last 15 minutes
$where .= " AND post_modified > '" . date('Y-m-d H:i:s', strtotime('-15 minutes')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');

Categories