15 de dezembro, 2016 | 0 Comments | Marcelo Torres

Habilitando o editor TinyMCE no campo de resumo (excerpt) do WordPress sem plugin

Por muitas vezes eu precisei usar HTML no campo de resumo padrão do WordPress, deixar um campo editável com HTML é muito ruim em termos de usabilidade para usuários leigos, então a melhor solução seria usar o mesmo editor que se usa no campo de conteúdo, não é? Abaixo segue um snippet que soluciona isso sem precisar usar um plugin:

O Snippet

<?php
add_action( 'add_meta_boxes', array ( 'tinyMCE_for_excerpt', 'switch_boxes' ) );
/**
* Replaces the default excerpt editor with TinyMCE.
*/
class tinyMCE_for_excerpt
{
/**
* Replaces the meta boxes.
*
* @return void
*/
public static function switch_boxes()
{
if ( ! post_type_supports( $GLOBALS['post']->post_type, 'excerpt' ) )
{
return;
}
remove_meta_box(
'postexcerpt' // ID
, '' // Screen, empty to support all post types
, 'normal' // Context
);
add_meta_box(
'postexcerpt2' // Reusing just 'postexcerpt' doesn't work.
, __( 'Excerpt' ) // Title
, array ( __CLASS__, 'show' ) // Display function
, null // Screen, we use all screens with meta boxes.
, 'normal' // Context
, 'core' // Priority
);
}
/**
* Output for the meta box.
*
* @param object $post
* @return void
*/
public static function show( $post )
{
?>
<label class="screen-reader-text" for="excerpt"><?php
_e( 'Excerpt' )
?></label>
<?php
// We use the default name, 'excerpt', so we don’t have to care about
// saving, other filters etc.
wp_editor(
self::unescape( $post->post_excerpt ),
'excerpt',
array (
'textarea_rows' => 15
, 'media_buttons' => FALSE
, 'teeny' => TRUE
, 'tinymce' => TRUE
)
);
}
/**
* The excerpt is escaped usually. This breaks the HTML editor.
*
* @param string $str
* @return string
*/
public static function unescape( $str )
{
return str_replace(
array ( '&lt;', '&gt;', '&quot;', '&amp;', '&nbsp;', '&amp;nbsp;' )
, array ( '<', '>', '"', '&', ' ', ' ' )
, $str
);
}
}

Esse é o resultado

TinyMCE no campo de resumo (excerpt) no WordPress sem plugin

Basta colocar no seu functions.php para funcionar.

Até a próxima!

Última atualização: 24 janeiro, 2017 às 8:18 pm