0

I have ten posts in my query that belong in three categories: cat-a,cat-b,cat-c.

I'm looking for a way to store $posts_ids from each category into a variable.

Say for example, if three posts are in "category-a" then store those posts_ids in a variable.

Cat-a
Post 1 ID->435
Post 2 ID->477
Post 3 ID->488
$idcata = 435,477,488

Cat-b
Post 1 ID->87
Post 2 ID->32
$idcatb = 87,32

Cat-c
Post 1 ID->876
$idcatc = 876

Thanks

2

For getting the posts related to each category you need to use get_posts( $args ) function and in $args you can add your category_id

$args = array ( 
    'post_type'   => 'post',    
    'category'    => $cat_ID,
    'post_status' => 'publish',
);

$my_posts = get_posts( $args ); // return array of posts

// storing all post ID in an array
foreach( $my_posts as $my_post ) {
    $post_cat_name[] = $my_post['ID'];
}

So in $post_cat_name it will store all the post id related to your $cat_ID

If you want these to be done for 3 $cat_id, then you can loop the above code for 3 $cat_id and you can use $post_cat_name array as 2D array.

  • PHP Fatal error: Cannot use object of type WP_Post as array. Error is in area: // storing all post ID in an array foreach( $my_posts as $my_post ) { $post_cat_name[] = $my_post['ID']; } – Gregory Schultz Jul 27 '16 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.