The get_shortcode_atts_regex WordPress PHP function retrieves the shortcode attributes regex.
Usage
$pattern = get_shortcode_atts_regex();
Parameters
- None
More information
See WordPress Developer Resources: get_shortcode_atts_regex
Examples
Match Shortcode Attributes
Retrieve the regex pattern for matching shortcode attributes and use it to match them in a string.
// The shortcode string $shortcode_str = '[custom_shortcode attribute1="value1" attribute2="value2"]'; // Get the regex pattern for shortcode attributes $pattern = get_shortcode_atts_regex(); // Match the shortcode attributes preg_match_all("/$pattern/", $shortcode_str, $matches); // Print the matched attributes print_r($matches);
Parse Attributes from a Shortcode
Parse attributes from a shortcode string and store them in an associative array.
// The shortcode string $shortcode_str = '[custom_shortcode attribute1="value1" attribute2="value2"]'; // Get the regex pattern for shortcode attributes $pattern = get_shortcode_atts_regex(); // Match the shortcode attributes preg_match_all("/$pattern/", $shortcode_str, $matches); // Parse the attributes $attributes = array(); foreach ($matches[0] as $match) { list($attribute, $value) = explode('=', $match); $attributes[$attribute] = trim($value, '"'); } // Print the attributes array print_r($attributes);
Modify Shortcode Attributes
Retrieve shortcode attributes, modify them, and rebuild the shortcode string.
// The shortcode string $shortcode_str = '[custom_shortcode attribute1="value1" attribute2="value2"]'; // Get the regex pattern for shortcode attributes $pattern = get_shortcode_atts_regex(); // Match the shortcode attributes preg_match_all("/$pattern/", $shortcode_str, $matches); // Modify the attributes $new_attributes = array(); foreach ($matches[0] as $match) { list($attribute, $value) = explode('=', $match); $new_value = $attribute === 'attribute1' ? '"modified_value"' : $value; $new_attributes[] = "{$attribute}={$new_value}"; } // Rebuild the shortcode string $new_shortcode_str = '[custom_shortcode ' . implode(' ', $new_attributes) . ']'; // Print the new shortcode string echo $new_shortcode_str;
Remove Specific Attribute
Remove a specific attribute from a shortcode string.
// The shortcode string $shortcode_str = '[custom_shortcode attribute1="value1" attribute2="value2"]'; // Get the regex pattern for shortcode attributes $pattern = get_shortcode_atts_regex(); // Match the shortcode attributes preg_match_all("/$pattern/", $shortcode_str, $matches); // Remove the attribute2 $new_attributes = array(); foreach ($matches[0] as $match) { list($attribute, $value) = explode('=', $match); if ($attribute !== 'attribute2') { $new_attributes[] = "{$attribute}={$value}"; } } // Rebuild the shortcode string $new_shortcode_str = '[custom_shortcode ' . implode(' ', $new_attributes) . ']'; // Print the new shortcode string echo $new_shortcode_str;