diff --git a/opengraph.php b/opengraph.php index 35c56ae..ae83540 100644 --- a/opengraph.php +++ b/opengraph.php @@ -618,7 +618,7 @@ function opengraph_default_description( $description = '', $length = 55 ) { } elseif ( ! empty( $post->post_excerpt ) ) { $description = $post->post_excerpt; } else { - $description = $post->post_content; + $description = opengraph_page_teaser( $post ); } } elseif ( is_author() ) { $id = get_queried_object_id(); @@ -639,6 +639,27 @@ function opengraph_default_description( $description = '', $length = 55 ) { } +/** + * Get the content of the current page of a post, cut at the `` tag. + * + * Splits the content at `` the same way core does for + * `get_the_content()`, so every page of a multipage post gets its own + * description. If the page has a `` tag, only the teaser before + * it is returned. + * + * @param WP_Post $post The post. + * + * @return string The content. + */ +function opengraph_page_teaser( $post ) { + $elements = generate_postdata( $post ); + $page = min( max( 1, (int) $elements['page'] ), count( $elements['pages'] ) ); + $content = $elements['pages'][ $page - 1 ]; + + return get_extended( $content )['main']; +} + + /** * Default locale property, using the WordPress locale. * diff --git a/tests/phpunit/tests/class-test-opengraph.php b/tests/phpunit/tests/class-test-opengraph.php index 5254aa3..1b12395 100644 --- a/tests/phpunit/tests/class-test-opengraph.php +++ b/tests/phpunit/tests/class-test-opengraph.php @@ -95,6 +95,48 @@ public function test_description_from_content() { $this->assertSame( implode( ' ', array_fill( 0, 55, 'word' ) ) . ' [...]', $metadata['og:description'] ); } + /** + * Test the description of a multipage post is taken from the current page. + * + * @see https://github.com/pfefferle/wordpress-opengraph/issues/9 + * + * @covers ::opengraph_default_description + * @covers ::opengraph_page_teaser + */ + public function test_description_from_multipage_content() { + $post_id = self::factory()->post->create( + array( + 'post_content' => '

First page

Second page

', + 'post_excerpt' => '', + ) + ); + + $metadata = $this->metadata_for( get_permalink( $post_id ) ); + $this->assertSame( 'First page', $metadata['og:description'] ); + + $metadata = $this->metadata_for( add_query_arg( 'page', 2, get_permalink( $post_id ) ) ); + $this->assertSame( 'Second page', $metadata['og:description'] ); + } + + /** + * Test the description is cut at the more tag. + * + * @covers ::opengraph_default_description + * @covers ::opengraph_page_teaser + */ + public function test_description_from_teaser() { + $post_id = self::factory()->post->create( + array( + 'post_content' => '

Teaser

Rest

', + 'post_excerpt' => '', + ) + ); + + $metadata = $this->metadata_for( get_permalink( $post_id ) ); + + $this->assertSame( 'Teaser', $metadata['og:description'] ); + } + /** * Test a password protected post exposes neither its content nor its images. *