Join the Voxel Guide Community!

Get Involved

Add UTM dynamic tag mod

Description/Instructions

Add this snippet to your child theme’s functions.php file to make this mod appear under the dynamic tags mod section in Voxel 1.5.

Instructions

This snippet into your functions file of your child theme.

// ADD UTM parameters to a URL modifier - VOXEL 1.5
add_action('voxel/dynamic-data/modifiers', function( $modifiers ) {
class Add_UTM_Parameters extends \Voxel\Dynamic_Data\Modifiers\Base_Modifier {
public function get_label(): string {
return _x('Add UTM Parameters', 'modifiers', 'voxel-backend');
}
public function get_key(): string {
return 'add_utm_parameters';
}
public function expects(): array {
return [ static::TYPE_STRING ];
}
protected function define_args(): void {
$this->define_arg([
'type' => 'text',
'label' => _x('UTM Source', 'modifiers', 'voxel-backend'),
]);
$this->define_arg([
'type' => 'text',
'label' => _x('UTM Medium', 'modifiers', 'voxel-backend'),
]);
$this->define_arg([
'type' => 'text',
'label' => _x('UTM Campaign', 'modifiers', 'voxel-backend'),
]);
}
public function apply( string $value ) {
// Validate the input value as a valid URL
if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
return esc_url( $value );
}
// Get UTM parameters from arguments
$utm_source = $this->get_arg(0) ? urlencode($this->get_arg(0)) : '';
$utm_medium = $this->get_arg(1) ? urlencode($this->get_arg(1)) : '';
$utm_campaign = $this->get_arg(2) ? urlencode($this->get_arg(2)) : '';
// Build the UTM query string
$utm_query = [];
if ( $utm_source ) {
$utm_query[] = 'utm_source=' . $utm_source;
}
if ( $utm_medium ) {
$utm_query[] = 'utm_medium=' . $utm_medium;
}
if ( $utm_campaign ) {
$utm_query[] = 'utm_campaign=' . $utm_campaign;
}
// If no UTM parameters are provided, return the original URL
if ( empty( $utm_query ) ) {
return esc_url( $value );
}
// Append UTM parameters to the URL
$delimiter = strpos( $value, '?' ) === false ? '?' : '&';
$modified_url = $value . $delimiter . implode( '&', $utm_query );
// Return the modified URL
return esc_url( $modified_url );
}
}
$modifiers['add_utm_parameters'] = Add_UTM_Parameters::class;
return $modifiers;
});

  • PHP
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24