如何根据is_page()条件标记在Wordpress上为不同的页面排队多个css和js文件?

Adr*_*chi 2 php wordpress

我是PHP/WordPress的新手,我在这里要做的是通过使用is_page()条件将不同的css和js文件排入不同的页面.

虽然我认为这是一个广泛讨论的话题,但我还没有找到一个简洁的方法来排队多个文件(css/js),然后设置is_page()条件,以便其中一些文件可以排入一个每个"不同的页面基础".

以下代码适用于我的主题,但是,我想知道是否有更好的方法来实现它.我真的很感激有关这个问题的一些指导.文本.

// To register my css styles I use the function below:

function enqueue_extra_styles()
{
wp_register_style( 'custom-style', get_stylesheet_directory_uri() . '/css/custom-style.css', array(), '1', 'all' );
wp_register_style( 'second-custom-style', get_stylesheet_directory_uri() . '/css/second-custom-style.css', array(), '1', 'all' );
wp_register_style( 'third-custom-style', get_stylesheet_directory_uri() . '/css/niceforms/third-custom-style.css', array(), '1', 'all' );

if ( is_page('8')) { 
//bellow styles will be enqueued only on a page of id=8

    wp_enqueue_style('custom-style');
    wp_enqueue_style( 'second-custom-style' ); 
  }

//bellow style will be enqueued only on a page of id=2111 

if ( is_page('2111')){
    wp_enqueue_style('third-custom-style');
  }

}

add_action('wp_enqueue_scripts', 'enqueue_extra_styles');



// To register my js files I use the function below:

function my_extra_jscripts()
{
wp_register_script('custom-script', get_template_directory_uri().'/js/custom-script.js', array('jquery'), '', TRUE);

wp_register_script('second-custom-script', get_template_directory_uri().'/js/second-custom-script.js', array('jquery'), '', TRUE);

if ( is_page('8')){
   wp_enqueue_script('custom-script');
  }

if ( is_page('2111')){
   wp_enqueue_script('second-custom-script');
  }
}
add_action('wp_enqueue_scripts', 'my_extra_jscripts');
Run Code Online (Sandbox Code Playgroud)

正如其他用户所建议的那样,有几种方法可以优化上面的代码.我已经看到了这个答案,我发现它在优化方面非常有前景,但是,我想要实现的是一种更好的方法,同时编写php"如果有条件"...我的意思是,在优化代码后作为用户Jeffrey还建议,如果我有超过1页我想要将文件排入队列,下一步该怎么办,比方说:4页?我是否应该继续写"if(is_page('')){}"类型的循环结构?

小智 6

你实际上可以像这样制作你的脚本:

<?php
function custom_scripts_method() {
    wp_register_style( 'custom-style', get_stylesheet_directory_uri() . '/css/custom-style.css', array(), '1', 'all' );
    wp_register_style( 'second-custom-style', get_stylesheet_directory_uri() . '/css/second-custom-style.css', array(), '1', 'all' );
    wp_register_style( 'third-custom-style', get_stylesheet_directory_uri() . '/css/niceforms/third-custom-style.css', array(), '1', 'all' );

    wp_register_script('custom-script', get_template_directory_uri().'/js/custom-script.js', array('jquery'), '', TRUE);
    wp_register_script('second-custom-script', get_template_directory_uri().'/js/second-custom-script.js', array('jquery'), '', TRUE);

    if ( is_page('8')) {
        wp_enqueue_style('custom-style');
        wp_enqueue_style( 'second-custom-style' );

        wp_enqueue_script('custom-script');
    }
}

add_action( 'wp_enqueue_scripts', 'custom_scripts_method' );
?>
Run Code Online (Sandbox Code Playgroud)

wp_enqueue_scripts接受css和jquery enqueue.

干杯!