Wordpress: sum custom meta_values from all posts by a user - php

Ok, so right now I have a working code, that basically echo the total amount of posts for meta_key _heart_this for a specific user:
<?php $query = new WP_Query( array( 'meta_key' => '_heart_this', 'author' => 1, ) );
echo $query->found_posts; ?>
However, some posts have meta_value of 2, 3 etc..
So I want to sum the total amount of meta_value and echo, because right now the number I get is inaccurate obviously.
I'm almost there, need a bit of guidance.
Thanks in advance.

It should be taken in loop. Use below code
$query = new WP_Query( array( 'meta_key' => '_heart_this', 'author' => 1) );
//Take all values in array
$sum = [];
if( $query->have_posts()){
while( $query->have_posts()): $query->the_post();
{
//Get all posts values one by one
$value = get_post_meta( get_the_ID(), '_heart_this', true );
//Push values in array
array_push($sum, $value);
}
endwhile;
}
//Sum all values of array to get total amount of meta value
$sum_final = array_sum ($sum);
echo $sum_final;
Tested & works

Related

Wordpress: echo TOTAL amount of posts for post author by meta_key?

Ok, so I know how to echo meta_key value for a post:
<?php
$meta_print_value=get_post_meta(get_the_ID(),'_heart_this',true);
echo($meta_print_value);
?>
I also know how to echo a TOTAL amount of posts with this specific meta_key:
<?php $query = new WP_Query( array( 'meta_key' => '_heart_this' ) )
echo $query->found_posts; ?>
What I need, is the TOTAL amount of posts for this meta_key for a post author.
I know I need to add get_the_author() somewhere in the above code to show the total amount of posts for the post author only, but struggling for a while now.
Any help would be appreciated.
Use Author Parameters in WP_Query(). You can use author id/name/multiple authors. For your case, the query should look like this:
<?php
$query = new WP_Query(
array(
'author' => get_the_author_meta( 'ID' );
'meta_key' => '_heart_this',
),
);
echo $query->found_posts; ?>

WP Query and ACF fields

Im new to WP Query and ACF custom fields. I want to write a code that will show first 3 results from the calculation of the total_score custom field. I have managed to short by the total score but I want to show the title and permanlink of the first 3 posts so the visitor will click and go to the post. Any help will be much appreciated. My code so far :
$args = array(
'posts_per_page' => -1,
'post_title' => true,);
$all_posts = array();
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ):
while ( $the_query->have_posts() ): $the_query->the_post();
// Get all fields
$fields = get_fields();
// Push each $fields array into the $all_posts array
array_push($all_posts, $fields);
endwhile;
// Restore original Post Data
wp_reset_postdata();
// Print the result here and do what you choose
print_r($all_posts);
endif;
if(isset($_POST['place']))
{ // start the loop
$q1=$_POST["place"];
//CORECT CODE !!!!
foreach($all_posts as &$value) {
if ($value['question1']==$q1){
$value['total_score']=$q1;
}
} } //end question 1
// question 2
if(isset($_POST['home']))
{ // start the loop
$q2=$_POST["home"];
foreach($all_posts as &$value) {
if ($value['question2']==$q2){
$value['total_score']=$value['total_score']+$q2;
}
//echo $value['total_score']."<br>"; }
//echo "Q2"."<br>";
//print_r($all_posts);
} //end question 2
// question 3
if(isset($_POST['hours']))
{ // start the loop
$q3=$_POST["hours"];
//CORECT CODE !!!!
foreach($all_posts as &$value) {
if ($value['question2']==$q3){
$value['total_score']=$value['total_score']+$q3;
}
}
//echo "Q2"."<br>";
} //end question 3
// shorting by total_score
function sortByOrder($a, $b) {
return $b['total_score'] - $a['total_score'];
}
usort($all_posts, 'sortByOrder');
//print_r($all_posts);
foreach($all_posts as &$value) {
echo $value['total_score']."<br>";
}
Please replace your code with only this code. It's give you only 3 post and your total_score ASC or DESC
and Replace data in as per comment
Let me know if any Query
<?php
$args = array(
'post_type' => 'portfolio', // your post type name
'orderby' => 'meta_value_num', // if total_score is string then use it - meta_value
'meta_key' => 'total_score', // your meta key name ( total_score custom field )
'posts_per_page' => 3,
'order' => 'ASC' // ASC or DESC
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
echo ''.get_the_title().'';
endwhile;
endif;
wp_reset_postdata();
You could look at using your $args variable to both limit and filter the results of WP_Query. Setting your 'posts_per_page' => 3. This means only 3 posts will be returned in the query.
However, as you are fetching all of the posts and using usort to sort them, you can swap this out to use this resource to help you query using a custom field. This will reduce the amount of work is needed to compile the posts you require.
You can then use the final result to loop over the 3 posts and output your title & permalink.

Add incremental parameter value to each post in wordpress query loop

I'm trying to combine several loops into one and sort the final results by relevance.
For the former part, I did this:
// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID);
$first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
// loop for same author
$by_author = new WP_Query (array(
'author' => $author_id,
'posts_per_page' => '5'
));
// add ids to array
if ($by_author->have_posts()) {
while ($by_author->have_posts()) {
$by_author->the_post();
$add[] = get_the_id();
}
}
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// add ids to array
if ($by_tag->have_posts()) {
while ($by_tag->have_posts()) {
$by_tag->the_post();
$add[] = get_the_id();
}
}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// add ids to array
if ($by_category->have_posts()) {
while ($by_category->have_posts()) {
$by_category->the_post();
$add[] = get_the_id();
}
}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'posts_per_page' => '10',
'orderby' => $weight[$post->ID],
'order' => 'DESC'
));
// show them
if ($related->have_posts()) {
while ($related->have_posts()) {
$related->the_post();
// [template]
}
}
This is working nicely combining the loops into one. For the latter part, what I'm trying to do next is to add an incremental "weight" value to each post as they come up so as to later sort them with something like 'orderby' => $weight,.
For example, if a post comes up in "same author" it gets 3 points, if another one comes up in same tag it gets 2 points and so on. If it comes up in more than one loop, it should get the combined points i.e. 3+2+1=6 hence be boosted to the top of the final query.
I have tried to add a counter to each preliminary loop, like $weight = +3 etc, but this only adds everything up for every post, not individually.
I also tried inserting something like this at the end of each preliminary loop...
$weight = 0;
if ($by_author){
foreach ($by_author as $post){
setup_postdata($post);
$weight = +10;
add_post_meta($post->ID, 'incr_number', $weight, true);
update_post_meta($post->ID, 'incr_number', $weight);
}
}
... and this to the final one
echo get_post_meta($post->ID,'incr_number',true);
But it still doesnt do it right. It assigns a global value, while I want them to be different depending on the actual main posts one is reading.
So is there a way to do this?
If I understand your question right, I think your last solution was close. Instead of a global $weight parameter, however, I think you need to build an array of $weights that's unique to each post:
$weights[$post.id] += 10;
Then, you could sort that array and get your most heavily weighted post IDs from there.

Wordpress - get total No. of meta_key for author

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?

Order posts by last comment date in WordPress

I am using a combination of get_comments() and get_post() to display a list of posts ordered by comment date.
Ref:
http://codex.wordpress.org/Function_Reference/get_comments
https://codex.wordpress.org/Function_Reference/get_post
My code:
$args = array(
'status' => 'approve',
'order' => 'DESC'
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) {
$post = get_post( $comment->comment_post_ID );
echo $post->post_title;
}
The problem with this approach is the list of posts will contain duplicate post titles if a post has more than one comment.
How can I remove the duplicates?
UPDATE:
This initial approach does a lot of unnecessary legwork. For example, on sites that have lots of posts and comments, the query will pull back lots of unnecessary comments.
UPDATED QUESTION:
How can I order a list of posts by comment date?
This is an interesting approach...but, I suppose you could just fill an array with post ID's and then check them later.
$args = ....
$ids = array();
.....
if(!in_array($post->ID, $ids):
$ids[] = $post->ID;
echo $post->title;
endif;

Categories