Last active
September 24, 2019 15:04
-
-
Save adkorte/b5ebe31740b3a63a1ed9 to your computer and use it in GitHub Desktop.
Ad Box: Simple way to mark your WordPress posts as ads with one click in your editor
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 | |
/** Ad Box **/ | |
/** Author: Adrian Korte, @adkorte **/ | |
/** add this snippet to your functions.php **/ | |
// add a meta box to your edit/new post screen | |
add_action( 'add_meta_boxes', 'meta_ad_box_add' ); | |
function meta_ad_box_add() | |
{ | |
// name and define box and it's appearance | |
add_meta_box( 'ad-box-id', 'Werbung', 'meta_ad_box', 'post', 'side', 'high' ); | |
} | |
function meta_ad_box($post) | |
{ | |
// $post is already set, and contains an object: the WordPress post | |
global $post; | |
// check if value is set | |
$values = get_post_custom( $post->ID ); | |
$check = isset( $values['meta_ad_box_check'] ) ? esc_attr($values['meta_ad_box_check'][0]) : ''; | |
// We'll use this nonce field later on when saving. | |
wp_nonce_field( 'meta_ad_box_nonce', 'meta_ad_box_noncename' ); | |
// Show checkbox on screen | |
echo ( | |
'<input type="checkbox" id="meta_ad_box_check" name="meta_ad_box_check"'. checked($check, 'on', false) .'/>'. | |
'<label for="meta_ad_box_check">Bei diesem Beitrag handelt es sich um Werbung</label>' | |
); | |
} | |
// save values in database | |
add_action( 'save_post', 'meta_ad_box_save' ); | |
function meta_ad_box_save( $post_id ) | |
{ | |
// enable autosave | |
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; | |
// if our nonce isn't there, or we can't verify it, bail | |
if( !isset( $_POST['meta_ad_box_noncename'] ) || !wp_verify_nonce( $_POST['meta_ad_box_noncename'], 'meta_ad_box_nonce' ) ) return; | |
// if our current user can't edit this post, bail | |
if( !current_user_can( 'edit_post' ) ) return; | |
// get value of checkbox | |
$chk = isset( $_POST['meta_ad_box_check'] ) ? 'on' : 'off'; | |
// save value to database, as post_meta | |
update_post_meta( $post_id, 'meta_ad_box_check', $chk ); | |
} | |
?> |
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 | |
/** Call your ad note within your content page **/ | |
/** Use this snippet in your content template files, within the loop **/ | |
// get value for meta_box | |
$adbutton = get_post_meta( get_the_ID(), 'meta_ad_box_check', true ); | |
// If value is 'on', show hint | |
if ( $adbutton == 'on' ) { | |
echo "Werbung"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment