Manually build WP_Query


I’m trying to manually build a query in ‘loop.php’ that outputs a list of 3 posts from a custom post type above the results automatically given when doing a search in WordPress.

As such, I’ve got the following code that displays these results as I intended:

// The Query
$query1 = new WP_Query( array( 'post_type' => 'sdm_downloads', 'posts_per_page' => 3) );

if ( $query1->have_posts() ) :
    echo '<div style="background-color:#fffced; padding:10px;margin-bottom:20px;">';
    echo '<h3>Selected relevant items from our Briefings library:</h3>';
    // The Loop
    while ( $query1->have_posts() ) {
    <article class="article-archive" id="post-<?php the_ID(); ?>">

                <p><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
                <!--<p class="entry-meta">Posted <strong><?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?></strong></p>-->
echo '</div>';

This is great, except that it just pulls out the three most recent posts from this post type. So, I figured I’d need to manually add in the search terms as follows:

$query1 = new WP_Query( array( 'post_type' => 'sdm_downloads', 'posts_per_page' => 3, 's' => $s) );

However this shows nothing at all. Likewise if I replace the s variable with a string, I still get no posts returned. I’ve even removed all arguments except for the string and still get no results eg:

$query1 = new WP_Query( array( 's' => 'awards') );

Any ideas, as to why this is happening &/or how it can be fixed?


If I do a dump of the query without specifying the ‘s’ argument I get the following

string(226) "SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'sdm_downloads' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 3"

Whereas if I add an ‘s’ argument to the WP_Query, I get the following dump:

string(32) "SELECT * FROM wp_posts WHERE 1=2" 

It appears that this behaviour only occurs when I have the Relevanssi search plugin enabled. I guess I’ll go ask over at the makers website, to see if they can shed any light on why this is happening.

In the meantime if anyone has any suggestions on how to deal with this, I’d be happy to hear them.

, , Phill Healey 6 years 2015-10-19T09:07:14-05:00 0 Answers 76 views 0

Leave an answer