WP Smith

Creating WordPress & Genesis Websites Since 2010

  • Home
  • About
  • Services
  • Blog
  • Contact

Sep 14 2011

Custom Post Types Plugin Spotlight: Easy Content Types (Premium)

One of the best custom post type plugins has to be Easy Content Types by Pippin Williamson (@pippinspages). This previously mentioned plugin, Easy Content Types provides an extremely easy-to-use, familiar (very WordPress-like) and intuitive interface for creating custom post types, taxonomies, and meta boxes. It makes creating custom categories, custom tags, and custom input fields so easy and simple. The stepwise process of creating the custom post type is extremely logical.

  1. Create the Custom Post Type (register custom post type)
  2. Create the Custom Taxonomies (register taxonomy)
  3. Create the Metabox
  4. Create the Metabox fields

Just like Custom Post Types UI exported CPT registration information, just recently announced, Pippin's newest edition now exports metabox php! Thus, this becomes the best custom post type plugin available! Now child theme designers can easily create custom post types in their sandbox, copy and paste the code in their functions.php file or an associate cpt.php file (or whatever) and have an excellently created custom post type to continue working to design!

So to demonstrate the exported php code, I went into the plugin, created a post type called wps_books, a custom taxonomy called wps_genre, and added a meta box with a few fields. Then I copied and pasted the code in my functions.php file, deactivated the plugin and the code works!

The Easy Content Types plugin is a premium plugin, available on CodeCanyon for $20. I know that most of us WordPress junkies are not keen on paying for premium plugins, but using this plugin can make coding easy and make it easy to learn how to do custom post types on your own.

However, for those who are just cheap and want a free plugin (like I do most of the time!): check out the giveaway of the plugin we’re running at the bottom of the post!

Here's the exported registration code:
[php]
// registration code for wps_books post type
function register_wps_books_posttype() {
$labels = array(
'name' => _x( 'Books', 'post type general name' ),
'singular_name' => _x( 'Book', 'post type singular name' ),
'add_new' => _x( 'Add New', 'Book'),
'add_new_item' => __( 'Add New Book '),
'edit_item' => __( 'Edit Book '),
'new_item' => __( 'New Book '),
'view_item' => __( 'View Book '),
'search_items' => __( 'Search Books '),
'not_found' => __( 'No Book found' ),
'not_found_in_trash'=> __( 'No Books found in Trash' ),
'parent_item_colon' => ''
);

$supports = array('title','editor','author','thumbnail','excerpt','custom-fields','comments');

$post_type_args = array(
'labels' => $labels,
'singular_label' => __('Book'),
'public' => true,
'show_ui' => true,
'publicly_queryable'=> true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'rewrite' => array('slug' => 'books'),
'supports' => $supports,
'menu_position' => 5,
'menu_icon' => 'http://localhost:8888/www/sandbox/wp-content/uploads/2011/09/Book-icon16.png'
);
register_post_type('wps_books',$post_type_args);
}
add_action('init', 'register_wps_books_posttype');
[/php]

Then I created a custom taxonomy called wps_genre, and here is the exported registration code:
[php]
// registration code for wps_genre taxonomy
function register_wps_genre_tax() {
$labels = array(
'name' => _x( 'Genre', 'taxonomy general name' ),
'singular_name' => _x( 'Genre', 'taxonomy singular name' ),
'add_new' => _x( 'Add New Genre', 'Genre'),
'add_new_item' => __( 'Add New Genre' ),
'edit_item' => __( 'Edit Genre' ),
'new_item' => __( 'New Genre' ),
'view_item' => __( 'View Genre' ),
'search_items' => __( 'Search Genre' ),
'not_found' => __( 'No Genre found' ),
'not_found_in_trash' => __( 'No Genre found in Trash' ),
);

$pages = array('wps_books');

$args = array(
'labels' => $labels,
'singular_label' => __('Genre'),
'public' => true,
'show_ui' => true,
'hierarchical' => false,
'show_tagcloud' => false,
'show_in_nav_menus' => true,
'rewrite' => array('slug' => 'genre'),
);
register_taxonomy('wps_genre', $pages, $args);
}
add_action('init', 'register_wps_genre_tax');
[/php]

Then I created a meta box area called "Book Information" with 3 fields: Pages, ISBN, and Publish Date, and here is the exported metabox code:
[php]
$bookinformation_metabox = array(
'id' => 'bookinformation',
'title' => 'Book Information',
'page' => 'wps_books',
'context' => 'normal',
'priority' => 'high',
'fields' => $bookinformation_fields = array(

array(
'name' => 'Pages',
'desc' => 'Enter the number of pages',
'id' => 'ecpt_pages',
'class' => 'ecpt_pages',
'type' => 'text',
'rich_editor' => 0,
'max' => 0
),

array(
'name' => 'ISBN',
'desc' => 'ISBN',
'id' => 'ecpt_isbn',
'class' => 'ecpt_isbn',
'type' => 'text',
'rich_editor' => 0,
'max' => 0
),

array(
'name' => 'Publish Date',
'desc' => '',
'id' => 'ecpt_publishdate',
'class' => 'ecpt_publishdate',
'type' => 'date',
'rich_editor' => 0,
'max' => 0
),
)
);

add_action('admin_menu', 'ecpt_add_bookinformation_meta_box');
function ecpt_add_bookinformation_meta_box() {

global $bookinformation_metabox;

add_meta_box($bookinformation_metabox['id'], $bookinformation_metabox['title'], 'ecpt_show_bookinformation_box', 'wps_books', 'normal', 'high', $bookinformation_metabox);
}

// function to show meta boxes
function ecpt_show_bookinformation_box() {
global $post;
global $bookinformation_metabox;
global $ecpt_prefix;

// Use nonce for verification
echo '<input type="hidden" name="ecpt_bookinformation_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

echo '<table class="form-table">';

foreach ($bookinformation_metabox['fields'] as $field) {
// get current post meta data

$meta = get_post_meta($post->ID, $field['id'], true);

echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" /><br/>', '', $field['desc'];
break;
case 'date':
echo '<input type="text" class="ecpt_datepicker" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '', $field['desc'];
break;
case 'upload':
echo '<input type="text" class="ecpt_upload_field" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:80%" /><input class="upload_image_button" type="button" value="Upload Image" /><br/>', '', $field['desc'];
break;
case 'textarea':
if($field['rich_editor'] == 1) {
// this is the old method of enabling the RTE. Now it only needs the class name.
//wp_tiny_mce(true, array('editor_selector' => $field['class'], 'remove_linebreaks' => false) );
echo '<div style="width: 97%; border: 1px solid #DFDFDF;"><textarea name="', $field['id'], '" class="theEditor ', $field['class'], '" id="', $field['id'], '" cols="60" rows="8" style="width:97%">', $meta ? $meta : $field['std'], '</textarea></div>', '', $field['desc'];
} else {
echo '<div style="width: 100%;"><textarea name="', $field['id'], '" class="', $field['class'], '" id="', $field['id'], '" cols="60" rows="8" style="width:97%">', $meta ? $meta : $field['std'], '</textarea></div>', '', $field['desc'];
}
break;
case 'select':
echo '<select name="', $field['id'], '" id="', $field['id'], '">';
foreach ($field['options'] as $option) {
echo '<option value="' . $option . '"', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
}
echo '</select>', '', $field['desc'];
break;
case 'radio':
foreach ($field['options'] as $option) {
echo '<input type="radio" name="', $field['id'], '" value="', $option, '"', $meta == $option ? ' checked="checked"' : '', ' />&nbsp;', $option;
}
echo '<br/>' . $field['desc'];
break;
case 'checkbox':
echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />&nbsp;';
echo $field['desc'];
break;
case 'slider':
echo '<input type="text" rel="' . $field['max'] . '" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" size="1" style="float: left; margin-right: 5px" />';
echo '<div class="ecpt-slider" rel="' . $field['id'] . '" style="float: left; width: 60%; margin: 5px 0 0 0;"></div>';
echo '<div style="width: 100%; clear: both;">' . $field['desc'] . '</div>';
break;
}
echo '<td>',
'</tr>';
}

echo '</table>';
}

add_action('save_post', 'ecpt_bookinformation_save');

// Save data from meta box
function ecpt_bookinformation_save($post_id) {
global $post;
global $bookinformation_metabox;

// verify nonce
if (!wp_verify_nonce($_POST['ecpt_bookinformation_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}

// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}

// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}

foreach ($bookinformation_metabox['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];

if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}

function ecpt_export_ui_scripts() {

global $ecpt_options;
?>
<script type="text/javascript">
jQuery(document).ready(function()
{

if(jQuery('.form-table .ecpt_upload_field').length > 0 ) {
// Media Uploader
window.formfield = '';

jQuery('.upload_image_button').live('click', function() {
window.formfield = jQuery('.ecpt_upload_field',jQuery(this).parent());
tb_show('', 'media-upload.php?type=file&TB_iframe=true');
return false;
});

window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (window.formfield) {
imgurl = jQuery('a','<div>'+html+'</div>').attr('href');
window.formfield.val(imgurl);
tb_remove();
}
else {
window.original_send_to_editor(html);
}
window.formfield = '';
window.imagefield = false;
}
}
if(jQuery('.form-table .ecpt-slider').length > 0 ) {
jQuery('.ecpt-slider').each(function(){
var $this = jQuery(this);
var id = $this.attr('rel');
var val = jQuery('#' + id).val();
var max = jQuery('#' + id).attr('rel');
max = parseInt(max);
//var step = $('#' + id).closest('input').attr('rel');
$this.slider({
value: val,
max: max,
step: 1,
slide: function(event, ui) {
jQuery('#' + id).val(ui.value);
}
});
});
}

if(jQuery('.form-table .ecpt_datepicker').length > 0 ) {
var dateFormat = 'mm-dd-yy';
jQuery('.ecpt_datepicker').datepicker({dateFormat: dateFormat});
}
});
</script>
<?php
}

function ecpt_export_datepicker_ui_scripts() {
global $ecpt_base_dir;
wp_enqueue_script('jquery-ui.min', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js', false, '1.8', 'all');
}
function ecpt_export_datepicker_ui_styles() {
global $ecpt_base_dir;
wp_enqueue_style('jquery-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css', false, '1.8', 'all');
}

// these are for newest versions of WP
add_action('admin_print_scripts-post.php', 'ecpt_export_datepicker_ui_scripts');
add_action('admin_print_scripts-edit.php', 'ecpt_export_datepicker_ui_scripts');
add_action('admin_print_scripts-post-new.php', 'ecpt_export_datepicker_ui_scripts');
add_action('admin_print_styles-post.php', 'ecpt_export_datepicker_ui_styles');
add_action('admin_print_styles-edit.php', 'ecpt_export_datepicker_ui_styles');
add_action('admin_print_styles-post-new.php', 'ecpt_export_datepicker_ui_styles');

if ((isset($_GET['post']) && (isset($_GET['action']) && $_GET['action'] == 'edit') ) || (strstr($_SERVER['REQUEST_URI'], 'wp-admin/post-new.php')))
{
add_action('admin_head', 'ecpt_export_ui_scripts');
}
[/php]

Awesome! Simply awesome! Pippin told me he was trying to do this and I am very, very excited that he has accomplished this!

If you haven't seen the introduction video, please check it out here:

Development Perspective Mini-Review

From a development perspective, Easy Content Types is a solid plugin, with a strong and active developer! However, overuse of the exported php code will lead to some redundant code for someone who doesn't know much coding. Also, with frameworks, like Genesis, there are some difficulties that the plugin must overcome to be fully integrated with the particular framework. However, after talking with Pippin, he made some updates to the export code (reducing some of the potential redundancy) and single/archives post type templating in light of frameworks, which can be expected in the next release in the next few days.

In light of the upcoming meta box class that is being targeted for WordPress 3.3, it will drastically reduce the export code. However, there will be a quick and seemless update when the metabox_class is announced in beta RCs.

Plugin Giveaway

CLOSED.
I have one copy to give away. To enter, do the following:

  1. Tweet on Twitter: "Free Giveaway by @wp_smith: Easy Content Types Plugin for WordPress by @pippinspages http://wp.me/pSgPV-1f0"
  2. Share the link on Google Plus
  3. If you don't have a Twitter account or a Google+ account, share the link on Facebook
  4. Then enter a comment below with the appropriate links answering the question, "Why should you get a copy of Easy Content Types by Pippin Williamson?"

One commenter will be chosen randomly on Friday to win. Only one comment per person will be counted.

Written by Travis Smith · Categorized: Custom Post Types, WordPress

Sep 12 2011

How to Add a Login Form to the Primary Navigation Menu in Genesis

Someone contacted me to develop a function that would add a login form to the primary navigation for their Genesis menu, and I would like to share it with you.

Primary Navigation with Login

[php]';
$login .= '';
$login .= '';
$login .= '';
$login .= '';
$login .= '';
$menu .= '

  • ' . $login . '
  • ';
    }
    // if logged in, do logout link
    else {
    global $current_user;
    get_currentuserinfo();
    $logout = '';
    $logout = 'Welcome ' . $current_user->display_name;
    $logout .= 'Logout';
    $menu .= '

  • ' . $logout . '
  • ';
    }

    return $menu;
    }
    [/php]

    Written by Travis Smith · Categorized: Tutorials, WordPress

    Aug 27 2011

    How to Add Custom Background Support to a Genesis Child Theme and Set an Easily Changed Default Background

    **UPDATE: Since writing this post, I have updated this code to be a plugin with everything. Please feel free to check it out: Genesis Custom Backgrounds.**

    I believe it would be really great if Genesis would support custom backgrounds (forum post). Anyways, the newly developed backgrounds (dark, light), while not part of core, could be easily integrated into ANY child theme.

    While I am not sure that this will become part of the Genesis core, and if I had to place a bet, I would bet against me. However, the benefits of this code, are as follows:

    • The code can easily be unhooked and removed
    • The code makes setting defaults easy, which is not part of WordPress, which is perfect for Child Themes
    • A few filters to customize even further

    To install the code, simply paste the following in your functions.php, or download the file at the end of the post.
    [php]<?php
    /**
    * Enables Genesis support of custom backgrounds
    *
    * @author Travis Smith
    *
    * @uses add_custom_background() calls standard, filterable callback
    * @uses apply_filters() filters callback
    *
    */
    function genesis_custom_background() {
    global $genesis_settings;

    $genesis_settings[ 'cb_default' ] = ''; //assuming this will be placed with the other defaults
    $cb = apply_filters( 'genesis_custom_background_args' , 'genesis_do_theme_background' );
    add_custom_background( $cb );
    }
    add_action( 'init' , 'genesis_custom_background' );

    /**
    * Outputs custom backgrounds inline
    *
    * @author Travis Smith
    *
    * @uses $genesis_settings for custom background default image
    * @uses apply_filters() filters defaults
    *
    */
    function genesis_do_theme_background() {
    global $genesis_settings;

    $defaults = array(
    'default_img' => ( isset( $genesis_settings['cb_default'] ) ) ? $genesis_settings['cb_default'] : '', //url, e.g., PARENT_URL . "/images/bg/gray/gray-1.png
    'bgimage' => get_background_image(),
    'bgcolor' => get_background_color(),
    );
    $defaults = apply_filters( 'genesis_background_defaults' , $defaults );

    extract( $defaults , EXTR_SKIP );

    // begin output
    $output = "<style type='text/css'>n";

    if( !empty( $bgimage ) ) {
    $background_styles = 'background-image: url('' . get_theme_mod( 'background_image' , '' ) . '');'
    . ' background-repeat: ' . get_theme_mod( 'background_repeat' , 'repeat' ) . ';'
    . ' background-position: top ' . get_theme_mod( 'background_position_x' , 'left' ) . ';' . 'background-attachment: '. get_theme_mod( 'background_attachment' , 'scroll' );
    $output .= "body { " . $background_styles . "); } n";
    }

    if( !empty( $bgcolor ) ) {
    $output .= "body { background-color: #" . $bgcolor . "; }; n";
    }

    // for child themes to set a default bg img
    if( !empty( $default_img ) && empty( $bgcolor ) && empty( $bgimage ) ) {
    $output .= "body { background: url('" . $default_img . "'); }n";
    }
    $output .= "</style>";

    echo apply_filters( 'genesis_background_output' , $output , $output, $bgimage , $bgcolor , ( isset( $background_styles ) ) ? $background_styles : '' );
    }
    [/php]

    This would be used by child themes as such:
    [php]<?php
    add_filter( 'genesis_background_defaults' , 'genesis_custom_background_childdefault' );
    function genesis_custom_background_childdefault( $defaults ) {
    //change the URL to whatever you'd like
    $defaults['default_img'] = CHILD_URL . '/images/bg/gray/gray-1.png';

    return $defaults;
    }[/php]

    If you wanted to include the StudioPress backgrounds, they are released to GPL and can be placed in any child theme folder. So feel free to download them (dark, light).

    To download this file, click here: [download id="15"]. Then place it in your child theme folder and include the following in your functions.php file. Assuming you place it in a lib folder within your child theme...
    [php]require_once(CHILD_DIR.'/lib/wps-genesis-custom-backgrounds.php');[/php]

    Written by Travis Smith · Categorized: WordPress

    Aug 26 2011

    How to Add Menu Descriptions & Featured Images to WordPress Menu Items

    Recently I read an awesome post by Bill Erickson about customizing WordPress menus. However, there are two things I wanted this class to do that in its original form it doesn't do.

    So since out of the box, WordPress doesn't intuitively allow you to add descriptions to the menu without requiring some custom code, rather the Walker class extended.

    Since Bill has done an excellent job at this I will extend his code to add the options of having a featured image and/or descriptions applied based on depth.

    Add this to your functions.php file.

    <?php
    class Menu_With_Description extends Walker_Nav_Menu {
    function start_el( &$output, $item, $depth, $args ) {
    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
    $class_names = ' class="' . esc_attr( $class_names ) . '"';
    $output .= $indent . '<li id="menu-item-' . $item->ID . '"' . $value . $class_names . '>';
    $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) . '"' : '';
    $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) . '"' : '';
    $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) . '"' : '';
    $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) . '"' : '';
    // get user defined attributes for thumbnail images
    $attr_defaults = array(
    'class' => 'nav_thumb',
    'alt' => esc_attr( $item->attr_title ),
    'title' => esc_attr( $item->attr_title )
    );
    $attr = isset( $args->thumbnail_attr ) ? $args->thumbnail_attr : '';
    $attr = wp_parse_args( $attr, $attr_defaults );
    $item_output = $args->before;
    // thumbnail image output
    $item_output .= ( isset( $args->thumbnail_link ) && $args->thumbnail_link ) ? '<a' . $attributes . '>' : '';
    $item_output .= apply_filters( 'menu_item_thumbnail', ( isset( $args->thumbnail ) && $args->thumbnail ) ? get_the_post_thumbnail( $item->object_id, ( isset( $args->thumbnail_size ) ) ? $args->thumbnail_size : 'thumbnail', $attr ) : '', $item, $args, $depth );
    $item_output .= ( isset( $args->thumbnail_link ) && $args->thumbnail_link ) ? '</a>' : '';
    // menu link output
    $item_output .= '<a' . $attributes . '>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    // menu description output based on depth
    $item_output .= ( $args->desc_depth >= $depth ) ? '<br /><span class="sub">' . $item->description . '</span>' : '';
    // close menu link anchor
    $item_output .= '</a>';
    $item_output .= $args->after;
    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
    }
    view raw Menu_With_Description.php hosted with ❤ by GitHub

     

    All Menus

    To highjack ALL of your menus, enter this code in your functions.php.

    <?php
    add_filter( 'wp_nav_menu_args', 'my_add_menu_descriptions' );
    function my_add_menu_descriptions( $args ) {
    $args['walker'] = new Menu_With_Description;
    $args['desc_depth'] = 0;
    $args['thumbnail'] = true;
    $args['thumbnail_link'] = false;
    $args['thumbnail_size'] = 'nav_thumb';
    $args['thumbnail_attr'] = array( 'class' => 'nav_thumb my_thumb', 'alt' => 'test', 'title' => 'test' );
    return $args;
    }
    view raw my_add_menu_descriptions.php hosted with ❤ by GitHub

    Menus Based on Location

    To highjack a menu based on registered and assigned location, then use this code in your functions.php.

    <?php
    add_filter( 'wp_nav_menu_args', 'my_add_menu_descriptions' );
    function my_add_menu_descriptions( $args ) {
    if ( $args['theme_location'] == 'primary' ) {
    $args['walker'] = new Menu_With_Description;
    $args['desc_depth'] = 0;
    $args['thumbnail'] = true;
    $args['thumbnail_link'] = false;
    $args['thumbnail_size'] = 'nav_thumb';
    $args['thumbnail_attr'] = array( 'class' => 'nav_thumb my_thumb', 'alt' => 'test', 'title' => 'test' );
    }
    return $args;
    }
    view raw my_add_menu_descriptions.php hosted with ❤ by GitHub

     

    Menus via WordPress Custom Menu Widget

    To highjack a custom menu based menu id that is called using the custom menu widget, or even a manual method (if the menu is being called by a location, you must use 'theme_location'), then use this code in your functions.php. This will highjack any menu called by the custom menu widget assuming you only have the standard registered theme locations. The example below assumes a standard theme custom menu registered locations for Genesis. Change 'primary' and/or 'secondary' to whatever your theme adds and add whatever more menus that your theme has to only target the custom menu widget.

    <?php
    add_filter( 'wp_nav_menu_args', 'my_add_menu_descriptions' );
    function my_add_menu_descriptions( $args ) {
    if ( $args['theme_location'] != 'primary' && $args['theme_location'] != 'secondary' ) {
    $args['walker'] = new Menu_With_Description;
    $args['desc_depth'] = 0;
    $args['thumbnail'] = true;
    $args['thumbnail_link'] = false;
    $args['thumbnail_size'] = 'nav_thumb';
    $args['thumbnail_attr'] = array( 'class' => 'nav_thumb my_thumb', 'alt' => 'test', 'title' => 'test' );
    }
    return $args;
    }
    view raw my_add_menu_descriptions.php hosted with ❤ by GitHub

    There is a caveat though. There are certain menu items that may not have a featured image such as custom links, categories, etc. There is a possible work-around that I am trying to work out.

    Here is the result of a sandbox description and featured images for all types (not just pages and posts), which I will be posting soon or writing up into a plugin...

    Sandbox Genesis Menu with Descriptions and Featured Images

    Written by Travis Smith · Categorized: Tutorials, WordPress

    Aug 25 2011

    How to Get Original Image from a Thumbnail Image in WordPress

    Recently, in order to dummy proof a metabox that accepts a file upload via Media Library from a user accidentally selecting something other than Original Image like Small, Medium, or Large, I wrote a validation script to check and correct this.
    Media Library: Insert Into Posts
    This function will change a thumbnail URL (http://domain.com/wp-content/uploads/2011/08/example_2a-158x300.jpg) to the original URL (http://domain.com/wp-content/uploads/2011/08/example_2a.jpg). To use this function, simply:

    [php]$url = wps_get_original_image( $url );[/php]

    Here is the script that can be added to your functions.php:

    [php]<!--?php function wps_get_original_image( $url ) { global $_wp_additional_image_sizes; $new_url = $url; // Get All Image Sizes $builtin_sizes = array( 'large' =--> array(
    'width' => get_option('large_size_w'),
    'height' => get_option('large_size_h')
    ),
    'medium' => array(
    'width' => get_option('medium_size_w'),
    'height' => get_option('medium_size_h')
    ),
    'thumbnail' => array(
    'width' => get_option('thumbnail_size_w'),
    'height' => get_option('thumbnail_size_h')
    )
    );

    $image_sizes = array_merge( $builtin_sizes, $_wp_additional_image_sizes );

    //$url = 'http://webendev.com/review/scheumanndental/wp-content/uploads/2011/08/example_2a-300x158.jpg';

    // Parse URL
    $info = pathinfo( $url );

    // Check to see if it is a post-thumbnail: assuming size < 999x999 so -999x999.jpg = 12chars $pos = strrpos($info['basename'], '-', -1); $length = strlen( $info['basename'] ); if ( ( $length - $pos ) > 12 )
    return $url;

    // Check to see if image is indeed a thumbnail and not example-2.jpg

    // Get image size extensions, e.g. -200x200
    // Get image size width only extensions, e.g., -200x
    // Get image size height only extensions, e.g., x200.
    $image_exts = array();
    $image_exts_width = array();
    $image_exts_height = array();
    foreach ($image_sizes as $image_size) {
    $image_exts[] = '-'.$image_size['width'].'x'.$image_size['height'];
    $image_exts_width[] = '-'.$image_size['width'].'x';
    $image_exts_height[] = 'x'.$image_size['height'];
    }

    // Cycle through image size extensions, e.g. -200x200
    foreach ( $image_exts as $image_ext ) {
    //if found, simply replace with nothing (easy)
    $new_url = str_replace( $image_ext , '' , $url );

    //report changed url
    if ( $new_url != $url )
    break;
    }

    // if a new url hasn't been generated...
    if ( $new_url == $url ) {
    // Cycle through image width only extensions, e.g. -200x
    foreach ( $image_exts_width as $image_ext ) {

    // check for width, e.g., -200x
    $pos1 = strrpos( $info['basename'] , $image_ext , -1 );
    if ( $pos1 ) {
    // strip, & assign new url
    $new_url = $info['dirname'] . '/' . substr( $info['basename'] , 0 , $pos1 ) . '.' . $info['extension'];
    }

    if ( $new_url != $url )
    break;
    }

    // if a new url hasn't been generated...
    if ( $new_url == $url ) {
    // Cycle through image height only extensions, e.g. x200.
    foreach ( $image_exts_height as $image_ext ) {

    // check for height, e.g., x200
    $pos2 = strrpos( $info['basename'] , $image_ext , -1 );

    //example_2a-263x300.jpg -> example_2a.jpg
    if ( $pos2 ) {
    // get position of -, strip, & assign new url
    $pos3 = strrpos( $info['basename'] , '-' , -1 );
    $new_url = $info['dirname'] . '/' . substr( $info['basename'] , 0 , $pos3 ) . '.' . $info['extension'];
    }

    if ( $new_url != $url )
    break;
    }
    }
    }

    if ( $new_url != $url )
    return $new_url;
    else
    return $url;
    }
    [/php]

    Written by Travis Smith · Categorized: Tutorials, WordPress

    • « Previous Page
    • 1
    • …
    • 17
    • 18
    • 19
    • 20
    • 21
    • …
    • 25
    • Next Page »
    • Twitter
    • Facebook
    • LinkedIn
    • Google+
    • RSS

    Copyright © 2025 � WP Smith on Genesis on Genesis Framework � WordPress � Log in