Wordpress - Count users by custom field - php

I have created a custom field for my wordpress users: GENDER containing MALE and FEMALE.
Now I want to count the number of male and female users.
Best would be using functions.php
This code counts the total users. Can it be extended to count the genders?
add_shortcode( 'ucount', 'wpsites_user_count' ); //Count users
function wpsites_user_count() {
$count = count_users();
echo "There are " , $count['total_users'] , " on your website!";}

This does the job:
add_shortcode( 'countfemale', 'wpsites_user_countfemale' ); //Count users
function wpsites_user_countfemale() {
$args = array(
'meta_key' => 'gender', //any custom field name
'meta_value' => 'female' //the value to compare against
);
$users= new WP_User_Query( $args );
echo $users->get_total();
}

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; ?>

Wordpress: sum custom meta_values from all posts by a user

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

Add ability to search for a category name in ajax search field wordpress

I have a Wordpress ajax search field that the user can search for products. I want to be able to search by product category also. "Whats new", "limited edition", etc. How would I query and display the category name?
Also I need the user to be able to search by location name and when clicked direct to a location page. So if they search "Walmart" or "Target" the link would always go to the location page. The location would not be a taxonomy so I'm guessing this would have to be hardecoded with all the locations names which is fine. How would I hardcode this into a query?
<?php
/*
** Custom search ajax
*/
add_action('wp_ajax_custom-search', 'search_ajax');
add_action('wp_ajax_nopriv_custom-search', 'search_ajax');
function search_ajax() {
if($_GET['s'] === '') {
wp_send_json(array(
'results' => [],
));
}
else {
$query = new WP_Query( array('s' => $_GET['s'], 'post_type' => array('product', 'tutorial') ) );
$query2 = new WP_Query( array('tag' => sanitize_title_with_dashes($_GET['s']) . ',' . sanitize_title_with_dashes(preg_replace('/s$/i', '', $_GET['s'])) . ',' . sanitize_title_with_dashes(preg_replace('/es$/i', '', $_GET['s'])) , 'post_type' => array('product', 'tutorial') ) );
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query->posts, $query2->posts );
$wp_query->post_count = $query->post_count + $query2->post_count;
wp_send_json(array(
'results' => array_map(function($p) { return array( 'title'=>get_the_title($p),'uri'=>get_permalink($p),'category'=>get_the_category($p->ID, 'search_category'),'postType'=>get_post_type($p),'thumb'=>get_the_post_thumbnail($p->ID,'medium')); }, $wp_query->posts)
));
}
}
?>
Because you probably query when printing the page for the categories / locations, i would have just printed the list into a JS array, and then work with a autocomplete plugin. Ex: https://jqueryui.com/autocomplete/
But in some cases i would prefer ajax live search, not this case.

Wordpress custom post type column sort query

I have a custom post type called reservation. In it I get the reservation for event/room you name it (not important).
When I go to my custom post type page, I get all the posts nicely displayed. The first column is the reservation date. Now the reservation date can be one - 28.11.2015, but it can also be multiple dates - 28.11.2015, 29.11.2015, 02.12.2015.
I would like to enable the sorting of that column. The problem is, this is a string, not a number so I cannot just create a simple sortable column query like described here.
So far I tried this:
add_filter( 'manage_edit-reservation_sortable_columns', 'reservation_sortable_column' );
if (!function_exists('reservation_sortable_column')) {
function reservation_sortable_column( $columns ) {
$columns['reservation_date'] = 'reservation_date';
return $columns;
}
}
add_filter( 'posts_clauses', 'manage_wp_posts_be_qe_pre_get_posts', 1, 2 );
if (!function_exists('manage_wp_posts_be_qe_pre_get_posts')) {
function manage_wp_posts_be_qe_pre_get_posts( $pieces, $query ) {
global $wpdb;
if ($query->is_main_query() && ( $orderby = $query->get('orderby') ) ) {
$order = strtoupper( $query->get('order') );
if ( !in_array( $order, array('ASC', 'DESC') ) ) {
$order = 'ASC';
switch ($orderby) {
case 'reservation_date':
$pieces[ 'join' ] .= " LEFT JOIN $wpdb->postmeta wp_rd ON wp_rd.post_id = {$wpdb->posts}.ID AND wp_rd.meta_key = 'reservation_date'";
$pieces[ 'orderby' ] = "STR_TO_DATE( wp_rd.meta_value,'%d.%m.%Y' ) $order, " . $pieces[ 'orderby' ];
break;
}
}
return $pieces;
}
}
}
This doesn't work, because I'm working with strings.
Luckily, my dates (when a person picks them), are already sorted lowest to highest date. They are stored in $custom['reservation_date'] array, where $custom = get_post_custom($post->ID). So I can get them like $custom['reservation_date'][0].
I can also separate the first date
preg_match('/^(.+?),/', $custom['reservation_date'][0], $matches);
If it's only one date, without the comma, I can then get them out like:
$first_date = (!empty($matches)) ? $matches[0] : $custom['reservation_date'][0];
Now what's bothering me is how to use this in my custom query? Currently the sorting is done on meta_value reservation_date (string). How do I make it so that I can sort based on these first dates?
Say I have dates like:
19.11.2015, 20.11.2015
28.11.2015
14.11.2015, 15.11.2015
13.11.2015
When I click to sort them in ascending order I'd like to get
13.11.2015
14.11.2015, 15.11.2015
19.11.2015, 20.11.2015
28.11.2015
And another click on the column will order them descending
28.11.2015
19.11.2015, 20.11.2015
14.11.2015, 15.11.2015
13.11.2015
Any help is appreciated.
You will not be able to sort in the WP Query as you have not stored the values in a way WordPress understands.
https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
You should store dates as YYYY-mm-dd.
Either change how the dates are stored or use PHP after the database request to sort.
// 1. if you change how "reservation_date" is stored in the db
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'reservation',
'meta_key' => 'reservation_date',
'orderby' => 'meta_value',
'order' => 'ASC'
));
// 2. if you choose to sort with PHP after pulling the data
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'reservation'
));
usort($posts, function ($post_a, $post_b) {
$post_a_custom = get_post_custom($post_a->ID);
$post_b_custom = get_post_custom($post_b->ID);
$post_a_date = DateTime::createFromFormat('d.m.Y', $post_a_custom['reservation_date'][0]);
$post_b_date = DateTime::createFromFormat('d.m.Y', $post_b_custom['reservation_date'][0]);
if ($post_a_date == $post_b_date) {
return 0;
} else if ($post_a_date > $post_b_date) {
return -1;
} else {
return 1;
}
});

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?

Categories