I have a custom post type that I'm searching through with a custom query. I want to output a message if there's too many results (that works fine). But the problem I have is when you first goto the page and no search has been performed, I don't want that message to appear. How can I stop it appearing when no search has been performed?
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 5,
'post_type' => 'researchdatabase',
'post_status' => 'publish',
'paged' => $paged
);
if($searchTerm != "") {
$args['s'] = $searchTerm;
}
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
$counter = 1; ?>
<p>
<b><?php echo $the_query->post_count; ?> research items</b>
<?php if($the_query->post_count > 20) { ?>
<br /><span class="research-alert"><b>Refine your search criteria to see fewer results.</b></span>
<?php } ?>
</p>
<hr />
<br />
<?php while ($the_query->have_posts()) { $the_query->the_post(); ?>
<?php // output results ?>
<?php $counter++;
} // end while
// reset post data
wp_reset_postdata();
} else {
echo 'No results';
} // end if
?>
Just change the condition:
<?php if($the_query->post_count > 20) { ?>
With:
<?php if($the_query->post_count > 20 && is_search()) { ?>
is_search() return true if any search term is sent for the current WP_Query.
"no search has been performed" equals "no search term in the query", why don't you just check search term first?
if(!empty($searchTerm)) {
$args = array(
's' => $searchTerm
'posts_per_page' => 5,
'post_type' => 'researchdatabase',
'post_status' => 'publish',
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1
);
$the_query = new WP_Query($args);
// Your code.
}
BTW: if you want to display total count of search results, you should use $the_query->found_posts not $the_query->post_count it only count posts on first page.
Related
I'm using an AJAX search to pull 3 custom post types from wordpress (post, guides, advice). As you can see in my if while loop, the results show which results are which but I'm trying to section them out individually so it will show something like this:
section 1
blog posts
section 2
guides
The problem seems to be that I need to edit the if while loop because adding anything inside that loop will just cause it to be in that loop. Does anyone know the best way to modify the if while loop to achieve this?
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
)
);
global $post;
if( $the_query->have_posts()) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<?php $type = get_post_type();
$term = $_POST['keyword'];
$i++;
$total = $the_query->found_posts;
?>
<span class="search-title">
<?php if ($type == 'post'):?>
<?php echo 'Article: ';?>
<?php elseif($type == 'guide' ):?>
<?php echo 'Guide: ';?>
<?php elseif($type == 'advice' ):?>
<?php echo 'advice: ';?>
<?php endif;?>
<?php the_title();?><br>
</span>
<?php endwhile; ?>
<?php
wp_reset_postdata();
else:
echo '<h3>No Results Found</h3>';
endif;
die();
}
If I were you, I'd probably just do three separate queries. They seem simple enough that it shouldn't cause any issues at all. Otherwise you have to either sort through or reorder the WP_Query results somehow.
If you're set on the single query, however - since these are such short HTML strings, I'd probably just control the output with the Output Buffer.
Basically you can create an associative array, and add the HTML strings to the appropriate keys. You could get a bit more elaborate and have them be nested arrays, but since your output is so light, you can probably get by just by having HTML strings as the values for the keys.
I took the liberty of cleaning up your code a little bit and removing some unused variables, etc.
function data_fetch(){
// Build the Query Arguments
$the_query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
// Do we have posts?
if( $the_query->have_posts()){
// We do. Start an array that will fill with HTML from the output buffer
$output = array(
'post' => '',
'guides' => '',
'advice' => '',
);
// Loop through the posts
while( $the_query->have_posts() ){
$the_query->the_post();
ob_start(); // Turn on the output buffer
$type = get_post_type(); ?>
<span class="search-title">
<?php echo ($type == 'post') ? 'Article: ' : ucwords($type).': '; // Output "Articles: " for posts, or just capitalize the other post type names ?>
<?php the_title();?><br>
</span>
<?php $output[$type] .= ob_get_clean(); // Add the HTML output from the buffer to our array
}
wp_reset_postdata();
// Here we have an array with 3 HTML strings that we can output wherever
echo $output['post'];
echo $output['guides'];
echo $output['advice'];
} else {
echo '<h3>No Results Found</h3>';
}
}
if I understood your concern, I propose to divide your code by creating a generic class.
and you make calls to the different Post Type :
class Custom_Query {
public $post_type;
public $key_word;
public function __construct($post_type, $keyword) {
$this->post_type = $post_type;
$this->key_word = $keyword;
}
public function getResult() {
echo '<h1>Article : ' . $this->post_type . '</h1>';
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr($this->key_word),
'post_type' => array($this->post_type),
'post_status' => 'publish'
)
);
if ($the_query->have_posts()):
while ($the_query->have_posts()): $the_query->the_post();
echo '<span class="search-title">';
echo '' . the_title() . '<br>';
echo '</span>';
endwhile;
else:
echo '<h3>No Results Found</h3>';
endif;
wp_reset_postdata();
}
}
global $post;
$type = get_post_type();
$term = $_POST['keyword'];
$article = new Custom_Query($type, $term);
$article->getResult();
You were on the right track initially. You can just use the standard post objects to check for post type. You can adjust to fit your needs, but try something like this:
<?php
query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
if ($query->have_posts()) {
while ($query->have_posts()):
$query->the_post();
?>
<div class="posts">
<?php
if ($query->post->post_type === 'post') {
// add your content
} else if ($query->post->post_type === 'guides' {
// add your content
} else {
// add your content
}
?>
</div>
<?php endwhile;
} else {
// no posts found
}
I hace 2 sections on my site: first is for popular posts (based on views) and the second section is for the recent posts.
If the post is already in the popular posts section, I don't want it to be displayed in the "Recent posts" section. Below is my code. In the first loop I've created an array to store all post ID's which are in that section. In the second loop I check if the id is in that array (may be not the best solution).
For some reason it only works with the first duplicate, even though $cont becomes true required amount of times(I checked with echo). So what gives?
<?php
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
$counter=0;
$post_ids = array();
while ( $popularpost->have_posts() ) : $popularpost->the_post();
$postID = get_the_ID();
$post_ids[$counter] = $postID;
?>
<?php the_title(); ?>
<?php $counter++; ?>
<?php endwhile; ?>
<?php $myquery = new WP_Query('posts_per_page=6');
while ( $myquery->have_posts() ) : $myquery->the_post(); ?>
<?php $post_id = get_the_ID(); ?>
<?php $post_ids_length = count($post_ids); ?>
<?php for ($i=0; $i < $post_ids_length; $i++) {
if ($post_id == $post_ids[$i]) {
$cont = "true";
} else {
$cont = "false";
}
} ?>
<?php if ($cont == "true") {
continue;
} ?>
<?php the_title(); ?>
<?php endwhile; ?>
Update your Second Query as below:
$args2 = array('post__not_in' => $post_ids,'posts_per_page' => 6 );
$myquery = new WP_query($args2);
And then just iterate over the result using the While loop.
Hi i need to display list of post by post type and category, i have code like this, but it isint working properly:
<?php $catquery = new WP_Query( 'posts_per_page=999&post_type=posttypename&cat=categoryname' ); while($catquery->have_posts()) : $catquery->the_post(); $i = 1; ?>
This code displaying post from "posttypename", but it displays all post from that custom post type, but i need to displaying post from only "categoryname"
The whole code looks like this:
<?php $catquery = new WP_Query( 'posts_per_page=999&post_type=posttypename%cat=categoryname' ); while($catquery->have_posts()) : $catquery->the_post(); $i = 1; ?> <?php if($i == 1) : ?> <div class="">content of the post</div> <?php endif; ?> <?php $i++; endwhile; ?>
Use WP_Query like this :
$catquery = new WP_Query(array(
'post_type' => 'posttypename',
'posts_per_page' => -1,
'category_name' => 'categoryname',
// 'cat' => cat ID here
));
if( $catquery->have_posts() ){
while($catquery->have_posts()){
$catquery->the_post();
// your stuff
}
wp_reset_postdata();
}
Try below code
<?php
$catquery = new WP_Query(array(
'post_type' => 'posttypename',
'posts_per_page' => -1,
'category_name' => 'categoryname'
));
if( $catquery->have_posts() ){
$i = 1;
while($catquery->have_posts()){
if($i == 1){ ?>
<div class="">content of the post</div>
<?php } ?>
$i++;
}
wp_reset_postdata();
}
?>
Im new with custom post type - taxonomy wordpress.
I created a template page to show list of products in custome taxonomy but i dont know how exactly to do.
Example:
Category
SubCategory
Product A in Category and B in Category>SubCategory.I want to click Category will show only Product A and if i click SubCat will show only Product B.
Tks for helping!
<?php
$wp_query->get_queried_object_id();
$args = array(
'post_type' => array('san-pham'),
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => 100,
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
);
$eq_query = new WP_Query( $args );
$wp_query->get_queried_object_id();
$offset = 0;
$count = 0;
$eq_total_posts = $eq_query->found_posts - $offset;
if ($eq_query->have_posts()) : // The Loop
$eq_count = $args['paged'] * $args['posts_per_page'] - $args['posts_per_page']; // Count items
?>
<?php
while ($eq_query->have_posts()): $eq_query->the_post();
$eq_count++;
$count++;
?>
<?php
if ($count == 4) {
$p4 = 'four';
$count = 0;
} else { $p4 = ''; }
?>
<div <?php post_class($p4); ?> id="pro-cat">
....
</div>
<?php endwhile; wp_reset_query(); ?>
<?php endif; ?>
I was hoping someone could help me with this problem.
I'm trying to make a loop in wordpress with two different post types ('product' and 'outfits')
The code below is working fine, this outputs a list of the two post types ordered by newest to older.
$loop = new WP_Query( array(
'post_type' => array( 'product', 'outfits' ),
'posts_per_page' => 15
) );
$counter = 0;
?>
<?php if ( $loop->have_posts() ) { while ( $loop->have_posts() ) { $loop->the_post();
$counter++; ?>
<?php $loop->is_home = false; ?>
<?php
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large');
$titulo = get_the_title();
$content = apply_filters ('the_content', $post->post_content); ?>
<div class="caja-<?php echo $counter; ?>">
<?php if ( $post->post_type == "product" ) {
//some stuff
<?php } else {
//some stuff
} ?>
</div>
<?php } } wp_reset_postdata();
What I would like to do is to insert a product post type after X number of outfits.
I was trying to merge a similar solution I've found in other question with no luck. I'm not a php expert so any help is appreciated
<?php
$args = array('post_type'=>'post', 'posts_per_page'=>9, 'category_name'=>'news');
$posts = get_posts($args);
$args = array('post_type'=>'testimonials', 'posts_per_page'=>3);
$testimonials = get_posts($args);
// see how many of the regular posts you got back //
$post_count = count($posts);
// see how many testimonials you got back //
$testimonial_count = count($testimonials);
// add them up to get the total result count //
$total_count = $post_count + $testimonial_count;
// Loop through the total number of results //
for($i = 1; $i <= $total_count; $i++){
// assuming you want to show one testimonial every third post //
if($i % 3 == 0){
// this means you're on the a third post, show a testimonial //
setup_postdata($testimonials[$i]);
}
else{
/** show a regular post */
setup_postdata($posts[$i]);
}
/** and now handle the output */
?><h1><?php the_title();?></h1><?php
} ?>
$x = 3;
$products = get_posts(array(
'post_type' => 'product',
'posts_per_page' => -1
));
$outfits = get_posts(array(
'post_type' => 'outfit',
'posts_per_page' => -1
));
foreach ($outfits as $num => $outfit) {
if ( ($num+1) % $x == 0) {
if (isset($products[($num+1)/$x - 1])) {
array_splice( $outfits, $num, 0, array($products[($num+1)/$x - 1]) );
}
}
}
foreach ($outfits as $outfit) {
$posts_id[] = $outfit->ID;
}
$query = new wp_query(array(
'post_type' => array('outfit', 'product'),
'post__in' => $posts_id,
'posts_per_page' => 15,
'orderby' => 'post__in'
));