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 this? I tried to get the page title and I could not. Just the post.
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 this? I tried to get the page title and I could not. Just the post.
The correct way to add CSS to a WordPress site is using wp_enqueue_style
. You can do this 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 you can use Conditional Tags or any other WP function to determine which page you are on. For example, if CSS is only for pages and the css file has the page slug, here's what you need to do:
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)
);
}
}
In 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