Specific css file for each wordpress page

Asked

Viewed 625 times

1

I’m making some custom pages in a wordpress template and would like to put a css stylesheet in each one right in the header. Is there any way to do that? I tried to get the title of the page and I couldn’t. Just from the post.

  • get_the_title did not take the page title?

  • It didn’t take, but maybe it’s because there’s no post on the page

  • This will be a bit of a hassle, because there is a need to make a css for each page?

1 answer

2


The correct way to add CSS to a Wordpress site is by using wp_enqueue_style. You can do it in your functions.php:

add_action( 'wp_enqueue_scripts', 'meu_css' );
function meu_css() {
    wp_enqueue_style(
        'nome-do-css',
        get_template_directory_uri() . '/caminho/do/arquivo.css',
        array(), // defina dependências aqui (opcional)
        '1.0', // versão do seu tema (opcional)
    );
}

This hook runs after queries so it is possible to use Conditional Tags or any other WP function to determine which page we are on. For example, if CSS is only for pages and the css file has the page’s Slug, this should do what you need:

add_action( 'wp_enqueue_scripts', 'meu_css' );
function meu_css() {
    global $post;

    if( is_page() ) { // somente se for uma página
        wp_enqueue_style(
            'nome-personalizado',
            get_template_directory_uri() . '/css/' . $post->post_name . '.css',
            array(), // defina dependências aqui (opcional)
            '1.0', // versão do seu tema (opcional)
        );
    }
}

On a page called Hello World, with Slug hello-world the above example will load the file http://seusite.com/wp-content/themes/seutema/css/hello-world.css

Browser other questions tagged

You are not signed in. Login or sign up in order to post.