Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active July 7, 2016 21:47
Show Gist options
  • Select an option

  • Save igorbenic/6e6f9f15b4e1b106ce62b2c9a53f7255 to your computer and use it in GitHub Desktop.

Select an option

Save igorbenic/6e6f9f15b4e1b106ce62b2c9a53f7255 to your computer and use it in GitHub Desktop.
Simple WordPress Advertising Plugin: Displaying Ads | http://www.ibenic.com/simple-wordpress-advertising-plugin-displaying-ads
<?php
array(
// Storing ads for top position
'top' => array(
0 => array(
//Ads parameters
)
),
// Storing ads for bottom position
'bottom' => array(
0 => array(
//Ads parameters
)
)
);
<?php
/**
* Inline Styles in WP Head
* @return void
*/
function swa_inline_style() {
$swa = swa();
if( ! $swa->has_ad_position('top') && ! $swa->has_ad_position('bottom') ) {
return;
}
?>
<style>
body.swa_ad_top {
padding-top:50px;
}
body.swa_ad_bottom {
padding-bottom: 50px;
}
.swa_ad_top .swa_ad_top {
position: absolute;
top:0;
}
.swa_ad_bottom .swa_ad_bottom {
position: fixed;
bottom:0;
top: auto;
z-index:999;
}
.swa_ad {
left:0;
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
background-color:#333;
color:white;
overflow: hidden;
}
.swa_ad img {
max-height: 50px;
width: auto;
}
.swa_ad p {
display:inline-block;
margin-left: 1em;
color:white;
}
.admin-bar.swa_ad_top .swa_ad_top{
top: 32px;
}
@media screen and (max-width: 782px) {
.admin-bar.swa_ad_top .swa_ad{
top: 46px;
}
}
</style>
<?php
}
<?php
// ...
/**
* Create Ads Array we will store and use
* @param array $ads Array of posts
* @return mixed
*/
function swa_create_ads_array( $ads ){
$ads_array = array();
$ads_array['top'] = array();
$ads_array['bottom'] = array();
foreach ( $ads as $ad ) {
$ad_meta = get_post_meta( $ad->ID, 'swa_info', true );
$new_ad = array(
'id' => $ad->ID,
'post_title' => $ad->post_title,
'link' => $ad_meta['link'],
'image' => get_the_post_thumbnail( $ad->ID, 'full' )
);
$position = $ad_meta['position'];
$ads_array[ $position ][] = $new_ad;
}
if( count( $ads_array['top'] ) == 0 && count( $ads_array['bottom'] ) == 0 ) {
return false;
}
return $ads_array;
}
<?php
// ...
/**
* Get Ads from cache or from the database
* @return mixed
*/
function swa_get_ads(){
if ( false === ( $ads = get_transient( 'swa_ads' ) ) ) {
/**
* The WordPress Query class.
* @link http://codex.wordpress.org/Function_Reference/WP_Query
*
*/
$args = array(
//Type & Status Parameters
'post_type' => 'swa',
'post_status' => 'publish',
//Pagination Parameters
'posts_per_page' => 100
);
$ads_from_db = get_posts( $args );
$ads = swa_create_ads_array( $ads_from_db );
set_transient( 'swa_ads', $ads );
}
$swa = swa();
$swa->set_ads( $ads );
return $ads;
}
<?php
/**
* Add body classes for position on which ads will be displayed
* @return [type] [description]
*/
function swa_add_body_classes() {
$swa = swa();
if( $swa->has_ad_position( 'top' ) ) {
add_filter('body_class', 'swa_add_body_top_class' );
}
if( $swa->has_ad_position( 'bottom' ) ) {
add_filter('body_class', 'swa_add_body_bottom_class' );
}
}
/**
* Filter function to add the class for top
* @param array $classes Array of classes that will be added to body
* @return array
*/
function swa_add_body_top_class( $classes ) {
$classes[] = 'swa_ad_top';
return $classes;
}
/**
* Filter function to add the class for bottom
* @param array $classes Array of classes that will be added to body
* @return array
*/
function swa_add_body_bottom_class( $classes ) {
$classes[] = 'swa_ad_bottom';
return $classes;
}
<?php
// ...
/**
* Display the ads, one random ad per position
* @return void
*/
function swa_display_ads() {
$swa = swa();
$ads = $swa->get_ads();
if( $ads ) {
$top_ads = $ads['top'];
$bottom_ads = $ads['bottom'];
if( count( $top_ads ) > 0 ) {
$random_top_ad = array_rand( $top_ads );
swa_render_ad( $top_ads[ $random_top_ad ], 'top' );
}
if( count( $bottom_ads ) > 0 ) {
$random_bottom_ad = array_rand( $bottom_ads );
swa_render_ad( $bottom_ads[ $random_bottom_ad ], 'bottom' );
}
}
}
/**
* Rendering function for the Ad
* @param array $ad_array Definition array of Ad
* @param string $position
* @return void
*/
function swa_render_ad( $ad_array, $position ) {
$swa_ad_class = 'swa_ad_top';
if( $position == 'bottom' ) {
$swa_ad_class = 'swa_ad_bottom';
}
$link = $ad_array['link'];
if( strpos( $link, 'http' ) === false ) {
$link = 'http://' . $link;
}
echo '<div class="swa_ad ' . $swa_ad_class . '">';
echo '<a target="_blank" href="' . $link . '">';
echo $ad_array['image'];
echo '<p>' . $ad_array['post_title'] . '</p>';
echo '</a>';
echo '</div>';
}
<?php
/**
* Function that triggers when our Ad is saved
* In this function we schedule the end of this ad to clear the transient and set the status of Ad
* @param number $post_id
* @param object $post
* @return mixed
*/
function swa_save_ad( $post_id, $post ){
$slug = 'swa';
if ( $slug != $post->post_type ) {
return;
}
$format = 'd-m-Y H:i';
$post_date = get_the_date( $format, $post_id );
$datetime = DateTime::createFromFormat( $format, $post_date );
$timestamp = $datetime->getTimestamp();
// Get the current Server Time
$current_time = time();
// Get the Current WordPress time
$wp_current_time = current_time( 'timestamp' );
// Get GMT offset
$offset = get_option('gmt_offset');
// Get Timezone string
$timezone = get_option('timezone_string');
$difference = 0;
if( $timezone ) {
date_default_timezone_set($timezone);
} else {
// Get the difference between. Difference will be minus if that time did not happen yet (such as GMT+0 and GMT+6)
$difference = $wp_current_time - $current_time;
}
// Multiply by -1 to get + so NY != -6 --> == +6
$the_end_time = (-1) * $difference + $timestamp;
// Get the duration of Ad
// Get the duration of Ad
$duration_of_ad = 0;
if( isset( $_POST['duration'] ) ) {
$duration_of_ad = $_POST['duration'];
}
$duration_of_ad_timestamp = $duration_of_ad * DAY_IN_SECONDS;
$the_end_time += $duration_of_ad_timestamp;
// Don't schedule if the end time is in the past
if( $wp_current_time > $the_end_time ) {
return $post_id;
}
// Post Status is 'Ended', publish it back
if( $post->post_status == 'ended' ){
swa_set_status( $post_id, 'swa', 'publish', 'ended' );
}
$scheduled_end_of_ad = wp_next_scheduled( 'swa_ad_ended', array( $post_id ) );
// If already scheduled, remove it
if( $scheduled_end_of_ad ) {
wp_unschedule_event( $scheduled_end_of_ad, 'swa_ad_ended', array( $post_id ) );
}
// Schedule the end
wp_schedule_single_event( $the_end_time, 'swa_ad_ended', array( $post_id ) );
}
<?php
// ...
/**
* Set status for a post
* @param number $post_id ID of the post for which we want to set the status
* @param string $post_type Post Type
* @param string $status New status we want to set
* @param string $from_status Old status, from which we will set
* @return boolean True/False
*/
function swa_set_status( $post_id, $post_type, $status, $from_status = 'publish'){
if( get_post_type( $post_id ) == $post_type ){
global $wpdb;
$update_status = $wpdb->update(
$wpdb->posts,
array(
'post_status' => $status, // string
),
array( 'ID' => $post_id, 'post_type' => $post_type, 'post_status' => $from_status ),
array(
'%s', // value1
),
array( '%d', '%s', '%s' )
);
if( $update_status ){
wp_transition_post_status( $status, $from_status, get_post($post_id) );
return true;
}
return false;
}
}
<?php
// ...
/**
* Function triggered when the ad has ended
* @param number $post_id
* @return void
*/
function swa_ad_ended( $post_id ) {
swa_set_status( $post_id, 'swa', 'ended' );
delete_transient( 'swa_ads' );
}
<?php
// ...
$swa_metabox->add_field(
array(
'name' => 'link',
'title' => __( 'Link of Ad', 'swa'),
'default' => 'http://',
'desc' => __( 'User who clicks will be redirected to this link', 'swa' )
)
);
$swa_metabox->add_field(
array(
'name' => 'position',
'title' => __( 'Position of the Ad', 'swa'),
'default' => 'top',
'type' => 'select',
'options' => array(
'top' => __( 'Top', 'swa' ),
'bottom' => __( 'Bottom', 'swa' )
)
)
);
<?php
// simple-wp-ads.php
/**
* Main Class
*/
class Simple_WP_Ads {
/**
* Ads to be rendered
* @var array
*/
protected $ads = array();
/**
* Return ads
* @return mixed
*/
public function get_ads(){
return $this->ads;
}
/**
* Sets ads
* @param mixed $ads
*/
public function set_ads( $ads ){
$this->ads = $ads;
}
/**
* Check if any ad is in position
* @param string $position the position to check
* @return mixed
*/
public function has_ad_position( $position ){
if( ! is_array( $this->ads ) ) {
return false;
}
if( isset( $this->ads[ $position ] ) && count( $this->ads[ $position ] ) > 0 ) {
return true;
}
return false;
}
// ...
}
<?php
// simple-wp-ads.php
// ...
// Simple_WP_Ads
/**
* Load dependencies
* @return void
*/
public function load_dependencies(){
/**
* Abstracts
*/
require_once SWA_ROOT .'inc/abstracts/class-swa-settings.php';
/**
* Classes
*/
require_once SWA_ROOT .'inc/class-swa-status.php';
/**
* Base functions
*/
require_once SWA_ROOT .'inc/swa-functions.php';
require_once SWA_ROOT .'inc/swa-cpt.php';
require_once SWA_ROOT .'inc/swa-statuses.php';
/**
* Load only on admin side
*/
if( is_admin() ) {
require_once SWA_ROOT .'inc/class-swa-metabox.php';
}
/**
* We are on the front page
*/
if( ! is_admin() ) {
require_once SWA_ROOT .'inc/swa-front.php';
}
}
// ...
<?php
// simple-wp-ads.php
// ...
// Simple_WP_Ads
/**
* Run the plugin
* @return void
*/
public function run(){
// Hook into the 'init' action
add_action( 'init', 'swa_cpt', 0 );
// Hook when swa has ended
add_action( 'swa_ad_ended', 'swa_ad_ended' );
if( is_admin() ) {
add_action( 'load-post.php', array( $this, 'construct_metabox_on_ad' ) );
add_action( 'load-post-new.php', array( $this, 'construct_metabox_on_ad' ) );
add_action( 'save_post', 'swa_save_ad', 99, 2 );
}
if( ! is_admin() ) {
// Add Style on front end
add_action( 'wp_head', 'swa_inline_style' );
// Get banners
add_action( 'init', 'swa_get_ads', 20 );
// Add body clases used in inline styles
add_action( 'init', 'swa_add_body_classes', 30 );
// Display the ads
add_action( 'wp_footer', 'swa_display_ads', 30 );
}
}
// ...
<?php
// simple-wp-ads.php
//...
function swa_start(){
$swa = swa();
$swa->load_dependencies();
$swa->run();
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment