duanpu1111 2019-04-04 21:12
浏览 92
已采纳

如何在Wordpress functions.php中使用高级自定义字段对脚本进行入队和出列?

I want to create checkboxes with Advanced Custom Fields in an admin panel in the Wordpress backend that can enable and disable scripts.

I created a checkbox field, called it import_animejs and checked it. Then used acf/load_field to enqueue the script but I am missing something as it's not working.

Here is my code:

function acf_checkbox_scripts() {
    wp_register_script('animejs', get_stylesheet_directory_uri() . '/bower_components/animejs/lib/anime.min.js', array('jquery'),'1.1', true);
}
add_action( 'wp_enqueue_scripts', 'acf_checkbox_scripts', 5 );

function load_field_import_animejs( $field ) {
    wp_enqueue_script('animejs');
    return $field;
}
add_filter('acf/load_field/name=import_animejs', 'load_field_import_animejs');

I expect the filter to recognise that import_animejs is ticked and enqueue anime.js but it doesn't.

Update: many thanks to Lachlan's answer this works, and just for clarification I completely removed the acf/load_field "load_field_import_animejs" function in the code I posted above.

  • 写回答

1条回答 默认 最新

  • doujiebo9849 2019-04-05 02:35
    关注

    You need to do an if statement and check if the field is true

    This can be done by:

    function acf_checkbox_scripts() {
        if ( get_field( 'import_animejs', 'options' ) ) { // only include 'options' if the acf field is on an acf options page, if not use the post_id of that page
            wp_register_script('animejs', get_stylesheet_directory_uri() . '/bower_components/animejs/lib/anime.min.js', array('jquery'),'1.1', true); 
            wp_enqueue_script('animejs');
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'acf_checkbox_scripts', 5 );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存