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 帮我调试idea基于spring boot项目
  • ¥15 es 7.17.20版本生成时间戳
  • ¥15 wpf dategrid表头排序图标自定义
  • ¥15 分析下图所示同步时序逻辑电路的逻辑功能。
  • ¥15 halcon联合c#遇到了问题不能解决
  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合