Displaying Number of Found Posts on Results Page in WordPress - php

I want to display the total number of found posts on results page in WordPress. For example "If someone searches for 'cat' it should display count for posts with the term 'cat', Right now I inserted some PHP code but it is displaying the total number of published posts and that's not I want to achieve. Please follow this link: https://bigfunx.com/?s=cats&id=1516&post_type=post
And you will clearly see that there are four articles found for cat and it is displaying 28 as count instead of 4. I hope you are understanding what I am trying to achieve. Looking forward to hearing from you soon. Thank you!
I try to enter the following code:
<?php $args = array(
'post_type' => 'post'
);
$query = new WP_Query($args);
$totalposts = $query->found_posts;
if($totalposts < 2) {
$result = "Meme";
} else {
$result = "Memes";
}
echo $totalposts . " " . $result; ?>
The above code is displaying the total number of published posts and also with singular and plural feature but I know I am missing something to properly displaying the result, Your help will be highly appreciated.

I am not sure where you add that code, but you can try this:
$args = array( 'post_type' => 'post', 's' => isset( $_GET['s'] ) ? $_GET['s'] : '')
Just add the 's' key in you $args variable.
This is not the best solution because you are making additional query on the search page. But given the info you have in your question that should work.
Better solution would be in the page where you display the title (search page) you can try:
global $wp_query; $totalposts = $wp_query->found_posts;

As mentioned in the comments, use th _n() to pluralize your string.
<?php
$args = array(
'post_type' => 'post',
);
$query = new WP_Query( $args );
$totalposts = $query->found_posts;
echo esc_attr( $totalposts . ' ' . _n( 'Meme', 'Memes', $totalposts ) );

Related

Wordpress show multiple post types in loop

I'm creating a Wordpress site were I would like to show "tiles" with content from the site on the front page. These tiles are custom post types from the site like "our services", "consultants", "blog posts" and so on.
I know how to show one custom post type in Wordpress, but the problem is that I need to pull multiple post types in the same loop as I want them to be displayed in a matrix. Another problem is that I need to shuffle all the items in a random order, so that for example not all blogs just show in one place but all objects show after different items in random.
The third problem is that I need to show all items for a certain post type and just the latest for another. For example do I need to show all "our services" tiles, but only a couple of the "blog" tiles.
Is this possible to do, or can you not pull out records in this way using Wordpress?
Thank you for the help!
I suggest reading up on custom wordpress queries https://codex.wordpress.org/Class_Reference/WP_Query
For the first question you just need to specify
'post_type' => array( 'tiles', 'consultants', 'post' )
for the second question
'orderby' => 'rand'
so you will have something like
$args = array(
'post_type' => array( 'tiles', 'consultants', 'post' ),
'orderby' => 'rand'
);
$query = new WP_Query( $args );
For the third question - I'm not sure if it is possible to achieve with one query.
you can customise the things like this ,
$posttypes = array('post_typ1','post_typ2','post_typ3');
$randompost_typs = shuffle($posttypes);
$counter = count($posttypes);
for($i=0; $i<$counter;$i++) {
// suppose you want to show all posts from post_type1 then
if($randompost_typs[$i]=='post_typ1') {
$posts_per_page = -1;
} elseif($randompost_typs[$i]=='post_typ2') { // will work for 2nd post type
$post_per_page = 5; // show 5 posts from this post type
} else {
$post_per_page = 3; // show 3 posts from last post type
}
// here you will use the WP_Query class from wordpress
$args = array(
'post_type' => $posttypes[$i],
'orderby' => 'rand',
'posts_per_page' => $post_per_page
);
$query = new WP_Query( $args );
if($query->have_posts()) : while($query->have_posts()): $query->the_post();
// all the remaining wp loop content for example
the_title();
the_excerpt();
endwhile;
else:
echo 'no posts';
endif;
}
hope this will help, let me know if it has any issue.

Wordpress: Figure out what page number a post would have on the index screen

I can't seem to figure the following out:
In a Wordpress theme I'm developing, 10 excerpts will be displayed at a time on the index screen. Naturally, then, if there are 20 posts the newest 10 posts will be displayed on page 1 and the 10 oldest on page 2 of the index screen.
When viewing any single post I would like to have a function which prints the page number upon which the current post would be found when viewing the index screen.
I've tried doing WP_queries, like:
$args = array(
'date_query' => array(
array(
'after' => get_the_date,
...
$query = new WP_Query( $args );
but with no luck.
Would anybody out there have any suggestions in which direction I should go about for figuring this one out!?! Any help is much obliged!
you could do a query on your page and figure out where your post would be....
$id = get_the_ID(); // set within your loop
$args = array(
'date_query' => array(
array(
'after' => get_the_date,
$query = new WP_Query( $args );
$i=1;
foreach($query as $post=>$key){
if($key->ID == $id) {//not tested have a look at the object to get correct location
$postnumber= $i;
}
$i++;
}
$page= $postnumber / 10;
$pagenumber= round($page, 0, PHP_ROUND_HALF_DOWN);
seems heavy on resources though!
I would probably opt for counting posts newer than the current one.
// This is not tested code, just a wild guess really. Sorry.
global $wpdb;
$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND post_date > %s";
$count = $wpdb->get_var(
$wpdb->prepare(
$query,
get_the_date( /* probably needs a better date format here */ )
)
);
Another option I can think of is to append a GET parameter on your links from your front page, since you get the posts there anyway.
<?php $count++ // in the loop right? ?>
<a href="<?php echo the_permalink();?>?index=<?php echo $count?>"?>
This would of course not work unless everyone uses the frontpage to go to your pages, but then you could count newer posts as a fallback.

Wordpress - Show only posts with specific slug

I'm sure this is going to be a silly question... but here it goes.
I currently have a page that only displays posts of a Custom Post Type (car).
I do this by running a query
$args = array(
'post_type' => 'car');
$query = new WP_Query( $args );
On to the loop...
For this Custom Post Type i have a Custom Taxonomy e.g. Subaru, Honda etc...
I'm just trying to work something else out, but if I wanted to show only posts that are Subaru's, how would I query that?
I guess I want to query the 'slug' (subaru), this code doesn't work, but you can see the route I was heading...
$args = array(
'name' => 'subaru',
'post_type' => 'car');
$query = new WP_Query( $args );
On to the loop...
I know name isn't right. What is the correct term to add to my $args array?
Many thanks
Depends on what your taxonomy is called. In my example its called 'brands':
$args = array(
'post_type' => 'car',
'brand' => 'subaru'
);
$query = new WP_Query( $args );
see http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
What you're trying to do is a taxonomy query. I could tell you how to do that but I think it's important I point out a much bigger mistake first. You shouldn't querying this on a page.
That's what archives are for.
Create a template file called archive-car.php and output there instead. That removes the need to run a custom WP Query.
Then create another file taxonomy-{your-custom-taxonomy-name}.php
Output the cars there as well and your problem is solved without adding any inefficient queries.
I think you need to use get_terms()
$terms = get_terms("Subaru");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
echo "<ul>";
foreach ( $terms as $term ) {
echo "<li>" . $term->name . "</li>";
}
echo "</ul>";
}
See this http://codex.wordpress.org/Function_Reference/get_terms

Custom WordPress Search Not Consistent with Results

I've set up a custom search to use the s GET variable on a URL. I want it to fetch certain results but I've come across an odd problem. First, here's my code:
$search_term = $_GET['s'];
if($search_term!=''){
$s = new WP_Query(array('s' => $search_term));
$search_array = array();
if($s->have_posts()){
while($s->have_posts()){
$s->the_post();
$title = get_the_title();
$permalink = get_permalink();
$search_identifier = $title.$permalink;
array_push($search_array,$search_identifier);
}
}
}
Essentially, I'm creating an array of unique values for each post because I need to use them for a function immediately after that.
I have a post titled 'Kitchen Assistant.' When I search 'kitchen', it shows up. When I search 'assistant' it does not show up.
I have other posts with the word 'assistant' in the title and content and those show up when I search 'assistant'. I'm curious as to why it would show up with one search term and not the other?
I've used var_dump($s) and the post is in the dump when I search 'assistant' but not when I search 'kitchen.'
Any help would be greatly appreciated. Thanks!
Try this.
$search_term = $_GET['s'];
if(!empty($search_term)){
$args = array(
'post_type' => 'post',
'meta_query' => array(
'key' => 'title',
'value' => $search_term,
'compare' => 'LIKE'
)
);
$s = new WP_Query($args);
$search_array = array();
if($s->have_posts()){
while($s->have_posts()){
$s->the_post();
$title = get_the_title();
$permalink = get_permalink();
$search_identifier = $title.$permalink;
array_push($search_array,$search_identifier);
}
}
}
I figured out the answer to my own question (finally!). I'm using the NineToFive template and I guess by default there's a limit on the number of search results that's returned (I'm not sure if that's a WordPress default; maybe someone can clarify that).
I changed my query to this:
$s = new WP_Query(array('s' => $search_term, 'posts_per_page' => -1));
To not put a limit on the search results and that changed it. I needed to find every possible search term on page 1 in order to cross reference it with the location but it was 'paginating' the search results in search query end of it.
Thanks for the help!

Wordpress count_posts() equivalent function non-expensive method

I'm looking to count the number of posts in the last week then group them by a custom taxonomy called 'topic' So that in the next get_posts equation I can get topics by the number of posts to that area in the last week.
It can be done like this with get posts, but I am concerned that this is unnecessarily expensive on the server. Is there another way?
function count_posts_by_taxanomy($since,$taxonomy){
global $sincer;
$sincer = $since;
function filter_post_count($where = ''){
global $sincer;
$where .= " AND post_date > '" . date('Y-m-d', strtotime($sincer)) . "'";
return $where;
}
$args = array(
'numberposts' => -1,
'post_type' => 'post',
'suppress_filters' => false
);
add_filter('posts_where','filter_post_count');
$posts = get_posts($args);
remove_filter('posts_where','filter_post_count');
$count_term = array();
foreach($posts as $post){
foreach(get_the_terms($post->ID,'topic') as $term){
$count_term[$term->slug] += 1;
}
}
print_r($count_term);
}
Called like this:
count_posts_by_taxanomy('-5 days','topic');
You would be better using a custom database query. See here for more info on that: http://codex.wordpress.org/Class_Reference/wpdb
I would then suggest you store the result in a transient. You don't need to run the query on every load.
http://codex.wordpress.org/Transients_API
You can use WP_Query and call $wp_query->found_posts to find count of posts. And then do a loop and cache values.
More at : http://codex.wordpress.org/Class_Reference/WP_Query
$query = new WP_Query( array('posts_per_page'=>-1,
'post_type'=>array('post'),
'date_query' => array(array('after' => 'YOUR DATE')),
'tax_query' => array(
array(
'taxonomy' => 'YOUR TAX'
))));

Categories