Custom CSS per page in Wordpress

2020-04-10 02:44发布

Good Morning All,

I have created a different background and a few other images for certain pages within our site. Currently the below code is working well with the "kids" page on our site.

<body<?php if ( is_page(array('kids'))) {
echo ' class="kids" '; } ?>>

I am trying to figure out how to go about adding that same CSS to other pages"under" the kids page. So if you go to kids/block-party, how would I go about adding it to the code to call that special CSS?

I have tried the below

<body<?php if ( is_page(array('kids, kids/block-party'))) {
echo ' class="kids" '; } ?>>

the comma does not seem to register for some reason.

This is a wordpress run site.

Thanks

标签: css wordpress
4条回答
男人必须洒脱
2楼-- · 2020-04-10 03:09

Another option is simply replacing

<body>

with

<body <?php body_class(); ?>>

Then you can target it it via css as follows:

body.page-id-2, body.parent-pageid-2 { background-color: red; }

Where the ID is the ID of the page/parent-page you are targeting. This will keep your template clear of logic, and allow you the same customization options your current method is using.

查看更多
做自己的国王
3楼-- · 2020-04-10 03:13

Figured out i needed the ' ' around them

<body<?php if ( is_page(array('newsletter-1', 'newsletter-2', 'newsletter-3'))) { echo '   class="myclass" '; } ?>>
查看更多
混吃等死
4楼-- · 2020-04-10 03:21

I may have over thought this one, but here's my solution.

The script below automatically gets all the children of a specific parent page and prints the class you need. This solution works great if you don't want to have to update the list of children pages manually.

This goes in your header.php file:

<?php 
    //set page id 
            $page_id = '98';

           //get page's children 
    $children = get_pages('child_of='.$page_id);
    foreach($children as $child){
       $children_ids = $child->ID;
    }

    if(is_page($page_id) || is_page($children_ids)){
       echo 'class="kids';
    }

?>

Thanks, and I hope this helps!

查看更多
孤傲高冷的网名
5楼-- · 2020-04-10 03:25

Note: I know the 3 current answers are a common solution to this problem for WP, but in practice, I hate it. It produces bloated HTML and monolithic CSS :/

Answer: You could use a template file assigned to any number of pages to add specific CSS/Javascript like so:

<?php
function my_scripts_method() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
    wp_enqueue_script( 'jquery' );
}    

add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

Source: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

查看更多
登录 后发表回答