Created
October 10, 2018 08:02
-
-
Save benthebear/2a4c87b857447fbcb55a5d7d162445d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
// Add Meta-Boxes | |
add_action( 'add_meta_boxes', 'waves_and_rocks_add_custom_meta_boxes' ); | |
// Save CSS Box | |
add_action( 'save_post', 'waves_and_rocks_save_meta_boxes' ); | |
// Add CSS to the Content | |
add_filter( 'the_content', 'waves_and_rocks_custom_css_the_content_filter' ); | |
/* ## MetaBox for CSS */ | |
function waves_and_rocks_add_custom_meta_boxes( $post ) { | |
add_meta_box( | |
'waves-and-rocks-meta-box-custom-css', | |
__( 'Custom CSS' ), | |
'waves_and_rocks_render_meta_box_custom_css', | |
array('post', 'page'), | |
'normal', | |
'default' | |
); | |
} | |
function waves_and_rocks_render_meta_box_custom_css($post){ | |
// Add a nonce field so we can check for it later. | |
wp_nonce_field( 'waves_and_rocks_save_meta_box_custom_css_data', 'waves_and_rocks_meta_box_custom_css_nonce' ); | |
echo '<textarea name="waves-and-rocks-meta-box-custom-css" style="with:100%;" cols="80" rows="10">'; | |
echo get_post_meta( $post->ID, "_waves-and-rocks-custom-css", true ); | |
echo '</textarea>'; | |
} | |
function waves_and_rocks_save_meta_boxes($post_id){ | |
// Verify that the nonce is valid. | |
if ( ! wp_verify_nonce( $_POST['waves_and_rocks_meta_box_custom_css_nonce'], 'waves_and_rocks_save_meta_box_custom_css_data' ) ) { | |
return; | |
} | |
// If this is an autosave, our form has not been submitted, so we don't want to do anything. | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { | |
return; | |
} | |
// Check the user's permissions. | |
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { | |
if ( ! current_user_can( 'edit_page', $post_id ) ) { | |
return; | |
} | |
} else { | |
if ( ! current_user_can( 'edit_post', $post_id ) ) { | |
return; | |
} | |
} | |
// Save CSS | |
if (isset( $_POST['waves-and-rocks-meta-box-custom-css'] ) ) { | |
// Sanitize user input. | |
$my_data = $_POST['waves-and-rocks-meta-box-custom-css']; | |
// Update the meta field in the database. | |
update_post_meta( $post_id, '_waves-and-rocks-custom-css', $my_data ); | |
} | |
} | |
function waves_and_rocks_custom_css_the_content_filter($content) { | |
$styles = get_post_meta( $GLOBALS['post']->ID, "_waves-and-rocks-custom-css", true ); | |
if (is_singular() and $styles !="") { | |
$output = ""; | |
$output .= "<style>"; | |
$output .= $styles; | |
$output .= "</style>"; | |
$content = $output.$content; | |
} | |
// otherwise returns the database content | |
return $content; | |
}?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment