I believe the primary problem in your code is the $custom_values
is set after you try to use it (and you need to use the same variable name). Otherwise, it doesn’t have a value when it’s in post_class()
. In fact, I’m surprised you’re not getting an error. That variable needs to get the value before the call to post_class
.
<?php $custom_values = get_post_meta($post->ID, 'post_class'); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'class-1 class-2' . $custom_values ); ?>>
In the above snippet, you also need to account for the fact that get_post_meta()
returns an array
by default. (This means the above code snippet still probably wouldn’t work.)
So instead of all that, the best practice is to use the post_class
filter (which would also mean you get this class if the post shows up on an archive page too.
To use the filter, you’d use a snippet like this (untested), probably in your functions.php
file:
add_filter( 'post_class', 'wpse182657_post_class', 10, 2 );
function wpse182657_post_class( $classes, $post_id ) {
// get the meta
// true assumes you only use one value per this key on any single post
// if false, you'd have to loop through the array with a foreach loop
$post_class = get_post_meta( $post_id, 'post_class', true );
// add $post_class variable to $classes array
$classes[] = esc_attr( $post_class );
// run along now, $classes
return $classes;
}