Finding sum of ACF custom field value for comments - php

I have created a few custom fields for comments to allow reviews on a Wordpress site built for listing hotels with user reviews as comments. One of these custom fields is a 'star_rating' field. I need to find a way to fetch the total sum of all values in order to find the average 'star_rating' value for each post to be displayed in search results and on the listing profile.
I have been trying for a long time to find the total sum for the star_rating field values. I have last used the following code but it does not work although I cannot see why. Any help would be much appreciated.
$ratings_sum = 0;
// Arguments for the query
$args = array();
// The comment query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// The comment loop
if ( !empty( $comments ) ) {
foreach ( $comments as $comment ) {
$ratings_sum+= $comment->star_rating;
}
} else {
// echo 'No comments found.';
}
echo $ratings_sum;
Many thanks in advance.

If you are using ACF custom field plugin, try to use get_field() function. You can't access your custom field $comment->star_rating like this.

Try below custom query for fetch star rating:
SELECT SUM(meta_value) FROM wp_commentmeta WHERE comment_id IN (SELECT comment_ID FROM wp_comments WHERE comment_post_ID = '//your post id') and meta_key='star_rating';

Related

How to get a Woocommerce order by meta_value in Wordpress

I am building a custom Wordpress plugin to integrate with Woocommerce Orders. This plugin receives a string as input. Upon receiving this string input, the plugin must search Woocommerce for an order that matches the passed in value. The Woocommerce Orders have a custom field my_number which stores the values I am searching. I read about WP_Query class. I read about get_posts function. Both takes a list of args as a parameter. All these do not answer my problem. The problem is that running queries using all these Wordpress built-in capabilities are not returning a result! What is fun to me is that if I use the same meta_key on a normal Wordpress post, I do get a result back. So, why am I not getting the same result back on a Wocommerce Order. You will see, I have tried even to remove post_type filter and all other fields and only left the meta_key. This is just one example:
$args = array(
'meta_key' => 'my_number',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
return ("<pre>".print_r( $post,true)."</pre>");
}
So, my question is how to a search an Order in Woocomerce Wordpress using the existing functionalities.
I can see the record in MySQL when I run
SELECT * FROM `wordpressTable_postmeta` WHERE meta_key = 'my_number'
Attached screenshot shows this order, with the custom field.
Okay, so I came across this article. To query Woocommerce order, you need to use the Woocomerce class WC_Order_Query.
https://pluginrepublic.com/querying-woocommerce-orders/
Now my fixed query looks like this and it is returning something:
$args = array(
'meta_key' => 'my_number',
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
foreach ( $orders as $order ) {
return ("<pre>".print_r( $order,true)."</pre>");
}

How to display products with shortcode in custom order?

I'm using woocommerce shortcode to display custom products loop, e.g. [products limit="-1" paginate="true" orderby="menu_order" columns="5" ids="85,11,1083,256,37,12,517,68,2577,104"]. But there's a problem – they are displaying sorted by title, but I need them to be sorted in that exact order they are in shortcode. I found no such option in shortcodes docs. Is there a way to achieve it with shortcode?
The woocommerce_shortcode_products_query_results hook runs after the products have been queried from the database, but before they are displayed on the page. By hooking into this hook and modifying the order of the results, it is possible to display the products in the desired order.
//Products shortcode custom order by id
add_filter('woocommerce_shortcode_products_query_results', 'bytflow_custom_products_shortcode_order', 10, 2);
function bytflow_custom_products_shortcode_order($results, $shortcode_products){
$attributes = $shortcode_products->get_attributes();
$order_by_arg = get_query_var('orderby');
// Check if there are any ids specified and that user didn't change the order
if (empty($order_by_arg) && ! empty( $attributes['ids'] ) ) {
$ids = explode( ',', $attributes['ids'] );
$ordered_results = array();
foreach ($ids as $id){
if(in_array($id, $results->ids)){
$ordered_results[] = $id;
}
}
$results->ids = $ordered_results;
}
return $results;
}
This code checks for the presence of the ids attribute in the shortcode and, if it exists, rearranges the products in the $results->ids array to match the order specified in the attribute. Source
Solution found: orderby = "post__in"
Source: Woocommerce Product Short Code Order by Order of IDs

Sorting WP user columns by non-meta value (PHP)

UPDATE: I've read a few more posts about similar issues and the consensus seemed to be that filtering by the actual data in the user admin table isn't an option, and that sorting needs to be done via adding the data to postmeta if it isn't there already. Hoping this isn't the case, but it's starting to sound like it.
I have added a handful of custom columns to the user admin table. Some of the columns get their values from custom user meta, but some do not. I've been able to make the columns that source their content from meta just fine with
if ( 'member_number' == $query->get( 'orderby' )) {
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', 'number' );
}
...but the column I'm unable to sort a column that gets its values by cross-referencing the user's info against entries from a Gravity Form, sorting the GF entries by date, and outputting the position of the GF entry that was matched to the user.
It might be simpler to just say that I want to display a "wait-list position" that can change frequently and would require updating postmeta of ~100 posts on a regular basis to accurately display the users position in the queue. Not thinking that was practical to do, the best I could come up with is to reference the user's email address against the list of those on the wait-list.
If it helps, the code that references my custom function and applies it to my column is:
if ('waitlist_pos' == $column_name){
$waitlistNumber = get_waitlist_position( $user_id );
$value = $waitlistNumber;
return $value;
}
...and my function to get those values is:
function get_waitlist_position( $user_id ){
$waitlistUser = get_user_by( 'id', $user_id);
if ( empty( $waitlistUser ) ) {
return;
} else {
$waitlistUserEmail = $waitlistUser->user_email;
$form_id = '18';
$entries = GFAPI::get_entries($form_id);
usort($entries, make_comparer('date_created'));
$emails = array_column( $entries, '3' );
$waitlistposition = array_search( $waitlistUserEmail, $emails );
if ( !in_array( $waitlistUserEmail, $emails, true )) {
return;
}
}
return $waitlistposition +1;
}
Only a few percent of users are on the waitlist.
I've managed to get the custom column created and to display the appropriate wait-list position of the user in the user admin table, but every guide I've found on making the column's content sortable either describe default WordPress sortable criteria, or by a meta query like I've done for other columns in the code above.
Any thoughts on simply sorting these columns by their value if the value does not actually exist as user meta or user data? The values are simple integers, starting from 1 and going to 100 or so.
I've tried leaving the created column alone, and although it does have the arrows indicating it is sort-able, clicking it does not change the order of the entries, and trying to force a query like the WP_Query used earlier, of course, results in a blank table once I try to sort.
Thanks for reading the long question about my simple problem! Also happy to hear if making the wait-list position into some sort of dynamic post-meta may make more sense.

Ordering Wordpress posts based on parent category

UPDATE: I have tried using the following code:
<?php if (is_category(events)) {
$posts = query_posts($query_string . '&orderby=event_date&order=desc');
} else {
$posts = query_posts($query_string . '&orderby=title&order=asc');
}
?>
Is there any reason why that wouldnt work? It seems to work fine organising posts in alphabetical order, but still no luck on the date order within 'events'.
--
After searching through various existing questions I can't quite find a solution to what I am trying to do.
Currently all posts on my site are ordered alphabetically, which is fine except for one new category that I have added. For this category I want to order all posts by a value that I enter into a custom field. The field is called 'event_date' - so I want to order the posts by date essentially, but not the date the post was created, the date the user manually enters into this field.
I managed to get it working by using:
<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>
However this overrides the aphabetical order for all other pages.
For alphabetical order I am using:
<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>
Essentially I want a statement that tells the page to order all posts in aphabetical order, unless the category is 'events', where I want to order them by the custom event date.
As you can probably tell I'm very much front end, not back end so a lot of this is fairly new to me, so any help or advice is appreciated.
To order posts by a custom field value, you need add the custom meta field to the query itself. orderby=meta_value in addition to meta_key=metafieldid will allow ordering in this fashion.
I would use the pre_get_posts hook and modify the query object if get_query_var( "cat" ) (or a similar query var) returns the desired post category.
add_action( "pre_get_posts", "custom_event_post_order" );
function custom_event_post_order( $query )
{
$queried_category = $query -> get_query_var( "cat" );
/*
* If the query in question is the template's main query and
* the category ID matches. You can remove the "is_main_query()"
* check if you need to have every single query overridden on
* a page (e.g. secondary queries, internal queries, etc.).
*/
if ( $query -> is_main_query() && $queried_category == 123 )
{
$query -> set( "meta_key", "event_date" ); // Your custom field ID.
$query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
$query -> set( "order", "ASC" ); // Or "DESC".
}
}
Remember that this approach overrides all queries that are using the category in question. You can build custom WP_Query objects that use their own parameters for constructing loops.
You also should standardize the way you save the custom field data to the database. For dates I prefer using UNIX-timestamp formatted times that are easy to move around and manipulate. This way no accidents happen when querying and some data is formatted in another way that the rest is.
Disclaimer: I did not have the time to test the above code in action, but the general idea should work properly.
EDIT: of course the above code should be inserted to functions.php or a similar generic functions file.
What about:
<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc'); ?>
<?php
$recent = new WP_Query(“cat=ID&showposts=x”);
while($recent->have_posts()) : $recent->the_post();
?>
Hopefully I understood your question, use the WP_Query and within the orderby add a space between your order by columns:
$args = array(
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
);
if(is_category($events)){
$args['orderby'] .= " meta_value_num";
$args['meta_key'] = 'event_date';
}
$posts = (array) new WP_Query( $args );

WordPress "wp_list_comments" custom order

I'm using WordPress 3.0.1 and want to order the comments from a post using a rating custom field.
Is this possible? I'm already using the callback property from wp_list_comments to customize the appearance of the comments.
Unfortunately this way I can only access the comments one by one and can't affect the order of the all result array.
I've already have a table with all the votes from the users.
Thanks in advance.
// get comments of post 1234
$comments = get_comments( array('post_id' => 1234) );
// ... order your comments collection using php (eg. usort) here ...
// print your comments
wp_list_comments( array( 'callback' => 'woocommerce_comments' ), $comments);
Try $comments = get_comments('postId=x');. It should be indexed by comment id. You can then look up the comment rating in your table.

Categories