essentially I need to be able to add a class to a post when it show in the list (say index.php) so when in the back end you can say oneCol, twoCol, threeCol and it will then output this within the loop post class.
This is to enable a tighter control of the layout. using this line of code for the output?
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>
Thanks in advance!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Note –
I recommend using the hook suggested by @Chip Bennett in another answer
Here’s the modified version of that filter –
function wpse_filter_post_class( $classes ) { $my_post_class = get_post_meta($post->ID, "your_meta_name"); if( $my_post_class != '' ) $classes[] = $my_post_class; return $classes; } add_filter( 'post_class', 'wpse_filter_post_class' );
You can setup a Custom fileds for that – See usage, then use get_post_meta() function to fetch it and show where you want
Example –
<?php echo get_post_meta($post->ID, "your_meta_name", true)?>
This will output the class name set in the meta_key.
OR ( Update #1 ) –
Pass the variable into Post Class
<?php $my_class = get_post_meta($post->ID, "your_meta_name") ?> <div id="post-<?php the_ID(); ?>" <?php post_class( $my_class ); ?>>
Method 2
Example:
function wpse_filter_post_class( $classes ) {
// How you determine what class is up to you;
// We will assume you've determined the class name
// and added it to $my_post_class
$my_post_class = 'some-class';
// Add it to the array of post classes
$classes[] = $my_post_class;
// Return the array
return $classes;
}
add_filter( 'post_class', 'wpse_filter_post_class' );
Edit
Assuming you’ll be using custom post meta data to determine the layout string to add as a post class, you’d do something like follows:
$my_post_class = ( isset( get_post_meta( get_the_ID(), '_post_layout', true ) ? get_post_meta( get_the_ID(), '_post_layout', true ) : false );
To incorporate that into your filter callback:
function wpse_filter_post_class( $classes ) {
// Test for your layout post meta
$my_post_class = ( isset( get_post_meta( get_the_ID(), '_post_layout', true ) ? get_post_meta( get_the_ID(), '_post_layout', true ) : false );
// If it's there, use it
if ( $my_post_class ) {
// Add layout as a post class
$classes[] = $my_post_class;
}
// Return the array
return $classes;
}
add_filter( 'post_class', 'wpse_filter_post_class' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0