简体   繁体   中英

wp_editor always convert <br> to <p>&nbsp;</p>

I create a custom plugin that has a wp_editor on the admin, now when I put some html tags in the editor in Text view tab like <br> and click on the Visual tab.. the <br> converts into <p>&nbsp;</p> when I back to Text tab.

this is my php code:

$html_value = '<h1>test</h1><br> ....';
$settings = array( 'textarea_name' => 'al_srms_fileform_content', 'media_buttons' => true, 'wpautop' => false );
wp_editor($html_value, 'mycustomeditor0pdf', $settings );

this is what happening: I put <br> tag by Text tab. 在此处输入图片说明

I click Visual to display the result. 在此处输入图片说明

I click back the Text tab and the <br> is gone and replaced by <p>&nbsp;</p> 在此处输入图片说明

is there a way the when putting a <br> it remains <br> ?

The problem you are running into is the result of the wpautop filter function in your Themes functions.php file.

To disable this function add the following to lines to your functions.php file located in your themes directory:

remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

Reference: https://codex.wordpress.org/Function_Reference/wpautop (Wordpress Codex)

I hope this will assist you. You don't need to install the suggested plug-in, though. Just add this mini plugin and you're set:

<?php
defined( 'ABSPATH' ) OR exit;
/* Plugin Name: TinyMCE break instead of paragraph */
function mytheme_tinymce_settings( $tinymce_init_settings ) {
    $tinymce_init_settings['forced_root_block'] = false;
    return $tinymce_init_settings;
}
add_filter( 'tiny_mce_before_init', 'mytheme_tinymce_settings' );

Now when you press enter, <br> tag will be inserted instead of creating new paragraph. But beware, if you create two consecutive newlines, the text will still be split to paragraph as a result of wpautop filter applied to your post content. You need to remove this filter first and create a new filter that will replace all newlines with <br> tags. Add something like this to your functions.php to display the <br> tags in your template:

remove_filter ( 'the_content', 'wpautop' );
add_filter ( 'the_content', 'add_newlines_to_post_content' );
function add_newlines_to_post_content( $content ) {
    return nl2br( $content );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM