0

I'm trying to add a piece of code to change css on a page. I added the code to functions.php in WordPress. However, it does not seem to work. Since I'm quite new to this there might be something quite basic wrong with the code... Any idea why it might not be working?

// This code is added to functions.php
// intro is the class name of the element I'm trying to change
add_action( 'intro', function () {
    if ( is_user_logged_in() ) {
        ?>
            <style>
                display: none!important;
            </style>
        <?php
    };
    exit;
});
2
  • 1
    It doesnt work because your style is incorrect. You are missing the selection. What should be set to display: none !important? div boxes, the entire body, or ... or ... or ...? Commented Feb 19, 2021 at 10:51
  • if you've made an update, please update your question to show what you've changed/tried, and what the new issue is? Commented Feb 19, 2021 at 13:27

2 Answers 2

2

I got it to work by removing exit; and targeting an element:

add_action( 'wp_head', function () {
    if ( is_user_logged_in() ) {
        ?>
            <style>
                .intro{
                    display: none!important;
                }
            </style>
        <?php
    };
});
Sign up to request clarification or add additional context in comments.

Comments

0

I think what you are trying to do is change the content of the css class which I do not think you can do. Instead a solution would be to assign a css class with the propertied that you want applied to the element e.g.

<div class="<?php if ( is_user_logged_in() ) { echo 'intro';} ?>">
   // Whatever you have here will get the css style applied 
   // if user is logged in
</div>

And inn The CSS you have the following

.intro{
  display: none!important;
}

You can create multiple files for different styles e.g. another class

.outro{
  display:initial;
}

And you can add it in the code as

<div class="<?php if ( is_user_logged_in() ) { echo 'intro';} else{ echo 'outro';} ?>">
       // Whatever you have here will get the css style applied 
       // if user is logged in and if logged out then outro class will be applied
    </div>

3 Comments

I think the problem with this solution is that it requires to directly add php in a WordPress page, which I don't think is possible in WordPress?
@Zoe it is possible. That is how the themes are designed. But as long as your answer works all good :).
@Zoe you make a child theme, and put your custom code in the child-theme/functions.php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.