Added a description with restricted character count to Listings block

Thought i should share this as it may be helpful…

I added a description to the listings block with a restricted character count using the PHP snippet below:-

add_filter(
	'hivepress/v1/templates/listing_view_block/blocks',
	function( $blocks, $template ) {
		$listing = $template->get_context('listing');
		
		if ( $listing ) {
			$original_description = $listing->get_description();
			$character_limit      = 150; // Set your character limit here
			$display_description  = ''; // Initialize an empty string for the description to be displayed

			if ( ! empty( $original_description ) ) { // Check if the original description is not empty
				// Check if mbstring extension is available, if not, use strlen and substr
				if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) {
					if ( mb_strlen( $original_description ) > $character_limit ) {
						$display_description = mb_substr( $original_description, 0, $character_limit ) . '...';
					} else {
						$display_description = $original_description;
					}
				} else {
					// Fallback for when mbstring is not enabled
					if ( strlen( $original_description ) > $character_limit ) {
						$display_description = substr( $original_description, 0, $character_limit ) . '...';
					} else {
						$display_description = $original_description;
					}
				}
			}

			// Only add the block if there's content to display
			if ( ! empty( $display_description ) ) {
				$blocks = hivepress()->helper->merge_trees(
					[ 'blocks' => $blocks ],
					[
						'blocks' => [
							'listing_details_primary' => [
								'blocks' => [
									'custom_listing_block_description' => [
										'type'    => 'content',
										'content' => '<p>' . esc_html( $display_description ) . '</p>',
										'_order'  => 6,
									],
								],
							],
						],
					]
				)['blocks'];
			}
		}
		
		return $blocks;
	},
	1000,
	2
);
1 Like

Hi @otiscreative,

Many thanks for sharing this! I’m sure the community will make good use of it.

Cheers,
Chris :victory_hand:

Hi,

Thank you for your solution, it will be useful for our community.