Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Created September 23, 2023 11:45
Show Gist options
  • Save doubleedesign/ddbfec2e9618c072eaa0f54d2bdc0d57 to your computer and use it in GitHub Desktop.
Save doubleedesign/ddbfec2e9618c072eaa0f54d2bdc0d57 to your computer and use it in GitHub Desktop.
Alter output of WordPress TinyMCE field content
<?php
/**
* Add spans and icons to buttons added by applying custom link classes in the WYSIWYG editor
* @param $content
* @return string
*/
function wapr_add_icons_to_buttons($content): string {
return preg_replace_callback('/<a class="btn btn--(?:.*) btn--icon" href="(?:.*)">(.*)<\/a>/', function($match) {
return str_replace($match[1], '<span>'.$match[1].'</span><i class="fa-regular fa-chevron-right"></i>', $match[0]);
}, $content);
}
add_filter('the_content', 'wapr_add_icons_to_buttons');
add_filter('acf_the_content', 'wapr_add_icons_to_buttons');
<?php
/**
* Add custom formats menu to TinyMCE
* @param $buttons
* @return array
*/
function wapr_add_mce_styleselect($buttons): array {
array_unshift($buttons, 'styleselect');
return $buttons;
}
add_filter('mce_buttons_2', 'wapr_add_mce_styleselect');
/**
* Populate custom formats menu in TinyMCE
* Notes: 'selector' for block-level element that format is applied to; 'inline' to add wrapping tag e.g.'span'
* Using 'attributes' to apply the classes instead of 'class' ensures previous classes are replaced rather than added to
* @param $init_array
*
* @return array
*/
function wapr_add_mce_styles($init_array): array {
$style_formats = array(
array(
'title' => 'Lead paragraph',
'block' => 'p',
'classes' => 'lead'
),
array(
'title' => 'Button (primary)',
'selector' => 'a',
'attributes' => array('class' => 'btn btn--primary btn--icon')
),
array(
'title' => 'Button (secondary)',
'selector' => 'a',
'attributes' => array('class' => 'btn btn--secondary btn--icon')
),
array(
'title' => 'Button (accent)',
'selector' => 'a',
'attributes' => array('class' => 'btn btn--accent btn--icon')
)
);
$init_array['style_formats'] = json_encode($style_formats);
return $init_array;
}
add_filter('tiny_mce_before_init', 'wapr_add_mce_styles');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment