Custom WP_Query for search - wordpress

I'm trying to make a custom WP_Query for a search results page.
With the following code, the page always displayed all posts regardless:
<?php
$args = array(
'posts_per_page' => '-1',
);
$query = new WP_Query( $args );
?>
So I've added the search Query to the $args, but this always returns no results - where is this going wrong?
<?php
$search_query = get_search_query();
echo $search_query;
$args = array(
'posts_per_page' => '-1',
's' => $search_query
);
$query = new WP_Query( $args );
?>

1) You can use the templatesearch.php and searchform.php as your starting points. Creating a Search Page Codex
2) As far as the custom query goes, you can use pre_get_posts hook to test if you're on a search page, then you get $_GET your values, edit your query accordingly. Action Reference - pre_get_posts
There are tons of tutorials online and questions on this exchange to help you out. Some are Simple and others are more Complex. You'll have to do some real research to accomplish this. Hope it helps!

I have solved this using pre_get_posts - I'm still intrigued as to why using the WP_Query method doesn't work, but here's what I'm now using:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('posts_per_page', '-1');
}
}
}
add_action('pre_get_posts','search_filter');

Related

WP_query returning all posts instead of custom post type

I'm working on a WP site and I'm having a strange problem with this WordPress query that is supposed to return the posts of custom post type osku_infopost ONLY. But instead I get ALL posts that are on the site (and pages, being of course of post_type page).
The strange part: This ONLY happens when one goes to the home URL (mysite.com). If I visit another page on the site (i.e. mysite.com/apage) the query delivers the expected results.
<?php
// fetch all infoposts in a query
$args = array(
'post_type' => 'osku_infopost',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1,
);
$infopost_query = new WP_Query( $args ); ?>
<div class="infoposts-container">
<ul id="infoposts">
<?php while ( $infopost_query->have_posts() ) : $infopost_query->the_post(); ?>
<li class="infopost-item">
<?php echo get_the_title($infopost_query->post->ID); ?>
<?php echo get_the_content($infopost_query->post->ID); ?>
</li>
<?php endwhile; ?>
</ul>
</div>
Something seems to be injecting the query but I can't understand where or how.
I'm probably missing something very obvious here. Any ideas?
I found the Issue: I had a filter in my functions.php that I originally used because I was using the main query to retreive multiple pages (post_type page) at once.
function my_get_posts( $query ) {
if ( is_home() && false == $query->query_vars['suppress_filters'] )
$query->set( 'post_type', array( 'post', 'page') );
return $query;
}
add_filter( 'pre_get_posts', 'my_get_posts' );
When this filter is active the post_type field in the array passed to WP_query (see code in question) seems to be ignored and the query automatically returns all posts of post_type post and of post_type page as stated in the array passed to $query->set(). Thanks to everyone who looked into it!

How to hook in a custom query to the loop with Wordpress

I want to create a loop and query posts by their author role. And display the results of a search term based on the authors role.
I've tried creating a function to alter the query's where clause:
$ids = get_users(
array(
'role' => 'administrator' ,
'fields' => 'ID'
)
);
$query = new WP_Query(
array(
'author__in' => $ids,
)
);
// If the query has data
if($query->have_posts() ) :
// Post loop
while ($query->have_posts() ) :
// Setup post data
$query->the_post();
?>
<!-- Do HTML markup and template tags here, eg. the_content(), the_title() etc.. -->
<h1>You're a post from administrator - <?php the_title(); ?></h1>
<?php get_template_part( 'template-parts/content', 'search' ); ?>
<?php
endwhile;
// End "If the query has data"
endif;
I'm trying to add a WP_Query to the loop but this is where I get stuck with the results not getting filtered by role so I'm fairly certain I must be implementing this wrong - this is the first time I've tried to do something like this so sorry if it's a dump question but I can't find an answer to my question so if anyone can point me in the right direction that would be amazing!
Any advice welcome, thank you!
You can try the posts_where
hook.
UPDATE:
Why don't you use the default WP_Query author arg instead hook.
You query will be :
$ids = get_users(
array(
'role' => 'administrator' ,
'fields' => 'ID'
)
);
$query = new WP_Query(
array(
'author__in' => $ids,
)
);

$wp_query and WP_QUERY - same arguments, different results

I spend this whole day trying to figure out a problem with a combination of a custom query and custom post types. This is my last resort...
The setting
I wrote a plugin that introduces some custom post types to my WordPress. To display them in the main query I hooked them into the query like this:
function add_cpt_to_query( $query ) {
*some code...*
// add custom post types to query
if ( !( is_admin() || is_post_type_archive() || is_page() ) && $query->is_main_query() ) {
$query->set('post_type', array_merge( array('post'), $cpt ) );
}
}
add_action('pre_get_posts','add_cpt_to_query');
In my theme on the other hand I setup ajax pagination like this:
function setup_pagination() {
global $wp_query;
$max_pages = $wp_query->max_num_pages;
$current_page = ( $wp_query->paged > 1 ) ? $wp_query->paged : 1;
$ajaxurl = admin_url( 'admin-ajax.php' );
wp_register_script( 'ajax-pagination', get_template_directory_uri() .'/js/dummy.js', array('jquery'), '', true);
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'max_pages' => $max_pages,
'current_page' => $current_page,
'ajaxurl' => $ajaxurl,
'query_vars' => $wp_query->query_vars
));
wp_enqueue_script( 'ajax-pagination' );
}
add_action( 'wp_enqueue_scripts', 'setup_pagination' );
function pagination() {
$query = $_POST['query_vars'];
$query['paged'] = $_POST['next_page'];
/*
$query = array(
'paged' => 2,
'post_type' => array('post', 'custom_post_type_1', 'custom_post_type_2' )
);
*/
$posts = new WP_Query( $query );
$GLOBALS['wp_query'] = $posts;
// Start the loop.
while ( have_posts() ) : the_post();
?>
*some code...*
<?php endwhile;
die();
}
add_action( 'wp_ajax_nopriv_ajax_pagination', 'pagination' );
add_action( 'wp_ajax_ajax_pagination', 'pagination' );
and the script part:
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
next_page: parseInt(ajaxpagination.current_page) + 1
}
});
The problem
If I pass the query_vars array I get from $wp_query with the altered 'paged' value back to WP_QUERY, it returns the wrong set of posts. It looks like, that WP_QUERY does not account for the cpts in the loop. Though these cpts are mentioned in the 'post_type' of the query_vars array and thereby passed along to the new WP_QUERY.
When I manually set 'post_type' and only pass this argument, it works as intended. The aspect that blows my mind is, that the resulting query_vars used in the ajax call to WP_QUERY are exactly the same, but only when I manually set 'post_type' the pagination works as it should.
I dont know if this was a somewhat understandable explanation, but I'm thankful for every idea that could help me out. Big THX!
Ok... I got it now.
I made a mistake in wp_localize_script(). The query_vars should be a json-string, I on the other hand just passed the array itself. My code above has to be altered in two lines:
function mk_setup_pagination() {
...
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
...
'query_vars' => json_encode($wp_query->query_vars) <- convert to json-string
));
...
}
function mk_pagination() {
$query = json_decode( stripslashes( $_POST['query_vars'] ) , true); <- convert json-string to array
...
Works like a charm now. :)
btw: the code is based on a tutorial by wpmudev.org: Loading WordPress Posts Dynamically With AJAX

Accessing Advanced Custom Fields by Page Name

I am trying to retrieve all advanced custom fields tied to a particular page. This is different than iterating through posts, I am familiar with the following:
$posts = get_posts(array(
'post_type' => 'post_name',
'meta_key' => 'color',
'meta_value' => 'red'
));
However this method is specific to posts and does not allow me to retrieve all ACF by page name.
I appreciate any suggestions on how to accomplish this.
The are too ways to do this that come to mind...
1. Using the Loop
Using WP_Query you can do something like this...
<?php
// WP_Query arguments
$args = array (
'pagename' => 'homepage',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_field( "field_name" );
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
In place of the 'homepage' in 'pagename' => 'homepage', you want to put the page slug of your page. And of course in place of the_field( "text_field" ); you want to add your fields/content.
You can also query by Page ID and some other parameters. You can find all other parameters that you can use here:
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
2. Adding second parameter to the_field() function
More simple way, without custom loop, is just to use ACF's built-in the_field() function with the $post->ID parameter added as a second parameter.
<?php the_field('field_name', 123);
This might be the way to go since you want to show the content of only one page, and therefore don't really need to loop.
Reference: http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/
You can use ACF's get_fields() function -
<?php $fields = get_fields( $post->ID ); ?>
You could then loop through them or simply print the array for testing.
http://www.advancedcustomfields.com/resources/get_fields/

Wordpress function : get_posts

Crazy night! ;P
I'm devoliping a plugin with Wordpress and I'm lost looking for a function.
What I did is,
$args = array("meta_key" => "email", "meta_value" =>$email);
$posts = get_posts($args);
I did that in order to filter custom fields with the same email,
if (count($posts) < 0){ // do something }
The problem is that get_posts didn't work with custom posts,
$args = array('post_type' => 'reserva', "meta_key" => "wpcf-email", "meta_value" =>$email);
I like to find something like get_posts in order to count it.
I think I have a bad solution,: to loop it, but I want to array it.
Any idea?
Thanks,
Best regards,
Use meta_query in your arguments array.
Try this, if you want post related to meta_key and meta_value so please use this
http://codex.wordpress.org/Class_Reference/WP_Meta_Query
thanks a lot, I will check it now,
As I said tonight i did an ugly solution,
I made a loop with a counter in porder to find if a custom fields exist.
Here is the ugly code,
<?php // Find matches in csutom post types
$my_consulta = array(
'post_type' => 'reserva',
'post_status' => 'draft',
'post_key' => 'wpcf-email',
'meta_value' => $email,
);
$wp_query = new WP_Query($my_consulta);
$count = 0;
while ( have_posts() ) : the_post();
$count = $count + 1;
endwhile;
if ($count == 0){
//No matches
} else {
//There is one or more matches
}
?>
Is a good way?
Best regards,
Cristian

Resources