0

I use wp-query and I need to display posts by author, using author id.

This is the serialized array:

a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";}

This array includes the author's id so my question how can use wp-query 'author' or 'author__in' by using a serialized array?

Like this:

$first_post_ids = get_posts( array(
    'fields'         => 'ids',
    'post_type'      => 'the_posts',
    'author__in'      => get_user_meta($current_user->ID, 'following_users', true)
));
1
  • What is 'post_type' => 'the_posts'? The correct post type for normal posts is post. Have you registered a custom post type called the_posts? Commented Dec 21, 2017 at 0:11

1 Answer 1

2

You need to unserialize() if its serialized string.

In your case from what I understand you store the array in the user_meta so its serialize it when you store it. but it will unserialize it when you use the get_user_meta so you dont need to unserialize()

Your code seems fine.

$author_in = get_user_meta($current_user->ID, 'following_users', true);
$first_post_ids = get_posts( array(
    'fields'         => 'ids',
    'post_type'      => 'the_posts',
    'author__in'      => $author_in
));
6
  • Sorry it's not wokring i get a php error: Warning: unserialize() expects parameter 1 to be string, Hope you can help me. Commented Dec 20, 2017 at 21:33
  • get_user_meta($current_user->ID, 'following_users', true) This return you serialized string? Commented Dec 20, 2017 at 21:34
  • If you mean if i print it like this: echo get_user_meta($current_user->ID, 'following_users', true); it's print 'Array' if i add your code it's give me a php error. Commented Dec 20, 2017 at 21:36
  • So from where you got the serialized data? add this array to your question Commented Dec 20, 2017 at 21:37
  • I have a follow - unfollow users system each user has following_users meta when the user follows another user a serialized array is stored into the database like the array that I put in the question, so I need to get the posts of users that I follow, Hope you understand me. Commented Dec 20, 2017 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.