How to Check for Class in body_class() in Wordpress - php

Within Wordpress header.php, I have
<body <?php body_class($class); ?>>
How do check to see if a specific class exists, and then load markup as a result?
For ex.
<body class"home logged-in">
<?php if $class == 'home' ?>
<div class="home"></div>
<? else : ?>
<div class="internal-page"></div>
<? endif; ?>
Thanks!

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
}
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.

You can access body_class with a filter add_filter('body_class', function ...) however, I think you are taking the wrong approach. Why not just use css for what you need? For example, .home>div { /* home styles */ }
Or you can load a different stylesheet
add_filter('body_class', function($classes) {
if (in_array('home', $classes)) {
wp_enqueue_style('home');
}
return $classes;
});

I have had the same problem as I created pages using different templates but a custom sub-menu needed to be the same on each pages.
I tried this one first what is failed
<body <?php body_class( 'extra-class' ); ?>>
The extra classes was added to the body tag but when I run the error log then it was not in the classes array. So I was sure it was added later to the body tag.
This solution worked for me:
functions.php
$GLOBALS['extraBodyClass'] = '';
In the template file
<?php $GLOBALS['extraBodyClass'] = 'extra-class' ?> - very first line in the template file
<body <?php body_class( $GLOBALS['extraBodyClass'] ); ?>> - after the template name declaration
In the header.php file
$classes = get_body_class();
if($GLOBALS['extraBodyClass']){
$classes[] = $GLOBALS['extraBodyClass'];
}

Related

php function to change css

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;
});
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
};
});
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>

Unable to inject a specific classname to body tag when a specific WordPress page template loads

I have a wordpress website in which there is a custom theme where I can create template parts for each webpage. I want to include/inject a specific class (ex: abc ) to the body tag in header.php when a specific page template (ex: abc.php) loads.
First I used the code bellow in header.php it did not work.
<body <?php if ( is_page_template( 'template-parts/page/abc.php' ) ) { body_class( 'abc' ); } else { body_class(); } ?>>
Then I added bellow code to functions.php but it is not working either.
add_filter( 'body_class','abc_class' );
function abc_class( $classes ) {
if ( is_page_template( 'template-parts/page/abc.php' ) ) {
$classes[] = 'abc';
}
return $classes;
}
I do not understand what I am doing wrong here. How can I fix this?
First of all the is_page_template() function works for WP templates, I mean which have in the beginning of the file
/*
* Template name: Your Super Template
*/
So, the function returns true is a page with this template is actually displaying. I will tell you more, you even do not have to add custom body classes because function body_class() adds specific unique classes for each page template :)
Second, the page templates can be in the theme directory itself or in 1-level subdirectory, so
<body <?php if ( is_page_template( 'abc.php' ) ) { body_class( 'abc' ); } else { body_class(); } ?>>
or
<body <?php if ( is_page_template( 'page-templates/abc.php' ) ) { body_class( 'abc' ); } else { body_class(); } ?>>
Your template in 2-level sub-directory, so it is not actually a Page Template, it is a template part.
So, in two words, the function is_page_template() is for Page Templates but not for template parts
I was able to add the following in functions.php so that it takes the slug and inject that to the body class every time a specific page loads.
add_filter( 'body_class', function( $classes ) {
if ( is_page() ){
$slug = get_queried_object()->post_name;
return array_merge( $classes, array( $slug ) );
}
return $classes;
} );

Custom field function available in WordPress templates

How to create a function in a custom page and use it in single.php?
I have the custom page mypage.php
<?php
/* Template Name: Form */
...
$myname = add_post_meta( $date, 'My Name', $name, true );
function name(){
if ($myname != ''){
echo ="Hello World! ";
}
}
get_header(); ?>
...
?>
Single page
<? php name(); ?>
To have functions available in all theme template files, you need to put them inside the file /wp-content/themes/your-theme/functions.php.
Just move your function to it, and call it in any template (single, page, archives, category). Check the documentation: Functions File Explained.
And to make the logic of your code work, you'd need to use get_post_meta in the function:
function name(){
$myname = get_post_meta('My Name');
if ($myname != ''){
echo "Hello World! ";
}
}
PS: it's a bit strange that you're setting a post meta everytime the mypage.php template is loaded...

Add Custom CCS to Specific Template Pages in Wordpress

I wish to centre the entry-title on certain pages in my Wordpress template using a body_class_filter. This will be based on the page template that is used.
e.g. Any page that uses page template pageshow.php should have custom CSS to centre the title.
I have read a few tutorials and comprehend what needs to be done. But my solution attempt isn't working. Here's what I tried...
I put the below at the bottom of my functions.php file...
if (is_page_template('pageshow.php'))
{ // Returns true when 'pageshow.php' is being used.
function my_class_names($classes)
{ // add 'class-name' to the $classes array
$classes[] = 'pageshowclass';
return $classes; // return the $classes array
}
// Now add pageshowclass class to the filter
add_filter('body_class', 'my_class_names');
}
else
{ // Returns false when 'about.php' is not being used.
}
And the below in my stylesheet...
/* Custom Page Styling by ID */
.pageshowclass h1.entry-title {
text-align: center;
}
But the class is not applied, nor is the css. Here is some useful doco.
Make sure your theme supports body_class. It should have the following in the body tag:
<body <?php body_class(); ?>>
If it does, check that your if condition is returning true, eg:
if (is_page_template('pageshow.php')){
echo 'ITS WORKING';
}

Wordpress PHP - categories

I think my previous question was over complicated and, to be honest, was confusing me, nevermind the people trying to answer.
I currently have to pages, both with one category of posts assigned to them, however both post pages are using the same content.php and content-single.php, but i was both pages to use different iterations of these pages for cosmetic reasons.
As an example, visit http://dev.n8geeks.com/blog/ and click on the first blog post. It displays a thumbnail, which is cool and is what i want. However, now on the "videos" page as seen here; http://dev.n8geeks.com/videos/ (once there, click on the post) it also shows the thumbnail box (but no thumbnails will be attached on this posts page category).
This is why i need to user different iterations of content.php and content-single.php, but i simply don't know how. It would also be great if the "videos" page had the same formatting as the "blog" page, but again, i don't know how to achieve this.
The code i'm using for the current "videos" page is as below.
<?php get_header(); ?>
<div id="content">
<div id="main">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: endif; ?>
<?php query_posts('category_name='.get_the_title().'&post_status=publish,future');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1 class="entry-title"><a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a></h1>
<p><?php the_content(); ?>
<?php endwhile; else: endif; ?>
</div>
</div>
<?php get_footer(); ?>
Thanks in advance, i really appreciate any help like you wouldn't believe - it's 4:33am and i'm going insane trying to find a fix for this.
Regards
Still extremely confusing, haha, but from the sounds of it you want different templates to show up based on which category the post is in when you're viewing a single post?
If so, you could try setting this as you single.php:
<?php get_header(); ?>
<?php
if ( have_posts() ) { the_post(); rewind_posts(); }
if ( in_category(1) || in_category(2) ) {
include(TEMPLATEPATH . '/single-cat1-2.php');
}
else {
include(TEMPLATEPATH . '/single-default.php');
}
?>
<?php get_footer(); ?>
(from http://wordpress.org/support/topic/alternate-single-post-template-for-specific-categories)
And create the files 'single-cat1-2.php' and 'single-default.php', just add to the if statement checking to see if the post is in a certain category (or categories) and load the correct template. You can use ID, name, and their slug as selectors for the in_category function as well, read more here.
EDIT:
Kay, well you do need to learn plugin programming to really do this. I've begun a quick plugin for you to help you out. It works, just isn't perfect. You could definitely use a different system, like tying the categories in the category menu, but I didn't feel like playing with the Settings API for that page.
So make a new directory in your plugins directory, call it PostCatTheme, make a new file in there called index.php and put this in it:
<?php
/*
* Plugin Name: Post Category Templates
*/
//Replace __FILE__ with whatever the real path is because of symbolic link
/**
* Allows declarations of which categories a single-post template is assigned to
*/
class WordpressPostCatTheme
{
private $pluginDir, $templates;
function __construct ()
{
$this->pluginDir = dirname(__FILE__);
add_action("init", array($this, "load"));
add_filter('single_template', array($this, 'get_post_template'));
}
public function WPCT_deactivate ()
{
delete_option("PostCatTheme_templates");
}
public function load ()
{
register_deactivation_hook( __FILE__, array(&$this, 'WPCT_deactivate') );
$this->templates = get_option("PostCatTheme_templates");
if ($this->templates === FALSE)
{
$this->templates = $this->get_post_templates();
update_option("PostCatTheme_templates", $this->templates);
}
}
// This function scans the template files of the active theme,
// and returns an array of [category] => {file}.php]
public function get_post_templates()
{
$themes = get_themes();
$theme = get_current_theme();
$templates = $themes[$theme]['Template Files'];
$post_templates = array();
$base = array(trailingslashit(get_template_directory()), trailingslashit(get_stylesheet_directory()));
foreach ((array)$templates as $template)
{
$template = WP_CONTENT_DIR . str_replace(WP_CONTENT_DIR, '', $template);
$basename = str_replace($base, '', $template);
// don't allow template files in subdirectories
if (false !== strpos($basename, '/'))
continue;
$template_data = implode('', file( $template ));
$categories = '';
if (preg_match( '|Categories (.*)$|mi', $template_data, $categories))
$categories = _cleanup_header_comment($categories[1]);
//The categories are split by a | (pipe), if there aren't any pipes, assume it's just
//one category, otherwise split at the pipe
if (empty($categories))
continue;
if (strpos($categories, "|") === FALSE)
$categories = array($categories);
else
$categories = explode("|", $categories);
foreach ($categories as $category)
{
if (!empty($category))
{
if (isset($post_templates[$category]))
throw new Exception("Error, category assigned to more than one template");
if(basename($template) != basename(__FILE__))
$post_templates[trim($category)] = $basename;
}
}
}
//file_put_contents($this->pluginDir . "/log", json_encode($post_templates));
return $post_templates;
}
// Filter the single template value, and replace it with
// the template chosen by the user, if they chose one.
function get_post_template($template)
{
global $post;
$cats = wp_get_post_categories($post->ID);
//Go through each category, until one hits
foreach ($cats as $c)
{
$templateP = $this->templates[$c];
if(!empty($templateP) && file_exists(TEMPLATEPATH . "/{$templateP}"))
{
$template = TEMPLATEPATH . "/{$templateP}";
break;
}
}
return $template;
}
}
if (!isset($PostCatThemePlugin))
$PostCatThemePlugin = new WordpressPostCatTheme;
?>
After that, in your custom single.php template, add the code Categories: 1|2 in the header section (where Template Name is). Whenever you change or add these, make sure to deactivate and reactivate the plugin, to refresh the cache that this information is stored in.
To get the ID of a category, edit a category and in the URL, the number after tag_ID= is the category's ID.
Hope that helps some,
Max

Categories