如何在定制器预览中使GET_THEME_MOD与AJAX一起工作

时间:2017-10-06 作者:michael

当AJAX在模板部件中调用get\\u theme\\u mod时,是否可以在自定义程序预览窗格中刷新后使其工作?

我有一个主题,可以加载滚动(无限滚动)上的帖子,除了没有在定制器预览中输出更新的主题mods外,其他一切都正常。当我点击保存按钮时,它只输出新的主题mods。

你知道如何在刷新后进行更新吗?

My control settings:


\'id\'        => \'show_caption\',
\'type\'      => \'select\',
\'section\'   => \'caption\',
\'transport\' => \'refresh\',
\'default\'   => \'top\',
\'choices\'   => array(
  \'top\'    => __( \'Top\', \'my-domain\' ),
  \'bottom\' => __( \'Bottom\', \'my-domain\' ),
),

InfiniteScroll.php:


class InfiniteScroll {

  private $query;

  public function __construct( WP_Query $query ) {
    $this->query = $query;
  }
  
  public function register() {
    add_action( \'wp_ajax_my_infinite_scroll\', array( $this, \'handleAjax\' ) );
    add_action( \'wp_ajax_nopriv_my_infinite_scroll\', array( $this, \'handleAjax\' ) );
    add_action( \'wp_enqueue_scripts\', array( $this, \'enqueueScripts\' ) );
  }

  public function getPosts() {
    ob_start();

    $this->query->query( $this->getData() );

    if ( $this->query->have_posts() ) {
      while ( $this->query->have_posts() ) {
        $this->query->the_post();
        get_template_part( \'template-parts/post/content\' );
      }
    }

    wp_reset_postdata();

    return ob_get_clean();
  }

  public function handleAjax() {
    if ( ! check_ajax_referer( \'infinite-scroll-ajax\', \'nonce\' ) ) {
      wp_die();
    }

    wp_send_json_success( $this->getPosts() );

    wp_die();
  }
  
  // ...

}

content.php:


echo get_theme_mod( \'show_caption\', \'top\' );

Ajax request before customize_save:

Before

1 个回复
最合适的回答,由SO网友:Weston Ruter 整理而成

WordPress 4.8.2中存在导致挂起的错误customized 在预览中不将更改注入Ajax请求。这已在4.9-alpha via中修复#42162. 然而,与此同时,您可以做一个变通方法来修改请求的url 逻辑如下:

// Workaround defect introduced in WordPress 4.8.2 where preview nonce is not included in request.
if ( \'undefined\' !== typeof _wpCustomizeSettings ) {
    urlParser = document.createElement( \'a\' );
    urlParser.href = url;
    urlParser.search += \'&customize_preview_nonce=\' + _wpCustomizeSettings.nonce.preview;
    url = urlParser.href;
}

结束