Home > database >  Count posts that include the current users email in a meta field
Count posts that include the current users email in a meta field

Time:01-14

I was hoping someone could please assist with my below code. I have a field called pds_project_manager and it contains the email address of my users assigned to projects(posts), I am wanting to count the number of posts that have the field with the current users email in it. The below code works, but if there is more than just the current users email address in the field pds_project_manager it ignores it and does note count it. The field will often have multiple email addresses in it.

$current_user = wp_get_current_user();
$display_name = $current_user->display_name;

$args_pm = array(//number of posts by pm
  'posts_per_page' => -1,
  'post_type' => 'project',
  'meta_query' => array(
            'relation' => 'AND',
    array(
        'key'   => 'status',
        'value' => '1'
    ),
    array(
        'key'   => 'pds_project_manager',
        'value' => $current_user->user_email,
     )
          )
);
$posts_pm = get_posts($args_pm);
$pm_count = count($posts_pm);//number of posts by pm

echo "$display_name's Active Projects: $pm_count";

CodePudding user response:

Assuming that you have a serialized array represented as a string and stored in Database for your pds_project_manager field, use LIKE in your query like this:

...
array(
        'key'   => 'pds_project_manager',
        'value' => $current_user->user_email,
        'compare' => 'LIKE'
     )
...

There is a good article why not to use LIKE or not to store serialized data in Database, in case you want to know alternatives: https://wordpress.stackexchange.com/questions/16709/meta-query-with-meta-values-as-serialize-arrays

CodePudding user response:

I have tweaked it a bit, you can use the 'meta_query' parameter in the 'get_posts' function, and use the 'compare' parameter set to 'LIKE' to match the current user's email address in the field which contains multiple emails. Please try this :

$current_user = wp_get_current_user();
$display_name = $current_user->display_name;

$args_pm = array(
  'posts_per_page' => -1,
  'post_type' => 'project',
  'meta_query' => array(
            'relation' => 'AND',
    array(
        'key'   => 'status',
        'value' => '1'
    ),
    array(
        'key' => 'pds_project_manager',
        'value' => $current_user->user_email,
        'compare' => 'LIKE'
    )
  )
);
$posts_pm = get_posts($args_pm);
$pm_count = count($posts_pm);

echo "$display_name's Active Projects: $pm_count";
  • Related