Maged Mohamed
Maged Mohamed

Reputation: 561

apply if condition if page url is exact the same as i provide

I have to apply a certain css for certain pages archives using a php snippet as there is no pages for this urls so i found this helpful code that if the url contains a string it will apply the condition below.

add_action( 'init', 'bbloomer_apply_css_if_url_contains_string' );

function bbloomer_apply_css_if_url_contains_string() {

$url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

if ( false !== strpos( $url, 'events/page' ) ) {
    echo '<style type="text/css">
         .buttonizerev { display: none; }
         </style>';
} 

}

I want to have the same code that this condition to be applied but not if the url contains a certain string i want it to be applied if the url is exactly the same as https://staging1.tktshub.com/events

How can i achieve this in one snippet to apply the condition i provided or even if in 2 snippets.

Upvotes: 0

Views: 554

Answers (1)

fiter
fiter

Reputation: 773

The good practice is using wp_add_inline_style function and wp_enqueue_scripts hook.

You have to find wp_enqueue_style of your main css file in functions.php:

wp_enqueue_style( 'style', get_stylesheet_uri() );

And use the first parameter ('style' in this case) as the first parameter in your wp_add_inline_style function:

wp_add_inline_style( 'style', $custom_css );

And provide your style as a string in the second parameter. The final code:

add_action( 'wp_enqueue_scripts', 'apply_css_if_url_contains_string' );

function apply_css_if_url_contains_string() {
  $url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

  if ( $url == 'staging1.tktshub.com/events' ) {
    $custom_css =  '.buttonizerev { display: none; }'; 
    wp_add_inline_style( 'style', $custom_css );
  } 
}

Read more about wp_add_inline_style here

Upvotes: 1

Related Questions