Created
November 5, 2011 14:33
-
-
Save chrisguitarguy/1341589 to your computer and use it in GitHub Desktop.
change the class of a post based on a postmeta value in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: wpse32973 Post Layout | |
Author: Christopher Davis | |
Author URI: http://www.christopherguitar.net/wordpress/ | |
Description: Change the post class (for styling purposes) so posts can be formatted correctly. | |
*/ | |
// register the meta box | |
add_action( 'add_meta_boxes', 'wpse32973_add_meta_box' ); | |
function wpse32973_add_meta_box() | |
{ | |
add_meta_box( | |
'wpse32973-box', | |
__( 'Post Layout' ), | |
'wpse32973_meta_box_cb', | |
'post', | |
'side', | |
'high' | |
); | |
} | |
// | |
function wpse32973_meta_box_cb( $post ) | |
{ | |
$meta = get_post_meta( $post->ID, '_wpse32973_layout', true ); | |
// what options you'd like to have for layouts. value => label | |
$opts = array( | |
'right_thumb' => __( 'Right Thumbnail' ), | |
'left_thumb' => __( 'Left Thumbnail' ) | |
); | |
wp_nonce_field( 'wpse32973_nonce', 'wpse32973_nonce', false ); | |
echo '<select name="wpse32973_layout">'; | |
foreach( $opts as $val => $label ) | |
{ | |
echo '<option ' . selected( $val, $meta, false ) . ' value="' . esc_attr( $val ) . '">' . esc_html( $label ) . '</option>'; | |
} | |
echo '</select>'; | |
} | |
add_action( 'edit_post', 'wpse32973_save' ); | |
function wpse32973_save( $post_id ) | |
{ | |
if( ! isset( $_POST['wpse32973_nonce'] ) || ! wp_verify_nonce( $_POST['wpse32973_nonce'], 'wpse32973_nonce' ) ) | |
return; | |
if( ! current_user_can( 'edit_post', $post_id ) ) | |
return; | |
if( isset( $_POST['wpse32973_layout'] ) ) | |
update_post_meta( $post_id, '_wpse32973_layout', esc_attr( strip_tags( $_POST['wpse32973_layout'] ) ) ); | |
} | |
add_filter( 'post_class', 'wpse32973_post_class', 10, 3 ); | |
function wpse32973_post_class( $classes, $class, $post_id ) | |
{ | |
$layout = get_post_meta( $post_id, '_wpse32973_layout', true ); | |
if( ! empty( $layout ) ) | |
{ | |
$classes[] = esc_attr( $layout ); | |
} | |
return $classes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment