Extract domain from URL • Online NC
  • PHP

Extract domain from URL

Give indications on the URL by targeting only the domain name for a better user experience.
  • Modifié il y a 5 mois
  • Share

Improve the user experience by extracting only the domain name from a dynamic URL, to provide clear, readable and relevant information. This avoids the need to display complex links and builds user confidence by clearly showing the source.

Useful for :

Simplified display of links in a user interface
✅ Customization of URL rendering on preview cards
Highlighting of the original site in internal search results
✅ Facilitating content moderation with rapid recognition of the source site

1️⃣ Paste the code into your child theme’s functions.php file.

2️⃣ Edit your Elementor Template and add the button, action list or other widget where you want the link to appear.

3️⃣ Insert any Voxel dynamic tag containing an URL > Add a modifier > select Extract Domain > Save.

You should now see:
@post(permalink).extract_domain()

				
					// File : Extract domain from URL.php
add_filter( 'voxel/dynamic-data/modifiers', function( $modifiers ) {

	class Extract_Domain extends \Voxel\Dynamic_Data\Modifiers\Base_Modifier {
		public function get_label(): string {
			return 'Extract Domain';
		}

		public function get_key(): string {
			return 'extract_domain';
		}

		public function apply( string $value ) {
			if ( empty( $value ) ) {
				return null;
			}

			$parsed_url = parse_url( trim( $value ), PHP_URL_HOST );

			if ( $parsed_url ) {
				$parsed_url = preg_replace('/^www\./', '', $parsed_url);

				$domain_parts = explode('.', $parsed_url);
				$domain_count = count($domain_parts);

				$second_level_domains = ['co.uk', 'com.au', 'gov.uk', 'org.au'];

				$last_two = strtolower($domain_parts[$domain_count - 2] . '.' . $domain_parts[$domain_count - 1]);
				if ( $domain_count >= 3 && in_array( $last_two, $second_level_domains ) ) {
					$domain = $domain_parts[$domain_count - 3] . '.' . $last_two;
				} else {
					$domain = $domain_parts[$domain_count - 2] . '.' . $domain_parts[$domain_count - 1];
				}

				return $domain;
			}

			return null;
		}
	}

	$modifiers['extract_domain'] = \Extract_Domain::class;
	return $modifiers;
});


				
			
  • Kevin Ekelmans Presario