Simple ad management for wordpress

Combine wordpress custom post type and widget management to get a simple ad management system that can easily be enhanced to suit specific needs. Code below provides implementation for

  • "ad" custom post type, with thumbnail for image, and custom field in meta box for url destination 
  • widget for displaying random ad each time web site is refreshed, you can adpat image sizz by changing the image size in your code, once it has been defined in wordpress image sizes (add_image_size function)

CUSTOM POST TYPE for AD MANAGEMENT

<?php
  // webmasterbulletin : ad custom post type with widget
  // include in your theme functions.php
 
// Registers the new post type and taxonomy
//http://wptheming.com/2010/08/custom-metabox-for-post-type/
function webmasterbulletin_ads_type() {
    register_post_type( 'ads',
        array(
            'labels' => array(
                'name' => __( 'Pub' ),
                'singular_name' => __( 'Pub' ),
                'add_new' => __( 'Ajouter pub' ),
                'add_new_item' => __( 'Ajouter pub' ),
                'edit_item' => __( 'Modifier pub' ),
                'new_item' => __( 'Ajouter pub' ),
                'view_item' => __( 'Consulter Pub' ),
                'search_items' => __( 'Recherche annonceurs' ),
                'not_found' => __( 'aucun annonceur sur ces criteres' ),
                'not_found_in_trash' => __( 'aucun annonceur dans la poubelle' )
            ),
            'public' => true,
            'supports' => array( 'title', 'editor', 'thumbnail'  ),
            'capability_type' => 'post',
            'rewrite' => array("slug" => "ads"), // Permalinks format
            'menu_position' => 5,
            'register_meta_box_cb' => 'add_wb_ad_metaboxes'
        )
    );
}
add_action( 'init', 'webmasterbulletin_ads_type' );
add_action( 'add_meta_boxes', 'add_wb_ad_metaboxes' );

// Add the Events Meta Boxes
function add_wb_ad_metaboxes() {
    add_meta_box('wpt_add_url', 'Destination', 'wb_ad_mb', 'ads', 'normal', 'high');
}
 // The Event Location Metabox
function wb_ad_mb() {
    global $post;
    // Noncename needed to verify where the data originated
    echo '<input type="hidden" name="adurl_noncename" id="adurl_noncename" value="' .
    wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
    // Get the location data if its already been entered
    $addurl = get_post_meta($post->ID, 'addurl', true);
    // Echo out the field
    echo '<input type="text" name="addurl" value="' . $addurl  . '" class="widefat" />';
}

// Save the Metabox Data
function wb_save_ad_meta($post_id, $post) {
    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times
    if ( !wp_verify_nonce( $_POST['adurl_noncename'], plugin_basename(__FILE__) )) {
    return $post->ID;
    }
    // Is the user allowed to edit the post or page?
    if ( !current_user_can( 'edit_post', $post->ID ))
        return $post->ID;
    // OK, we're authenticated: we need to find and save the data
    // We'll put it into an array to make it easier to loop though.
    $events_meta['addurl'] = $_POST['addurl'];
    // Add values of $events_meta as custom fields
    foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
        if( $post->post_type == 'revision' ) return; // Don't store custom data twice
        $value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
        if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
            update_post_meta($post->ID, $key, $value);
        } else { // If the custom field doesn't have a value
            add_post_meta($post->ID, $key, $value);
        }
        if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
    }
}
add_action('save_post', 'wb_save_ad_meta', 1, 2); // save the custom fields

 

widget for ad management

code adapted from Simple Random Posts Widget plugin

define("DefNoOfPosts", "1"); // default number of random posts to display

class SimpleRandomPostsWidget extends WP_Widget {

    function SimpleRandomPostsWidget()
    {
        parent::WP_Widget( false, 'Simple ADS Random Posts',  array('description' => 'Random posts widget') );
    }

    function widget($args, $instance)
    {
        global $NewSimpleRandomPosts;
        $title =   $instance['title'];
        echo $args['before_widget'];
        echo $args['before_title'] . $title . $args['after_title'];
        echo $NewSimpleRandomPosts->GetSimpleRandomPosts(  empty( $instance['ShowPosts'] ) ? DefNoOfPosts : $instance['ShowPosts'] );
        echo $args['after_widget'];
    }

    function update($new_instance)
    {
        return $new_instance;
    }

    function form($instance)
    {
        ?>

        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php echo 'Title:'; ?></label>
            <input type="text" name="<?php echo $this->get_field_name('title'); ?>" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" value="<?php echo esc_attr($instance['title']); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('ShowPosts'); ?>"><?php echo 'Number of entries:'; ?></label>
            <input type="text" name="<?php echo $this->get_field_name('ShowPosts'); ?>" id="<?php echo $this->get_field_id('ShowPosts'); ?>" value="<?php if ( empty( $instance['ShowPosts'] ) ) { echo esc_attr(DefNoOfPosts); } else { echo esc_attr($instance['ShowPosts']); } ?>" size="3" />
        </p>

        <?php
    }

}



class SimpleRandomPosts {

    function GetSimpleRandomPosts($noofposts)
    {
        wp_reset_query();
         remove_filter ( 'posts_join', 'recent_join'  );
         remove_filter ( 'posts_fields', 'recent_fields'  );
            $the_query = new WP_Query('orderby=rand&post_type=ads&showposts='.$noofposts);
           // echo $the_query->request;
            if ($the_query->have_posts()) :
              
                while ($the_query->have_posts()) : $the_query->the_post();
                $url=get_post_meta(get_the_ID(),"adurl", true);
 
                    echo  '<div align="center"><a href="'.$url.'" target="_blank">';
                    echo get_the_post_thumbnail( get_the_ID(), "largeur200", array('title'=>get_the_title(), "alt"=>get_the_title() )); echo"<br>";
                    echo get_the_title().'</a></div> ';
                endwhile;
 
                echo '</ul>';

            endif;

        wp_reset_query();
    }

}



$NewSimpleRandomPosts = new SimpleRandomPosts();

function SimpleRandomPosts_widgets_init()
{
    register_widget('SimpleRandomPostsWidget');
}

add_action('widgets_init', 'SimpleRandomPosts_widgets_init');
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *