如何将CSS和Js添加到wordpress子主题

时间:2017-05-26 21:18:31

标签: javascript php css wordpress

我正在尝试将cssjs添加到我的Wordpress子主题中,但没有一个被拾取。

主题是从一些设置文件夹递归添加的。

我错了怎么回事?

提前谢谢大家。

functions.php

<?php

/* Add Scripts */

if ( ! function_exists('rev_cust_scripts')) {

    add_action( 'wp_enqueue_scripts', 'rev_cust_scripts' );

    function rev_cust_scripts() {
        $css_paths = array("layout", "js");
        $scripts_stack = [];

        foreach ($css_paths as &$value) {

            $dir = get_stylesheet_directory() . '/' . $value;
            $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );

            foreach ( $iterator as $path ) {
                if ( ! $path -> isDir() ) {
                    $path_parts = pathinfo($path);
                    $file_parts = $path_parts['extension'];

                    if ( !in_array($file_parts, array('css','js'), true ) ) 
                        continue;

                    switch ($file_parts) {
                        case 'css':
                        $file_name = basename($path, '.css');
                        break;
                        case 'js':
                        $file_name = basename($path, '.js');
                        break;
                    }

                    $pages_base = "/opt/lampp/htdocs/projects/wordpress_projects/liz_bloggable";
                    $server_pages_base = "http://localhost/projects/wordpress_projects/liz_bloggable";

                    $url = str_replace($pages_base, $server_pages_base, $path);

                    $array_item = array('script' => $file_parts, 'handle' => $file_name, 'src' => $url);
                    array_push($scripts_stack, $array_item);
                }
            }
        }

        doAttachScripts($scripts_stack);
    }

    function doAttachScripts($scripts) {
        foreach ($scripts as $key => $child_array) {
            if (is_array($child_array)) {
                $script = $child_array['script'];

                switch ($script) {
                    case 'css':
                    wp_enqueue_style($child_array['handle'], $child_array['src']);
                    break;

                    case 'js' :
                    wp_enqueue_script( $child_array['handle'], $child_array['src'], array('jquery'));
                    break;
                }
                unset($scripts[$key]);
            }
        }
    }
}

0 个答案:

没有答案