Skip Navigation

[Resolved] Custom shortcode to remove text after a comma

This support ticket is created 3 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

This topic contains 2 replies, has 2 voices.

Last updated by nateW 3 years, 1 month ago.

Assisted by: Shane.

Author
Posts
#2310525

Hi, how can I create a custom shortcode to remove all text after a comma from a text field? I'm outputting the custom post title, which is an address (for example 123 Main Street, City, State, Zip code), but on a list view on another page, I want to output just 123 Main Street. Thanks in advance for the help!

#2310669

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Nate,

Thank you for getting in touch.

The best way to resolve this is as you say using a custom shortcode to trim the text. In this case we will make use of the explode function to convert the string to an array using the comma as a delimiter.

What this does is that we will get an array of text where we can trim off the specific text we want. In your case it will be the first segment.

I've crafted a custom shortcode below that should help you with this.
Add the following to your Toolset custom code settings at Toolset->Settings->Custom Code. Once you've done this please ensure that you've activated it.

// Add Shortcode
function wp_trim_text( $atts , $content = null ) {

	// Attributes
	$atts = shortcode_atts(
		array(
			'text' => '',
			'position' => '',
		),
		$atts
	);

	$arr = explode(",",$atts['text']);
	return $arr[$atts['position']];

}
add_shortcode( 'wp_trim_text', 'wp_trim_text' );

To use the shortcode here is an example.

[wp_trim_text text="someshortcode" position="0"]

Replace "someshortcode" with the actual shortcode. Now you see I have 0 for the position. This will return the first value in the array.

If we were to input "23 Main Street, City, State, Zip code" it will return 23 Main Street

Please let me know if this helps.
Thanks,
Shane

#2312335

This is perfect, thank you so much! My issue is resolved now.