首页 > 解决方案 > 如何阻止部分刷新在 Wordpress Customizer 实时预览中删除分节符?

问题描述

我已将自己的设置添加到 Wordpress 定制器并进行设置,以便使用“postMessage”方法进行实时预览。除了当我编辑链接到段落文本的字段时,它几乎可以完美地工作,预览不会显示段落中的换行符。然而,这是暂时的,一旦关闭定制器或刷新页面,段落间隙就会重新出现。

我正在使用以下代码在 customizer.php 中定义 Customizer 部分:

// About Section Text
$wp_customize->add_setting( 'about__text' , array(
    'default'   => 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis, odit unde magnam dolores quasi voluptas, impedit a nam inventore atque eaque nobis possimus officiis deleniti quisquam animi deserunt ad ipsa sapiente illo?',
    'transport' => 'postMessage',
) );

// About Section Text (CONTROL)
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'about__text', array(
    'label'      => __( 'About Section Content:', 'mytheme' ),
    'section'    => 'edit__homepage--section',
    'settings'   => 'about__text',
    'priority'   => 3,
    'type'       => 'textarea'
) ) );

我使用以下代码在我的 index.php 文件中显示上述主题模块:

    <div class="about__text">
      <?php echo wpautop(get_theme_mod('about__text')); ?>
    </div>

这是我的jQuery:

( function( $ ) {
    wp.customize( 'about__text', function( value ) {
        value.bind( function( newVal ) {
            $( '.about__text' ).html( newVal );
        } );
    } );
} )( jQuery );

我尝试过使用不同的 jquery 对象,例如 text() 和 contents() ,但它们要么有相同的问题,要么根本不起作用。

有谁知道是否有办法让 javascript 预览来尊重段落样式?也许像 wpautop() 的 javascript 版本?

标签: javascriptphpjquerywordpresswordpress-theming

解决方案


您可以像这样使用选择性刷新。值在服务器端呈现,因此无需额外的 JS。并且由于仅刷新选定的包装器元素,因此它比定制器中的整页重新加载更有效。在以下示例中,仅.about__text刷新内容。由于渲染是在服务器端完成的,因此无需寻找 wpautop 功能的 JS 替代方案。我相信这将是问题中提到的问题的一种替代方法。

function wpso_customize_register( $wp_customize ) {
    $wp_customize->selective_refresh->add_partial(
        'about__text',
        array(
            'selector'        => '.about__text',
            'render_callback' => function(){
                echo wp_kses_post( wpautop( get_theme_mod('about__text') ) );
            },
        )
    );
}
add_action( 'customize_register', 'wpso_customize_register' );

推荐阅读