Ive been looking all over web i even tried to hire freelancer for help on this but had no luck. While searching i found this how to get popular posts fro selected categories in wordpress? & http://www.queness.com/code-snippet/6546/how-to-display-most-popular-posts-from-a-specific-category-in-wordpress and thats basically what i want but i want the information i get from it split up so i can rank the post.
<?php
$args=array(
'cat' => 3, // this is category ID
'orderby' => 'comment_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 6, // how much post you want to display
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
<?php }
wp_reset_query(); ?>
With that code it gets the most popular post by comments and what i want to do is basically take the results and add a rank to it like example below.
#1 - post 1
#2 - post 2
#3 - post 3
#4 - post 4
#5 - post5 last post
thanks in advance for any help
May be this idea will help you.
Use get_comments_number( $post_id ) function
To get number of comment and then do a if else loop for displaying rank.
$num_comments = get_comments_number(); // get_comments_number returns only a numeric value
if ( comments_open() ) {
if ( $num_comments == 0 ) {
$rating= 0 ;
} elseif ( $num_comments > 1 ) {
$rating= 1 ;
} else {
$rating= 0 ;
}
}
Thanks
By your current question I understand the following:
You want to query from the WP database posts that have the most comments.
You want to display to visitors a ranking for those received posts. The ranking is determined by the amount of comments post has.
So your result could be:
1 Post A (comment count 500)
2 Post B (Comment count 499)
3 Post Z (Comment count 200)
This is how I would do it:
<?php
function get_popular_posts()
{
$sql="SELECT comment_count, guid AS link_to_post, post_title
FROM wp_posts
WHERE post_status = "publish" AND post_type = "post"
ORDER BY comment_count DESC
LIMIT 5"
return $wpdb->get_results($sql, OBJECT)
}
$post_objects = get_popular_posts();
$i = 1;
foreach($post_objects as $object)
{
echo 'Post: ' . $i . '#' . ' ' . $post_title . ' ' . $link_to_post . ' ' . $comment_count;
$i++;
}
?>
Haven't tested the code. But it should take five "top posts" from the database. Left in the comment_count for explanatory reasons.
Related
I would like to groupe WP post (from 'dlm_download' post type by values from an acf field 'telechargement_type_fichier'.
Value 1 : Post 1 Post 2 Post 3
Value 2 : Post 4 Post 5 Post 6
Value 3 : Post 7 Post 8 Post 9
...
Here's my code :
$field_posts = array();
$args = array(
'post_type' => 'dlm_download',
'post_status' => 'publish',
);
$query = new WP_Query($args);
while ( $query->have_posts() ) {
$query->the_post();
$field = get_post_meta(get_the_ID(), 'telechargement_type_fichier',true);
$field_posts[$field][] = $post;
}
wp_reset_query();
foreach ($field_posts as $field_post => $field_title) {
echo '<p style="font-weight:bold;">' . esc_html($field_post) . '</p>';
foreach ($field_title as $post_listing => $listing)
{ setup_postdata($listing);
$id = get_the_id();
$title = get_the_title($id);
var_dump($title);
}
wp_reset_postdata();
}
However, here's the result I obtain :
Value 1 - programme_scolaire
Post 1 - Title Post 1 - Title Post 1 - Title
Value 2 - module
Post 1 - Title
Value 3 - flyer
Post 1 - Title Post 1 - Title
Value 4 - jeu
Post 1 - Title Post 1 - Title Post 1 - Title Post 1 - Title
I obtain the real posts number by existing values field but same post/title into the loop.
May be post id error or "reset_postdata()"... Don't understand why.
Could you help me ?
Thanks !
I'm not super familiar with PHP/Wordpress, but I think your inner foreach should look like this:
foreach ($field_post as $post_listing)
{ setup_postdata($post_listing);
$id = get_the_id();
$title = get_the_title($id);
var_dump($title);
}
Or
foreach ($field_post as $post_listing => $listing)
{
var_dump($listing);
}
I found the solution.
Making an array :
$field_posts = array();
Making a query with posts you would like to filter by field value and calling the ACF field and value you want to display.
$args = array(
'post_type' => 'dlm_download',
'post_status' => 'publish',
'posts_per_page' => 20,
);
$query = new WP_Query($args);
while ( $query->have_posts() ) {
$query->the_post();
$title = get_the_title();
$value = get_field_object('telechargement_type_fichier');
$field = $value['value']['label'];
$field_posts[$field][$title] = $post;
}
Making a foreach loop into a foreach loop to classify each post per field value
foreach($field_posts as $field_post => $field_title) {
echo '<p><strong>' . $field_post . '</strong></h3>';
foreach($field_title as $post_listing => $listing) {
echo '<p>' . $post_listing . '</p>';
}
} wp_reset_postdata();
I obtain :
Field value 1
Post 1
Post 2
Field value 2
Post 3
Post 4
etc .........
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 ) );
On my home page I'm showing 9 post, I have a load more button (with ajax) who calls 9 other posts and so on. Currently I'm ordering by 'date' but I would like to order by random. The problem is that my first wp_query orderby rand shows 9 random post, and when I load more post my second wp_query orderby random too can shows the same post from the first 9 post.
How can I randomize 2 wp_query with the same random ? Or is there another way to do this ?
As it is already suggest by a community member, I tried to store visibles Id in an array and used post__not_in like :
$query = new WP_QUERY(array(
'post_type' => 'my_posts',
'posts_per_page' => 9,
'orderby' => 'rand',
'post__not_in' => $postNoIn,
'paged' => $paged
));
But this didn't solve my problem.
The $paged variable is the current page number for my posts. I have 32 posts and I'm getting them 9 by 9, so there is 4 pages. When I use the second wp_query displays above, I get 9 random post minus the possible 9 first posts, so I can have less than 9 post and the query stopped when the last page in reached. I will have about 28 posts and not 32 cause the query stopped at page 4 and not until all posts are displayed.
Thanks in advance for your answers !
I've finally succeeded !
Here is my answer
I change my first query to get all post order by "rand", like :
$args = array(
'post_type' => 'my_posts',
'posts_per_page' => -1,
'orderby' => 'rand'
);
Then in my loop I display the 9 first posts, after 9 posts I get the ID of all the others posts
<?php
$index = 0;
$idsInt = array();
while ($the_query->have_posts()):
$the_query->the_post();
if ($index < 9) :
get_template_part('part-template/content', get_post_format());
$index++;
else :
array_push($idsInt, get_the_ID());
endif;
endwhile;
After that I prepare my data to be use with ajax, for this I convert my list of int element into a string list
$index = 0;
$idsString = array();
foreach ($idsInt as $id) {
if ($index == 0) {
$idsString .= " \"" . $id . "\"";
} else {
$idsString .= ", \"" . $id . "\"";
}
$index++;
}
Here is my "Load More" button, I put in "data-id" my list of ID
<div class="text-center">
<a id="btn-load-more" data-id='[<?php echo $idsString ?>]'
class="home-load-more"
data-page="1"
data-url="<?php home_url(); ?>/wp-admin/admin-ajax.php" >
<span class="text"><?php _e('Load More') ?></span>
</a>
</div>
In my script.js, my ajax function looks like :
$(document).on('click', '.home-load-more', function () {
let that = $(this);
let page = that.data('page');
let newPage = page + 1;
let ajaxurl = that.data('url');
let ids = that.data('id');
$.ajax({
url: ajaxurl,
type: 'post',
data: {
page: page,
action: 'home_load_more',
foo : ids
},
error: function (response) {
console.log(response);
},
success: function (response) {
if (!(response === "")) {
that.data('page', newPage);
$('.my_row').append(response);
}
}
});
});
My $_POST['page'] contains a number of page that increment on every Load More call, I'll explain why I'm using it later, and my $_POST['foo'] contains my list of ID create in my first query loop.
Now my php functions !
( explications of my code in the php comments ! )
function home_load_more()
{
$ids = ($_POST['foo']);
$paged = $_POST["page"];
$postIn = array();
// I want to display only 9 posts on each calls
for ($i = 0; $i < 9; $i++) {
/* Here is my strange calcul to get ids
- from 0 to 8 on the first call
- from 9 to 17 on the second call
- from 18 to 26 on the third call
and so on...
That is why I use the $paged, to get
a value that is increment by one on every calls. */
// Break if they are no more ids in the list
if ($ids[($paged - 1) * 9 + $i] == null) {
break;
}
// $postIn contains 9 posts IDs
array_push($postIn, $ids[($paged - 1) * 9 + $i]);
}
$query = new WP_QUERY(array(
'post_type' => 'my_posts',
'orderby' => 'post__in', // here I give my list of 9 ids
'post__in' => $postIn
));
if ($postIn[0] == null) {
// Load More button won't display any posts
wp_reset_postdata();
} else {
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
get_template_part('part-template/content', get_post_format());
}
}
wp_reset_postdata();
}
die();
}
That's it ! I think there is a best way to do this but I still want to show you my code. Hope this can help somebody, and if you have comment, questions, or ideas, don't hesitate to tell me in the comment section !
Just store already visible ids somewhere in array, when requesting load more, send that array, then include it to $args
$args = array (
...
'post__not_in' => array( 1, 2, 3),
...
);
I need to build an 'announcement' banner showing the 5 latest posts, of which one MUST be the latest newsletter.
What I want to do: latest 4 posts excluding newsletter category + latest newsletter post as the 5th post.
How is this possible?
I have tried tax_query, but then it only shows the newsletter category, and does not limit that specific category.
I have tried excluding all post IDs from the newsletter category, but then if there are no newsletters in the latest 5 posts, it does not show the latest newsletter at all.
Code:
$category_id = get_cat_ID('Newsletter');
$latest_newsletter = query_posts("cat=$category_id&order_by=date");
$exclude_ids = [];
$count = 0;
while (have_posts()) : the_post();
$post = get_post();
if($count > 0) {
$exclude_ids[] = $post->ID;
}
$count++;
endwhile;
wp_reset_query();
query_posts(['posts_per_page' => '4', 'order_by' => 'date', 'post__not_in' => $exclude_ids]); if (have_posts()) : ?>
<div class="news-announcement">
<h3>ANNOUNCEMENT</h3>
<div id="ticker" class="ticker">
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li> continue reading...
<?php the_title( ); ?></li>
<?php endwhile; ?>
</ul>
</div>
</div>
Any ideas?
You can create two separate query objects to achieve what you want.
e.g
//this is just an example not complete code
// write you actual query in the array passed to WP_Query
$latest_articles = new WP_Query( array('order' => 'DESC', 'posts_per_page ' => 4) );
while ( $latest_articles->have_posts() ) :
// Loop over the posts and show the content
$newletter_article = new WP_Query( array('order' => 'DESC', 'posts_per_page'=> 1, 'cat' => 1 ) );
while ( $newletter_article->have_posts() ) :
//show the newletter article
Running a voting system on my site that lets users vote on posts with the standard up/down type thing.
I'm trying to run a query on author pages to get the total number of 'votes' that author has attributed to them over all the posts they've made.
Small problem is that when the author has zero votes it displays the total number of votes from the meta_key value for every author on the site.
Code:-
<?php
function author_rating_total() {
$user_id = get_the_author_meta( 'ID' );
$query = array (
'author' => $user_id,
'suppress_filters' => 'true', //lets skip some unnessecery sql queries
'posts_per_page' => -1
);
$queryObject = new WP_Query($query); while($queryObject->have_posts()) : $queryObject->the_post();
$post_ratings_data = get_post_custom(get_the_id());
$post_ratings_score = intval($post_ratings_data['votecount'][0]);
$ratings_array[] = $post_ratings_score;
endwhile;
$ratings_sum = array_sum($ratings_array);
if ($ratings_sum > 0) {
$ratings_sum = '' . $ratings_sum;
}
echo $ratings_sum;
wp_reset_query();
}
?>
<?php
echo author_rating_total();
?>
How do I return the value 0 instead of the total number of that meta_key?