the-seo-framework icon indicating copy to clipboard operation
the-seo-framework copied to clipboard

Combine post excerpt and content when parsing description

Open sybrew opened this issue 11 months ago • 1 comments

Sometimes, the excerpt produces no usable content for a description. Then, the user will be left without a generated description.

To mitigate this issue, we could also consider processing the content. However, this requires a second cycle of the description generator, which introduces unwanted complexity and performance degradation.

It'd be much more feasible to append the content to the description during the "getting" phase. Then, we can parse them together as one big content field.

We should consider making this optional, for it can affect existing descriptions. Moreover, creating an unusable excerpt is rare — not many people put HTML in the excerpt.

sybrew avatar Feb 04 '25 12:02 sybrew

Here's a snippet to test this feature.

It will slow down generation time because the excerpt must be reprocessed. I have not implemented a hook when the excerpt gets fetched, but only thereafter.

However, I put in a few safeguards to prevent some unnecessary reprocessing. When this feature gets implemented in the plugin, reprocessing won't occur.

add_filter(
	'the_seo_framework_get_excerpt',
	/**
	 * Filters the excerpt.
	 *
	 * @param string     $excerpt The obtained excerpt.
	 * @param array|null $args    The query arguments. Accepts 'id', 'tax', 'pta', and 'uid'.
	 *                            Leave null to autodetermine query.
	 */
	function( $excerpt, $args ) {

		// If there already wasn't an excerpt, we sure won't be getting another one right now.
		if ( empty( $excerpt ) )
			return $excerpt;

		if ( isset( $args ) ) {
			The_SEO_Framework\normalize_generation_args( $args );
			$is_single = 'single' === The_SEO_Framework\get_query_type_from_args( $args );
		} else {
			$is_single = tsf()->query()->is_singular();
		}

		if ( ! empty( $is_single ) ) {
			$tsf_post = tsf()->data()->post();
			$_excerpt = $tsf_post->get_excerpt();

			// Only append the content if there's an excerpt -- we would've already defaulted to the content otherwise.
			if ( $_excerpt ) {
				$content = $tsf_post->get_content();

				if ( $content ) {
					$tsf_html = tsf()->format()->html();

					$excerpt = $tsf_html->strip_paragraph_urls( $tsf_html->strip_newline_urls( "{$_excerpt} {$content}" ) );

					if ( $excerpt )
						$excerpt = $tsf_html->extract_content( $excerpt );
				}
			}
		}

		return $excerpt;
	},
	10,
	2,
);

sybrew avatar Feb 11 '25 16:02 sybrew