Quang Huy
Quang Huy

Reputation: 59

WordPress custom page CSS

I have tried to do some self research and found these questions 1 and 2 but none of them really solved my problem so I created a new one.

I tried to use wp_enqueue_scripts function to load specific CSS file into specific page, but somehow it always skips the condition and proceeds to the else condition. Here is my code;

function theme_script_enqueue() {
    if(is_page_template('index.php')) {
        wp_enqueue_style('indexstyle', get_template_directory_uri() . '/css/news.css', array(), '1.0.0', 'all');
        wp_enqueue_script('indexjs', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true);
    } else {
        wp_enqueue_style('mainstyle', get_template_directory_uri() . '/css/main.css', array(), '1.0.0', 'all');
        wp_enqueue_script('mainjs', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true);
    }
}

add_action('wp_enqueue_scripts', 'theme_script_enqueue');

When I access http://localhost:8888/wordpress/index.php just to make sure, based on the condition, I expected the script to load news.css but instead it loaded main.css which they have some elements with different colors so I spotted instantly. I did do the switch CSS file between the condition and it always load the else condition when I tried to access index.php. Did I do something wrong?

Upvotes: 0

Views: 252

Answers (1)

Der Alex
Der Alex

Reputation: 854

As described here: https://developer.wordpress.org/themes/template-files-section/page-template-files/

index.php — If no specific page templates are assigned or found, WordPress defaults back to using the theme’s index file to render pages.

So for my understanding index.php is a fallback and not a template. Also you have to describe your template file:

<?php /* Template Name: Example Template */ ?>

Have you written that comment into your template file?

Upvotes: 2

Related Questions