Php check body class

Php – Check if a body has class “paged-“

I’m trying to find if the body class basically has part of a class as Im currently using is_paged() in an if-statement and that is working. Of course as the paged pages goes, it’s «paged-1, paged-2» etc.

Anyone have an idea to see a way to create an if-statement that involves:

If bodyclass has «paged-«, or «paged-numerical_value» then do something.

Any ideas or help would be appreciated.

Best Solution

You may try something like this:

// Get the body classes as array $classes = get_body_class(); // For exact maych try this if (in_array('paged-1', $classes)) < // . >// For partial match try this $match = FALSE; foreach($classes as $string) < if (strpos($string, 'paged-') !== FALSE) < $match = TRUE; break; >> if($match) < // . >

Read about get_body_class function on Codex .

Php – How to check if PHP array is associative or sequential

You have asked two questions that are not quite equivalent:

  • Firstly, how to determine whether an array has only numeric keys
  • Secondly, how to determine whether an array has sequential numeric keys, starting from 0

Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)

The first question (simply checking that all keys are numeric) is answered well by Captain kurO.

For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:

function isAssoc(array $arr) < if (array() === $arr) return false; return array_keys($arr) !== range(0, count($arr) - 1); >var_dump(isAssoc(['a', 'b', 'c'])); // false var_dump(isAssoc(["0" => 'a', "1" => 'b', "2" => 'c'])); // false var_dump(isAssoc(["1" => 'a', "0" => 'b', "2" => 'c'])); // true var_dump(isAssoc(["a" => 'a', "b" => 'b', "c" => 'c'])); // true 
Php – How to check if a string contains a specific word

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$a = 'How are you?'; if (strpos($a, 'are') !== false)

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn’t found. Since 0 is a valid offset and 0 is «falsey», we can’t use simpler constructs like !strpos($a, ‘are’) .

Now with PHP 8 you can do this using str_contains:

if (str_contains('How are you', 'are'))

Источник

PHP: Check whether an HTML element has a certain class

I’d like to present links to similar topics at the end of of a blog entry. My strategy would be to quote the topic tag as class attribute to the html or body element:

And make a simple PHP function at the bottom of the page: «If has class ‘bears’, include bears.php here.» Without any elses. Could someone help me with the code? The data-attribute in HTML 5 might be more appropriate for that, but I don’t know if PHP can address them. Thanks. Runa

how are you giving your html those classes? Statically? If so, you will need to use something like jQuery ajax to call php and fetch data. PHP is server side and processes before output, so you can’t expect it to react to something already written to the DOM.

Читайте также:  Бинарное представление строки питон

As you’re trying to do this from PHP-side, there’s not much difference between class or data- attributes, both are equally inefficient. Those would require reading the OB and using a DOM parser/ugly regexes. You’d be much better using variables, a global array would take care of it easily.

@sebas — api.jquery.com/jQuery.ajax — that. makes life easier. I know the difference. But if he google searches «jquery ajax» at his level he is much more likely to resolve his problem than if he were to just search for ajax.

@KaiQing I understand the pedagogic intention but I have to disapprove. The trend of systematically using frameworks to realise simple javascript tasks goes against my education and my values. (In the case of ajax, jquery actually complicates it in my opinion) My disapproval does not mean I don’t respect your opinion.

Источник

How to Check for Class in body_class() in WordPress

If you really, really need to use different markup based on the body_class classes, then use get_body_class,But there are probably better ways to do this, like @Rob’s suggestion of Conditional Tags. Those map pretty closely to the classes used by body_class., 1 I have tried your method of grabbing the body class with ‘get_body_class();’, but when itterating through the array and echoing the content, it spits out ALL the class tags, EXCEPT the one I manually added with ‘body_class($class);’. Am I doing something wrong? I can see my class in the body tag, but ‘get_body_class();’ doesn’t have it contained in there. – KVDD Oct 31 ’14 at 22:23 , 1 If you read his answer given to the best answer he said that adding the class with > did not work. It was my problem as well and the method I added worked for me. – László Péter Varga May 3 ’18 at 20:11

If you really, really need to use different markup based on the body_class classes, then use get_body_class

$classes = get_body_class(); if (in_array('home',$classes)) < // your markup >else < // some other markup >

Answer by Carter Esquivel

This function gives the body element different classes and can be added, typically, in the header.php’s HTML body tag.,The following example shows how to implement the body_class template tag into a theme.,You can check all these in function get_body_class(),To add the following to the WordPress Theme functions.php file, changing my_class_names and class-name to meet your needs:

The following example shows how to implement the body_class template tag into a theme.

The actual HTML output might resemble something like this (the About the Tests page from the Theme Unit Test):

In the WordPress Theme stylesheet, add the appropriate styles, such as:

Answer by Cain McDowell

Within WordPress header.php, I have ,How do check to see if a specific class exists, and then load markup as a result? For ex.,If you really, really need to use different markup based on the body_class classes, then use get_body_class,>

Within WordPress header.php, I have

How do check to see if a specific class exists, and then load markup as a result? For ex.

Answer by Byron Barry

In this short tutorial, we’ll look at the WordPress body class and how we can manipulate it using core API calls.,The body_class() function in WordPress makes this very easy for us by automatically adding a bunch of appropriate classes to the body tag of our website.,In this small tutorial, we have covered two methods of adding to the WordPress body class:,This takes all of the classes in the array and passes them to the body_class function.

Читайте также:  Css галерея с разными размерами

There may be times when you want to add more than one body class. This can be achieved using a simple array:

It’s possible to use a WordPress filter to add a body class, too. This method keeps the theme code cleaner and is particularly useful if you want to add a body class from a plugin. This code can either go in your theme’s functions.php or within your plugin.

add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes )

To add more classes to the filter, just add another line that adds another value to the array:

add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes )

Conditions can also be used in a filter. Taking the same example that we used earlier, we can achieve the same effect:

add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes ) < if ( is_shop() ) < $classes[] = 'class-name'; $classes[] = 'class-name-two'; >return $classes; >

So let’s add a new class, using a filter and a WordPress conditional tag:

add_filter( 'body_class','halfhalf_body_class' ); function halfhalf_body_class( $classes ) < if ( is_page_template( 'page-halfhalf.php' ) ) < $classes[] = 'halfhalf-page'; >return $classes; >

It’s unlikely that you will want to remove a body class, as you are not forced to use them and they add very little to your markup. That said, it is possible to do this using the same body_class filter.

add_filter( 'body_class', 'remove_body_class' ); function remove_body_class( $classes )

Answer by Daniella Barton

Body class (body_class) is a WordPress function that allows you to assign CSS classes to the body element. ,First, you need to make sure that your theme’s body element contains the body class function as shown above. If it does, then it will automatically include all the WordPress generated CSS classes mentioned above. ,This allows theme developers to check if a condition is true or false before adding a custom CSS class to the body_class function. ,You can use the body_class function to add CSS classes for full-width page layouts, sidebar content, header and footers, etc.

Normally most starter themes and frameworks already include the body class function inside the HTML body tag. However, if your theme does not have it, then you can add it by modifying the body tag like this:

Here are some examples of common classes that WordPress might add, depending on which page is being displayed:

.rtl <> .home <> .blog <> .archive <> .date <> .search <> .paged <> .attachment <> .error404 <> .single postid-(id) <> .attachmentid-(id) <> .attachment-(mime-type) <> .author <> .author-(user_nicename) <> .category <> .category-(slug) <> .tag <> .tag-(slug) <> .page-parent <> .page-child parent-pageid-(id) <> .page-template page-template-(template file name) <> .search-results <> .search-no-results <> .logged-in <> .paged-(page number) <> .single-paged-(page number) <> .page-paged-(page number) <> .category-paged-(page number) <> .tag-paged-(page number) <> .date-paged-(page number) <> .author-paged-(page number) <> .search-paged-(page number) <> 

Because body classes are theme specific, you would need to add the following code to your theme’s functions.php file.

function my_class_names($classes) < // add 'class-name' to the $classes array $classes[] = 'wpb-class'; // return the $classes array return $classes; >//Now add test class to the filter add_filter('body_class','my_class_names'); 

To achieve this you will add the following code to your theme’s functions.php file.

function wpb_loggedin_user_role_class($classes) < // let's check if it is homepage if ( is_home() ) < // Now let's check if the logged in user has author user role. $user = wp_get_current_user(); if ( in_array( 'author', (array) $user->roles ) ) < //The user has the "author" role // Add user role to the body class $classes[] = 'author'; // Return the classes array return $classes; >> else < // if it is not homepage, then just return default classes return $classes; >> add_filter('body_class', 'wpb_loggedin_user_role_class'); 

To do that we will use the conditional tag is_preview and then add our custom CSS class.

function add_preview_class($classes) < if ( is_preview() ) < $classes[] = 'preview-mode'; return $classes; >return $classes; > add_filter('body_class','add_preview_class'); 

Now, we will add the following CSS to our theme’s stylesheet to utilize the new custom CSS class we just added.

.preview-mode .site-header:before

First, you need to add category names as CSS class on single post pages. To do that, add the following code to your theme’s functions.php file:

// add category nicenames in body class function category_id_class($classes) < global $post; foreach((get_the_category($post->ID)) as $category) $classes[] = $category->category_nicename; return $classes; > add_filter('body_class', 'category_id_class'); 

Paste the following code in your theme’s functions.php file:

//Page Slug Body Class function add_slug_body_class( $classes ) < global $post; if ( isset( $post ) ) < $classes[] = $post->post_type . '-' . $post->post_name; > return $classes; > add_filter( 'body_class', 'add_slug_body_class' ); 

Simply, copy and paste the following code in your theme’s functions.php file:

 function wpb_browser_body_class($classes) < global $is_iphone, $is_chrome, $is_safari, $is_NS4, $is_opera, $is_macIE, $is_winIE, $is_gecko, $is_lynx, $is_IE, $is_edge; if ($is_iphone) $classes[] ='iphone-safari'; elseif ($is_chrome) $classes[] ='google-chrome'; elseif ($is_safari) $classes[] ='safari'; elseif ($is_NS4) $classes[] ='netscape'; elseif ($is_opera) $classes[] ='opera'; elseif ($is_macIE) $classes[] ='mac-ie'; elseif ($is_winIE) $classes[] ='windows-ie'; elseif ($is_gecko) $classes[] ='firefox'; elseif ($is_lynx) $classes[] ='lynx'; elseif ($is_IE) $classes[] ='internet-explorer'; elseif ($is_edge) $classes[] ='ms-edge'; else $classes[] = 'unknown'; return $classes; >add_filter('body_class','wpb_browser_body_class'); 

You can then use classes like:

Читайте также:  Css body full width

Answer by Sevyn Barnes

add_filter( 'body_class', 'custom_class' ); function custom_class( $classes ) < if ( is_page_template( 'page-example.php' ) ) < $classes[] = 'example'; >return $classes; > 

Answer by Sawyer Meza

Since WordPress 2.8, we can target specific types of page views with CSS using the new body_class() tag. Designed for use within the element, body_class() outputs various class attributes according to the current type of page view. This makes it easy to apply page-specific styling such as current-page navigation highlighting and other nifty CSS tricks.,The body_class() tag will output the following class names depending on current page type:,This is a exemplified version of the body_class_plus() function that enables us to target and apply specific class attributes to any page or category containing the following terms in the URL/page-slug:,So, for example, when you are logged in to WordPress and viewing your blog’s home page, the body_class() tag will result in something like this:

For the uninitiated, here is a quick review of the body_class() tag. When used as follows:

This functionality enables you to, say, apply styles to the heading elements on all of your search pages:

This is powerful, yes, but what if we want to target, say, all categories that include the term “services” in the category slug? Sure, we could declare each of them individually, like this:

.category-coffee-service < color: red; >.category-brunch-services < color: red; >.category-dinner-services < color: red; >.category-snacks-services < color: red; >.category-drinks-services < color: red; >.category-inside-services < color: red; >.category-design-services < color: red; >.category-health-services < color: red; >.category-services-info < color: red; >.category-services-data < color: red; >.category-services-cost
 elseif(preg_match("/products/i", $class)) < echo 'class="products"'; >elseif(preg_match("/business/i", $class)) < echo 'class="business"'; >elseif(preg_match("/pleasure/i", $class)) < echo 'class="pleasure"'; >else < echo 'class="no-body-class-matches"'; >> else < echo 'class="body-class-not-available"'; >> > ?>

To call this function in your theme template, include the following tag in the element of your choice (e.g., within the element):

Источник

Оцените статью