如何在自定义窗口小部件类中将数据传递给Java脚本

时间:2020-04-05 作者:sialfa

我有一个自定义小部件,用户可以在其中在<input> 领域它工作正常,但我需要从php 并将其传递给javascript 与我的小部件插件一起排队的文件。我正在测试wp_localize_script 但它不会工作,如果这样做,我将无法访问传递的数据console.log. 如何解决此问题,是否可以从php 至插件js 文件

class InstagramFeedWidget extends WP_Widget {

  public $url;

  public function __construct()
  {
    parent::__construct(
      \'instagram-widget\',
      \'Instagram feed\',
      array(
        \'description\' => \'\'
      )
    );
    add_action( \'widgets_init\', array($this, \'init\') );
    add_action( \'wp_enqueue_scripts\', array($this, \'initScripts\' ) );
  }

  public function init()
  {
    register_sidebar(
      array(
        \'name\'        =>  \'Instagram feed\',
        \'id\'          =>  \'ig-feed\',
        \'description\' =>  \'Instagram feed widget\',
      )
    );
    register_widget( \'InstagramFeedWidget\' );
  }

  public function widget( $args, $instance )
  {
    $this->url = \'https://instagram.com/\'.$instance[\'username\'].\'?__a=1\';


    // $ch = curl_init();
    // curl_setopt( $ch, CURLOPT_URL, $url );
    // curl_setopt( $ch, CURLOPT_HTTPHEADER, array(\'Accept: application/json\') );
    // curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    // curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    // $feed = curl_exec($ch);
    // curl_close($ch);
    // $data = json_decode( $feed , true);
    // ob_start();
    ?>
    <!-- <div class="jumbotron jumbotron-fluid ig-feed">
      <div class="container">
        <div class="row">
          <div class="col-sm-12 col-md-12 col-lg-12"> -->
            <div class="swiper-container swiper-feed" id="ig-feed">
              <div class="swiper-wrapper">
                <img class="swiper-slide feed-img" src="">
            <?php
              // foreach( $data[\'graphql\'][\'user\'][\'edge_owner_to_timeline_media\'][\'edges\'] as $node ){
              //   foreach( $node as $img ){
              //     echo \'<div class="swiper-slide feed-img" style="background-image:url(\'.$img[\'display_url\'].\');"></div>\';
              //   }
              // }
            ?>
              </div>
            <div class="swiper-button-prev "></div>
            <div class="swiper-button-next"></div>
            </div>
          <!-- </div> -->
        <!-- </div>
      </div>
    </div> -->
    <?php
    echo ob_get_clean();
  }

  public function form( $instance )
  {
    $username = isset( $instance[\'username\'] ) ? esc_attr( $instance[\'username\'] ) : \'\';
    ?>
    <p>
    <label for="<?php esc_attr( $this->get_field_id(\'username\') ); ?>"><?php _e(\'Username\'); ?></label>
    <input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id(\'username\') ); ?>" name="<?php echo esc_attr( $this->get_field_name(\'username\') ); ?>" value="<?php echo esc_attr($username); ?>">
    </p>
    <?php
  }

  public function update( $new_instance, $old_instance )
  {
    $instance = $old_instance;

    $instance[\'username\'] = esc_attr($new_instance[\'username\']);

    return $instance;
  }

  public function initScripts()
  {

    wp_enqueue_style(\'instagram-widget\', plugins_url( \'instagram-widget.min.css\', __FILE__), array(\'swiper\'), null);
    wp_enqueue_script(\'instagram-widget-js\', plugins_url( \'instagram-widget.js\', __FILE__), array(\'swiper\'), null);
    wp_localize_script( \'instagram-widjet-js\', \'igfeed\', array( \'profile_url\' => $this->url )  );
  }

}

new InstagramFeedWidget;

// instagram-widjet.js file
(function($){
  $(document).ready(function(){
    let igfeed = igfeed.profile_url;
    console.log(igfeed);

    const igFeed = new Vue({
      el: \'#ig-feed\',
      data: {
        feedImg: []
      },
      mounted: function(){
        axios.get(igfeed.profile_url).then( (response) => {
          console.log(response);
        });
      },
      methods: {

      }
    });

    const feedSwiper = new Swiper(\'.swiper-feed\', {
      slidesPerView: 4,
      spaceBetween: 50,
      slidesPerGroup: 4,
      loop: true,
      autoplay: {
        delay: 5000
      },
      //loopFillGroupWithBlank: true,
      navigation: {
        nextEl: \'.swiper-button-next\',
        prevEl: \'.swiper-button-prev\',
      },
    });


  });
}(jQuery));

1 个回复
SO网友:cjbj

这是一个时间问题,您可以从hook order. 当你到达dynamic_sidebar 在前端执行小部件代码的函数,您已经通过widgets_initwp_enqueue_scripts 挂钩(在dynamic_sidebar 钩子位于同名函数中)。您不能将小部件中的脚本排队。

有两种方法可以解决这个问题:

编写一个函数,直接从数据库访问小部件数据(这是一个多维数组,您可以使用get_option(sidebars_widgets). 您可以将此函数绑定到wp_enqueue_scripts hook.wp_footer 钩子,在执行小部件代码时仍然可用wp_localize_script 将在任何地方工作,因为它只是在调用时打印变量。

相关推荐

如何在wp_post`post_content`中剥离javascript

我的网站正在遭受SQL注入攻击,重定向到广告网站dolohen[dot]com。我需要在提供javascript之前去掉它。Is there a filter I can add or update to remove everything between tags in wp_posts post_content我不熟悉wordpress编程,但不熟悉sql和数据库。这有点让人困惑,因为有些人想在帖子中加入javascript,但却不能。然而,这些SQL注入器似乎是随心所欲的!ThanksPhil公