Wordpress - Add numerical values of custom fields together - php

I have a custom post type created in my WordPress blog called 'reviews'. Inside this I have a custom field with a number out of 5.
I am trying to add all of these numbers together and then divide by the amount of posts to get an aggregate score.
I am attempting to use this code...
<?php
$total_score=0;
$meta_key = 'target';//set this to your custom field meta key
$allscores=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
foreach ($allscores as $score) {
$total_score = $total_score + $score;
}
echo 'Total score is '.$total_score;
?>
But I am getting a result of 0, can anyone see where I am going wrong?

Turns out it was me all along, the numbers entered in the database were spelt out alphabetically rather than numerical so the 0 result I was receiving was technically correct :)

Related

ACF make top 10 based on field value

I'm using ACF for a while now and I thought this would be easier but cant figure out how to do this properly...
I'm trying to create some kind of trophy cabinet. So every company has a score that is stored inside a ACF called "company_score".
For example we have companies called Microsoft, Facebook and Twitter. They all have a score:
Facebook = 200000
Microsoft = 900000
Twitter = 100000
So the top 3 wil be like
1) Microsoft
2) Facebook
3) Twitter
I know how to display the value of an ACF but how can I compare all the scores that are stored and when a company has the best score it will display a gold medal. When a company has the second best score it will display a silver medal and so on.
I all had it figured it out in my head but a bit stuck here how to do this.
There could be several approaches to handle this. The first one, which comes in my mind is very simple.
Try these steps:
Pull all fields
Store in an array
Sort the array in ascending order
Display the results.
I hope, you've some understanding of the code but here are the coded guidelines...
<?php
$fields = get_fields();
$company_details = array();
if( $fields ):
foreach( $fields as $name => $value ):
$company_details[ $name ] = $value;
endforeach;
endif;
//to sort by company score
arsort( $company_details );
//loop through the array and display results, like
foreach( $company_details as $name => $value):
echo "Company name is: " .$name. ". Company Score: " . $value;
endforeach;
PS: The code is not tested because the purpose was to share logic with you. So, ignore if there's any error.

Insert into array based on items insert date

I am trying to make an array with posts in them, now, i need to insert the posts into the array based on their post date, eg if a post was posted on day 4 it will come after the post that was posted on day 5, so the newest posts gets added and displayed first, is there a good way to do this?
The easiest and not right method at all:
$sortedNews = []; //sorted news
foreach($newsArray as $news) {
$sortedNews[strtotime($news['date'])] = $news; //take date and switch to unix timestamp as key of value
}
krsort($sortedNews); //sort by key (reverse) new to old
The right way it's let your database sort it itself ORDER BY `date` DESC

How to get meta_key and its meta_value within wp_usermeta by ajax call (json format)

In Wordpress I have created some custom fields within my Theme Edit Profile page which, one of them, allows me to enter a user address.
This address is automatically stored in WordPress DB under table wp_usermeta. (custom field is called user_address).
From wp_usermeta, the column called meta_key has a value 'user_address'. But the content I"m trying to collect is its meta_value equivalent.
Screenshot:
Here my php code to convert the data into JSON format:
......
$row=$db->prepare('select * from wp_usermeta');
......
foreach($row as $rec)//foreach loop
{
$json_array['meta_key']=$rec['meta_key'];
array_push($json_data,$json_array);
}
From the JS file:
request('file.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
console.log(data[i].meta_key);
}
........
My problem is here. From data[i] I need to get all the 'user_address' (within meta_key) and the equvalent value stored in meta_value as shown in the screeshot above, but unfortunately I don't know how to get it.
I can get all the meta_key values, but I don't know how to associate user_address to meta_value.
I've tried:
data[i].meta_key.user_address.meta_value
data[i].user_address.meta_value
data[i].meta_key[user_address].meta_value
data[i].meta_key['user_address'].meta_value
Any suggestions?
Thanks
Okay, so the user_address in your table is not a key, it is the value of meta_key. Your end result, thinking logically, is that you want the meta_value of a meta_key that has the value of user_address.
One way to do this, to change the foreach loop in php to:
foreach($row as $rec)
{
$json_array[$rec['meta_key']]=$rec['meta_value'];
array_push($json_data,$json_array);
}
Now, if you dump that array, it will look like:
array(
...
[10] => array (
'user_address' => '26 Aorile Costo'
),
...
)
And you can reference to it in javascript with data[i].user_address
You could also get rid of the array_push, and just output the $json_array, so you wont have to walk the array in javascript, and can reference to it simply as data.user_address, because the array dump will now look like:
array(
...
'user_address' => '26 Aorile Costo',
...
)
I have found a solution.
Changed from
$row=$db->prepare('select * from wp_usermeta');
to
$row=$db->prepare('select * from wp_usermeta where meta_key = "user_address"')
Then i've changed :
$json_array['meta_key']=$rec['meta_key'];
to
$json_array['meta_value']=$rec['meta_value'];
and data[i] becomes data[i].meta_value

PHP: do an ORDER BY using external data?

Ahoy all! Long story short with this one if you don't mind lending a hand to this novice PHPer. :)
I have a database field called "Categories" that has this stored:
Fruit, People, Place, Animals, Landscape
I also have a separate table in the DB that has items with these category names in the fields for each item. Right now, the script (i am trying to fork it a bit) uses:
SELECT DISTINCT(type), type FROM the_categories ORDER BY type ASC
in order to display a list of all categories available. Simple enough right?
Welllllll..... I don't want to sort by ASC, I want to sort by the list of items in the first Categories field I mentioned. Whatever order those are in is the order I want to display the "types" above.
Obviously I will have to do an explode on the commas, and maybe give them a 1 to whatever order....but even then.... how do I do an "orderby" using data stored in another folder?
Is this even possible? lol Thanks again!
... ORDER BY FIELD(type,"Fruit","People","Place","Animals","Landscape")
http://www.cfdan.com/posts/Handy_MySQL_-_ORDER_BY_FIELD.cfm
And just so future onlookers have it .... here is the explode code
$query2 = mysql_query("SELECT * FROM categorytable");
while($row = mysql_fetch_array($query2)){
$categories = html_entity_decode($row['categories']);
$thelist = explode(',', $categories);
foreach($thelist as $order){
if(trim($order) != ''){
$order = trim($order);
$order = ", '".$order."'";
$theorder .= $order;
}
}
and then for the query, just put in the the order variable
SELECT DISTINCT(type), type FROM the_categories ORDER BY FIELD(type" . $theorder .")")

I need to get the post id for the first post of the current user in wordpress

I have this so far
get_currentuserinfo(); $the_post = get_posts("author=" . $current_user->ID . "&posts_per_page=1"); $the_post = $the_post[0];
but I'm not sure how to get just the ID out of the array
get_posts() will return an array of posts ordered by the date of publication, in descending order. So, with the code you posted, the first post in the array ([0]) will be the last post published by the author. If you really want the first post of the user, you can just add the order argument to the call (&order=ASC) to override the default.
I think the key for the ID is just "ID", so you can retrieve it with $the_post = $post[0]['ID']. But I have to admit I can't remember for sure and the documentation does not detail that, it could also be "post_id". You can do a: print_r($the_post) to check the keys of the returned array.
You can write query like this way-
$oldest_post_query = get_posts("post_type=post&numberposts=1&order=ASC");
$oldest_post_id = $oldest_post_query[0]->ID;
//print the post title
<h1>'.get_the_title( $oldest_post_id ).'</h1>';

Categories