| | 499 | |
| | 500 | /** |
| | 501 | * @ticket 22448 |
| | 502 | */ |
| | 503 | function test_the_posts_filter() { |
| | 504 | // Create posts and clear their caches. |
| | 505 | $post_ids = $this->factory->post->create_many( 10 ); |
| | 506 | foreach ( $post_ids as $post_id ) |
| | 507 | clean_post_cache( $post_id ); |
| | 508 | |
| | 509 | add_filter( 'the_posts', array( $this, 'the_posts_filter' ) ); |
| | 510 | |
| | 511 | $query = new WP_Query( array( |
| | 512 | 'post_type' => 'post', |
| | 513 | 'posts_per_page' => 5, |
| | 514 | ) ); |
| | 515 | |
| | 516 | // Sixth post added in filter |
| | 517 | $this->assertEquals( 6, count( $query->posts ) ); |
| | 518 | $this->assertEquals( 6, $query->post_count ); |
| | 519 | |
| | 520 | foreach ( $query->posts as $post ) { |
| | 521 | |
| | 522 | // posts are WP_Post objects |
| | 523 | $this->assertTrue( is_a( $post, 'WP_Post' ) ); |
| | 524 | |
| | 525 | // filters are raw |
| | 526 | $this->assertEquals( 'raw', $post->filter ); |
| | 527 | |
| | 528 | // custom data added in the_posts filter is preserved |
| | 529 | $this->assertEquals( array( $post->ID, 'custom data' ), $post->custom_data ); |
| | 530 | } |
| | 531 | |
| | 532 | remove_filter( 'the_posts', array( $this, 'the_posts_filter' ) ); |
| | 533 | } |
| | 534 | |
| | 535 | /** |
| | 536 | * Use with the_posts filter, appends a post and adds some custom data. |
| | 537 | */ |
| | 538 | function the_posts_filter( $posts ) { |
| | 539 | $posts[] = clone $posts[0]; |
| | 540 | |
| | 541 | // Add some custom data to each post. |
| | 542 | foreach ( $posts as $key => $post ) |
| | 543 | $posts[ $key ]->custom_data = array( $post->ID, 'custom data' ); |
| | 544 | |
| | 545 | return $posts; |
| | 546 | } |