Yonatan Shippin
Yonatan Shippin

Reputation: 171

Adding a class to Wordpress post_class using add_filter in functions.php

I'm trying to add an extra class to all posts of a certain type- I'm currently getting a blank page after adding this to functions.php

I need to add the class "post" only where the $classes contain the string "toefl_post".

Here is my code:

function add_post_class($classes) {

$tester = strpos($classes,'toefl_post');
$additional = 'post'

if($tester === false) {
 // string NOT found
    return $classes;
}
else {

 // string found
      $classes = $classes + $additional;
    return $classes;
};
}

add_filter('post_class', 'add_post_class');

I'm pretty new to PHP so I'm guessing something is wrong with the code- Would really appreciate any help.

Upvotes: 0

Views: 2864

Answers (3)

Pbinder
Pbinder

Reputation: 470

The answer works but this one is more simple:

add_filter('post_class','my_class');
function my_class( $classes ) {
  $classes[] = 'my-class-name';
  return $classes;
}

Upvotes: 3

santerref
santerref

Reputation: 163

Your problem is here $additional = 'post'

You are missing a ;.

There are also others syntax errors like Enrique Chavez says.

Upvotes: 1

Enrique Chavez
Enrique Chavez

Reputation: 1429

Yeah, you have a lot of syntax issues there.

1.- $classes is an Array, not a String

2.- You can't use + to contatenate strings, you should use .

3.- To add a key into an array you should use array_push

try this:

function add_post_class($classes) {
    $additional = 'post';
    foreach ($classes as $class) {
        if( $class == 'toefl_post'){
            array_push($classes , $additional);
            break;
        }
    }
    return $classes;
}
add_filter('post_class', 'add_post_class');

Upvotes: 2

Related Questions