Browse Source

SEO: build meta description without rendering dynamic blocks

dw_seo_description ran the full the_content filter to build the excerpt, which
re-rendered the Gravity Forms block during wp_head (wasteful + tripped a GF
Post-Category PHP 8 warning). New dw_seo_excerpt_from_content strips dynamic
blocks via excerpt_remove_blocks before do_blocks.
windhamdavid 6 days ago
parent
commit
59a3fa378d
1 changed files with 29 additions and 4 deletions
  1. 29 4
      inc/seo.php

+ 29 - 4
inc/seo.php

@@ -26,15 +26,40 @@ function dw_seo_favicon() {
 	echo "<link rel=\"apple-touch-icon\" href=\"/apple-touch-icon.png\">\n";
 }
 
+/** Plain-text description from a post's content WITHOUT rendering dynamic blocks.
+ *
+ * The old path (dw_good_excerpt) ran the full the_content filter here, which re-renders any
+ * embedded Gravity Forms block during wp_head — wasteful, and it trips a GF Post-Category
+ * warning on the guestbook/contact pages. excerpt_remove_blocks() drops the form (and other
+ * dynamic blocks) first, so only static text blocks get rendered. Returns a trimmed string. */
+function dw_seo_excerpt_from_content( $id ) {
+	$post = get_post( $id );
+	if ( ! $post ) {
+		return '';
+	}
+	$text = trim( (string) $post->post_excerpt );
+	if ( $text === '' ) {
+		$content = (string) $post->post_content;
+		if ( function_exists( 'excerpt_remove_blocks' ) ) {
+			$content = excerpt_remove_blocks( $content ); // strip forms + other dynamic blocks
+		}
+		$text = do_blocks( $content );
+	}
+	$text = wp_strip_all_tags( strip_shortcodes( $text ) );
+	$text = trim( preg_replace( '/\s+/', ' ', $text ) );
+	if ( mb_strlen( $text ) > 300 ) {
+		$text = rtrim( mb_substr( $text, 0, 300 ) ) . '…';
+	}
+	return $text;
+}
+
 /** Page description: post meta_desc field -> excerpt -> site tagline. Returns a string. */
 function dw_seo_description() {
 	if ( is_singular() ) {
 		$id = get_queried_object_id();
 		$d  = trim( (string) get_post_meta( $id, 'meta_desc', true ) );
-		if ( $d === '' && function_exists( 'dw_good_excerpt' ) ) {
-			ob_start();
-			dw_good_excerpt( 300 );
-			$d = trim( (string) ob_get_clean() );
+		if ( $d === '' ) {
+			$d = dw_seo_excerpt_from_content( $id );
 		}
 		if ( $d !== '' ) {
 			return $d;