Thursday, October 18, 2012

Add select menu to filter by custom field in admin

Adding this code to the functions.php of your wordpress theme will add a select menu with a list of all custom fields, just select the field you want to filter by and click the filter button.

add_filter( 'parse_query', 'ba_admin_posts_filter' );
add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
function ba_admin_posts_filter( $query )
{
    global $pagenow;
    if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
        $query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];
    if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
        $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
    }
}
function ba_admin_posts_filter_restrict_manage_posts()
{
    global $wpdb;
    $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
    $fields = $wpdb->get_results($sql, ARRAY_N);
?>
<select name="ADMIN_FILTER_FIELD_NAME">
<option value=""><?php _e('Filter By Custom Fields', 'baapf'); ?></option>
<?php
    $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
    $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
    foreach ($fields as $field) {
        if (substr($field[0],0,1) != "_"){
        printf
            (
                '<option value="%s"%s>%s</option>',
                $field[0],
                $field[0] == $current? ' selected="selected"':'',
                $field[0]
            );
        }
    }
?>
</select> <?php _e('Value:', 'baapf'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
<?php
}

Enable TinyMCE editor for post the_excerpt

Adding this code to the functions.php of your wordpress theme will add the TinyMCE editor to the post excerpt textarea.

function tinymce_excerpt_js(){ ?>
<script type="text/javascript">
        jQuery(document).ready( tinymce_excerpt );
            function tinymce_excerpt() {
                jQuery("#excerpt").addClass("mceEditor");
                tinyMCE.execCommand("mceAddControl", false, "excerpt");
            }
</script>
<?php }
add_action( 'admin_head-post.php', 'tinymce_excerpt_js');
add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js');
function tinymce_css(){ ?>
<style type='text/css'>
            #postexcerpt .inside{margin:0;padding:0;background:#fff;}
            #postexcerpt .inside p{padding:0px 0px 5px 10px;}
            #postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; }
</style>
<?php }
add_action( 'admin_head-post.php', 'tinymce_css');
add_action( 'admin_head-post-new.php', 'tinymce_css');

Create most recent posts dashboard widget

Adding this code to the functions.php of your wordpress theme will create a new dashboard widget showing the five most recent posts.
function wps_recent_posts_dw() {
?>
   <ol>
     <?php
          global $post;
          $args = array( 'numberposts' => 5 );
          $myposts = get_posts( $args );
                foreach( $myposts as $post ) :  setup_postdata($post); ?>
                    <li> (<? the_date('Y / n / d'); ?>) <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
          <?php endforeach; ?>
   </ol>
<?php
}
function add_wps_recent_posts_dw() {
       wp_add_dashboard_widget( 'wps_recent_posts_dw', __( 'Recent Posts' ), 'wps_recent_posts_dw' );
}
add_action('wp_dashboard_setup', 'add_wps_recent_posts_dw' );

Remove admin color scheme options from user profile

Adding this codeto the functions.php of your wordpress theme will remove the admin color scheme from the user profile.

function admin_color_scheme() {
   global $_wp_admin_css_colors;
   $_wp_admin_css_colors = 0;
}
add_action('admin_head', 'admin_color_scheme');

Display EXIF metadata in media library admin column

Adding this snippet to the functions.php of your wordpress theme will create a new column within the media library that will display EXIF metadata. Including, (credit, camera, focal length, aperture, iso, shutter speed, timestamp, copyright).

add_filter('manage_media_columns', 'posts_columns_attachment_exif', 1);
add_action('manage_media_custom_column', 'posts_custom_columns_attachment_exif', 1, 2);
function posts_columns_attachment_exif($defaults){
    $defaults['wps_post_attachments_exif'] = __('EXIF');
    return $defaults;
}
function posts_custom_columns_attachment_exif($column_name, $id){
        if($column_name === 'wps_post_attachments_exif'){
           $meta = wp_get_attachment_metadata($id);
           if($meta[image_meta][camera] != ''){
           echo "CR:  ".$meta[image_meta][credit]."<hr />";
           echo "CAM:  ".$meta[image_meta][camera]."<hr />";
           echo "FL:  ".$meta[image_meta][focal_length]."<hr />";
           echo "AP:  ".$meta[image_meta][aperture]."<hr />";
           echo "ISO:  ".$meta[image_meta][iso]."<hr />";
           echo "SS:  ".$meta[image_meta][shutter_speed]."<hr />";
           echo "TS:  ".$meta[image_meta][created_timestamp]."<hr />";
           echo "C:  ".$meta[image_meta][copyright];
           }
    }
}

Remove menu items from 3.3 admin bar

Adding this codeto the functions.php of your wordpress theme will remove menu items from the wordpress 3.3 admin bar.
function wps_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_node('wp-logo');
    $wp_admin_bar->remove_node('about');
    $wp_admin_bar->remove_node('wporg');
    $wp_admin_bar->remove_node('documentation');
    $wp_admin_bar->remove_node('support-forums');
    $wp_admin_bar->remove_node('feedback');
    $wp_admin_bar->remove_node('view-site');
}
add_action( 'wp_before_admin_bar_render', 'wps_admin_bar' )

Monday, October 1, 2012

Prevent direct file access to functions.php

if (!empty($_SERVER['SCRIPT_FILENAME']) && 'functions.php' == basename($_SERVER['SCRIPT_FILENAME']))
{
die ('No access!');
}

Add rel=”lightbox” to all images embedded in a post

Adding this snippet to the functions.php of your wordpress theme will add a rel=”lightbox” attribute to all images embedded in your post. Also note that on line 05 you can change the rel=”lightbox” to whatever you need as some image viewer scripts will use rel=”thumbnail” for example. This snippet will also add the post title as the title attribute of the images anchor tag.
add_filter('the_content', 'my_addlightboxrel');
function my_addlightboxrel($content) {
       global $post;
       $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
       $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';
       $content = preg_replace($pattern, $replacement, $content);
       return $content;
}

Attach PDF files to post with custom metabox file selection

Adding this snippet to the functions.php of your wordpress theme will create a new metabox within your post editing screen with a select menu listing all PDF files. Adding the second snippet in your wordpress template in the location you wish to display the files URL.

add_action("admin_init", "pdf_init");
add_action('save_post', 'save_pdf_link');
function pdf_init(){
        add_meta_box("my-pdf", "PDF Document", "pdf_link", "post", "normal", "low");
        }
function pdf_link(){
        global $post;
        $custom  = get_post_custom($post->ID);
        $link    = $custom["link"][0];
        $count   = 0;
        echo '<div class="link_header">';
        $query_pdf_args = array(
                'post_type' => 'attachment',
                'post_mime_type' =>'application/pdf',
                'post_status' => 'inherit',
                'posts_per_page' => -1,
                );
        $query_pdf = new WP_Query( $query_pdf_args );
        $pdf = array();
        echo '<select name="link">';
        echo '<option class="pdf_select">SELECT pdf FILE</option>';
        foreach ( $query_pdf->posts as $file) {
           if($link == $pdf[]= $file->guid){
              echo '<option value="'.$pdf[]= $file->guid.'" selected="true">'.$pdf[]= $file->guid.'</option>';
                 }else{
              echo '<option value="'.$pdf[]= $file->guid.'">'.$pdf[]= $file->guid.'</option>';
                 }
                $count++;
        }
        echo '</select><br /></div>';
        echo '<p>Selecting a pdf file from the above list to attach to this post.</p>';
        echo '<div class="pdf_count"><span>Files:</span> <b>'.$count.'</b></div>';
}
function save_pdf_link(){
        global $post;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ return $post->ID; }
        update_post_meta($post->ID, "link", $_POST["link"]);
}
add_action( 'admin_head', 'pdf_css' );
function pdf_css() {
        echo '<style type="text/css">
        .pdf_select{
                font-weight:bold;
                background:#e5e5e5;
                }
        .pdf_count{
                font-size:9px;
                color:#0066ff;
                text-transform:uppercase;
                background:#f3f3f3;
                border-top:solid 1px #e5e5e5;
                padding:6px 6px 6px 12px;
                margin:0px -6px -8px -6px;
                -moz-border-radius:0px 0px 6px 6px;
                -webkit-border-radius:0px 0px 6px 6px;
                border-radius:0px 0px 6px 6px;
                }
        .pdf_count span{color:#666;}
                </style>';
}
function pdf_file_url(){
        global $wp_query;
        $custom = get_post_custom($wp_query->post->ID);
        echo $custom['link'][0];
}

 echo pdf_file_url();
My PDF File

Remove current theme from “Right Now” dashboard widget

add_filter( 'ngettext', 'wps_remove_theme_name' );
if(!function_exists('wps_remove_theme_name')) {
function wps_remove_theme_name($translated) {
     $translated = str_ireplace('Theme %1$s with',  '',  $translated );
     return $translated;
  }
}

Insert calendar into wp_nav_menu

Needed this for a recent project as a client wanted to display the wordpress calendar as a dropdown item within the menu. Add this snippet to the functions.php of your wordpress theme will add a new menu item to your wp_nav_menu that has a submenu calendar.
add_filter('wp_nav_menu_items','add_calendar', 10, 2);
function add_calendar($items, $args) {
    if( $args->theme_location == 'header-navigation' )
        return $items . '<li><a href="#">Calendar</a><ul class="sub-menu"><li>' . get_calendar(true,false) . '</li></ul></li>';
}

Shortcode for HTML5 audio in posts and pages

Adding this snippet to the functions.php of your wordpress theme will create a new shortcode for HTML5 audio. Just add the second snippet of shortcode to a post or page to add HTML5 audio.


function html5_audio($atts, $content = null) {
        extract(shortcode_atts(array(
                "src" => '',
                "autoplay" => '',
                "preload"=> 'true',
                "loop" => '',
                "controls"=> ''
        ), $atts));
        return '<audio src="'.$src.'" autoplay="'.$autoplay.'" preload="'.$preload.'" loop="'.$loop.'" controls="'.$controls.'" autobuffer />';
}
add_shortcode('audio5', 'html5_audio');

[audio5 src="http://your-site/videos/your-video.mp4" loop="true" autoplay="autoplay" preload="auto" loop="loop" controls=""]

Send email notification when user role changes

function user_role_update( $user_id, $new_role ) {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "Role changed: ".$site_url."";
        $message = "Hello " .$user_info->display_name . " your role has changed on ".$site_url.", congratulations you are now an " . $new_role;
        wp_mail($to, $subject, $message);
}
add_action( 'set_user_role', 'user_role_update', 10, 2);

Send email notification when profile updates

function user_profile_update( $user_id ) {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "Profile Updated: ".$site_url."";
        $message = "Hello " .$user_info->display_name . "\nYour profile has been updated!\n\nThank you for visiting\n ".$site_url."";
        wp_mail( $to, $subject, $message);
}
add_action( 'profile_update', 'user_profile_update', 10, 2);

Add class to next and previous post_link

I recently needed to use this for a theme I was building figured I would post the results up here for everyone. Adding this snippet to the functions.php of your wordpress theme will add a custom class to next and previous post_link.
function add_class_next_post_link($html){
    $html = str_replace('<a','<a class="next"',$html);
    return $html;
}
add_filter('next_post_link','add_class_next_post_link',10,1);
function add_class_previous_post_link($html){
    $html = str_replace('<a','<a class="prev"',$html);
    return $html;
}
add_filter('previous_post_link','add_class_previous_post_link',10,1);

Increase the excerpt field height

Adding this snippet to the functions.php of your wordpress theme will increase height of the excerpt field within your post editing screen.
add_action('admin_head', 'excerpt_textarea_height');
function excerpt_textarea_height() {
        echo'
        <style type="text/css">
                #excerpt{ height:500px; }
        </style>
        ';
}

Increase the excerpt field height

Adding this snippet to the functions.php of your wordpress theme will increase height of the excerpt field within your post editing screen.
add_action('admin_head', 'excerpt_textarea_height');
function excerpt_textarea_height() {
        echo'
        <style type="text/css">
                #excerpt{ height:500px; }
        </style>
        ';
}

Automatically wrap images in the_content with custom html

Adding this snippet to the functions.php of your wordpress theme will automatically wrap images in the_content with any custom HTML that you wish.
function filter_images($content){
    return preg_replace('/<img (.*) \/>\s*/iU', '<span class="className"><b><img \1 /></b></span>', $content);
}
add_filter('the_content', 'filter_images');

Remove admin color scheme options from user profile

Adding this snippet to the functions.php of your wordpress theme will remove the admin color scheme from the user profile.

function admin_color_scheme() {
   global $_wp_admin_css_colors;
   $_wp_admin_css_colors = 0;
}
add_action('admin_head', 'admin_color_scheme');

Disable the help menu for admin only

Adding this snippet to the functions.php of your wordpress theme will display the help menu for the admin only.

function hide_help() {
    if(!is_admin()){
    echo '<style type="text/css">
            #contextual-help-link-wrap { display: none !important; }
          </style>';
    }
}
add_action('admin_head', 'hide_help');

Display EXIF metadata in media library admin column

For anyone that uses wordpress for photography you should find this snippet useful. Adding this snippet to the functions.php of your wordpress theme will create a new column within the media library that will display EXIF metadata. Including, (credit, camera, focal length, aperture, iso, shutter speed, timestamp, copyright).

add_filter('manage_media_columns', 'posts_columns_attachment_exif', 1);
add_action('manage_media_custom_column', 'posts_custom_columns_attachment_exif', 1, 2);
function posts_columns_attachment_exif($defaults){
    $defaults['wps_post_attachments_exif'] = __('EXIF');
    return $defaults;
}
function posts_custom_columns_attachment_exif($column_name, $id){
        if($column_name === 'wps_post_attachments_exif'){
           $meta = wp_get_attachment_metadata($id);
           if($meta[image_meta][camera] != ''){
           echo "CR:  ".$meta[image_meta][credit]."<hr />";
           echo "CAM:  ".$meta[image_meta][camera]."<hr />";
           echo "FL:  ".$meta[image_meta][focal_length]."<hr />";
           echo "AP:  ".$meta[image_meta][aperture]."<hr />";
           echo "ISO:  ".$meta[image_meta][iso]."<hr />";
           echo "SS:  ".$meta[image_meta][shutter_speed]."<hr />";
           echo "TS:  ".$meta[image_meta][created_timestamp]."<hr />";
           echo "C:  ".$meta[image_meta][copyright];
           }
    }
}

Disable dragging of metaboxes within admin

Adding this snippet to the functions.php of your wordpress theme will disable all dragging of metaboxes within the admin. Please note that this includes dashboard widgets as well.

function disable_drag_metabox() {
    wp_deregister_script('postbox');
}
add_action( 'admin_init', 'disable_drag_metabox' );

Include external file shortcode

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
  if ($file!='')
    return @file_get_contents($file);
}
add_shortcode( 'show_file', 'show_file_func' );

[show_file file="http://www.mysite.com/somefile.html"]

Remove inline style from gallery shortcode

The WordPress gallery shortcode will add some inline CSS to your document however if I’m like many of you, I would rather use my own. Adding the above snippet to the functions.php of your wordpress theme will disable the default gallery styles from being inserted into the page.
add_filter( 'use_default_gallery_style', '__return_false' );

Highlight keywords in search results within the_excerpt and the_title

You can add to the functions.php of your wordpress theme to highlight keywords in search results for the_excerpt and the_title
function wps_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');

Remove unneeded images / thumbnail sizes

Adding some or all of these lines of code to the functions.php of your wordpress theme will effectively remove some of the default images sizes that may be unneeded. Make sure to include both the _w _h for width and height,

   update_option( 'thumbnail_size_h', 0 );
    update_option( 'thumbnail_size_w', 0 );
    update_option( 'medium_size_h', 0 );
    update_option( 'medium_size_w', 0 );
    update_option( 'large_size_h', 0 );
    update_option( 'large_size_w', 0 );

Allow more HTML tags in the editor

By default the wordpress editor does not allow some tags and will strip them out. Adding this snippet to the functions.php of your wordpress theme will enable you to use HTML tags like iframe, name, class etc…

function jb_change_mce_options($initArray) {
        $ext = 'pre[id|name|class|style],iframe[align|longdesc| name|width|height|frameborder|scrolling|marginheight| marginwidth|src]';
        if ( isset( $initArray['extended_valid_elements'] ) ) {
                $initArray['extended_valid_elements'] .= ',' . $ext;
        } else {
                $initArray['extended_valid_elements'] = $ext;
        }
        return $initArray;
}
add_filter('tiny_mce_before_init', 'jb_change_mce_options');

Adjust default sizes for embedded content

Adding this snippet to the functions.php of your wordpress theme will let you update the default embed sizes
function wps_embed_size($embed_size){
    if(is_single()){
        $embed_size['height'] = 240;
        $embed_size['width']  = 380;
    }
    return $embed_size;
}
add_filter('embed_defaults', 'wps_embed_size');

Hide update nag within the admin

Adding this snippet to the functions.php of your wordpress theme will hide the update nag within the wordpress admin.

function remove_upgrade_nag() {
   echo '<style type="text/css">
           .update-nag {display: none}
         </style>';
}
add_action('admin_head', 'remove_upgrade_nag');

Check if post / page has a gallery

Adding this snippet to your wordpress theme will let you check to see if a post contains the gallery shortcode. Add this code to the single.php template of your wordpress theme inside the loop.
if (strpos($post->post_content,'[gallery') === false){
  echo 'no gallery';
}else{
  echo 'has gallery';
}

Add custom field automatically when post or page is publish

Adding this snippet to the functions.php of your wordpress theme will add a custom field to a post or page when published. Don’t forget to update the FIELD_NAME and the CUSTOM VALUE.
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post'. 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'FIELD_NAME', 'CUSTOM VALUE', true);
    }
}

Facebook open graph snippet to set default image

Adding this snippet to the functions.php of your wordpress theme will allow you to specify Facebook Open Graph information on your WordPress posts. Allowing you to specify which image should be displayed when sharing your article on Facebook among other things.
function diww_facebook_image() {
                echo '<meta property="fb:admins" content="ADMIN_ID" />';
                echo '<meta property="og:title" content="' . get_the_title() . '" />';
                echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />';
        global $post;
        if ( is_singular() ) { // only if a single post or page
                echo '<meta property="og:type" content="article" />';
                echo '<meta property="og:url" content="' . get_permalink() . '" />';
        if (has_post_thumbnail( $post->ID )) { // use featured image if there is one
                $feat_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
                echo '<meta property="og:image" content="' . esc_attr( $feat_image[0] ) . '" />';
         }else{ // use site logo in case no featured image
                echo '<meta property="og:image" content="http://yourdomain.com/logo.png" />';
         }
        }
        if ( is_home() ) { // for homepage only
                echo '<meta property="og:type" content="website" />';
                echo '<meta property="og:url" content="' . get_bloginfo('url') . '" />';
                echo '<meta property="og:image" content="http://yourdomain.com/logo.png" />';
        }
}
add_action( 'wp_head', 'diww_facebook_image' );

Hide post view and post preview admin buttons

Ever wanted to remove “preview & view” options from the new post and post edit admin screens. Add this code functions.php of your wordpress theme and don’t forget to update the post type array. Enter any post type you would like to remove the "view and preview" buttons from "custom post type, post, page".
function posttype_admin_css() {
    global $post_type;
    $post_types = array(
                        /* set post types */
                        'post_type_name',
                        'post',
                        'page',
                  );
    if(in_array($post_type, $post_types))
    echo '';
}
add_action( 'admin_head-post-new.php', 'posttype_admin_css' );
add_action( 'admin_head-post.php', 'posttype_admin_css' );

    echo
'<style type="text/css">#post-preview, #view-post-btn{display: none;}</style>'

Change default "Enter title here" text within post title input field

paste the code into your functions.php file.
function title_text_input( $title ){
     return $title = 'Enter new title';
}
add_filter( 'enter_title_here', 'title_text_input' );

Disable theme switching

Paste the following code into functions.php
add_action('admin_init', 'slt_lock_theme');
function slt_lock_theme() {
 global $submenu, $userdata;
 get_currentuserinfo();
 if ($userdata->ID != 1) {
  unset($submenu['themes.php'][5]);
  unset($submenu['themes.php'][15]);
 }
}

Remove menu items from WordPress admin bar

Paste this code into your theme functions.php file to remove menus from the admin bar.
function wps_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('wp-logo');
    $wp_admin_bar->remove_menu('about');
    $wp_admin_bar->remove_menu('wporg');
    $wp_admin_bar->remove_menu('documentation');
    $wp_admin_bar->remove_menu('support-forums');
    $wp_admin_bar->remove_menu('feedback');
    $wp_admin_bar->remove_menu('view-site');
}
add_action( 'wp_before_admin_bar_render', 'wps_admin_bar' );

How to execute shortcodes inside custom fields

By default, WordPress do not allows shortcodes to be executed inside custom fields. If for some reason you need to be able to execute a shortcode inside a specific custom field, here is an easy way to do it.

Just put this code into whatever page you are displaying the results of the shortcode, and change the your_custom_field_here to the name of your custom field.

<?php echo apply_filters('the_content', get_post_meta($post->ID, 'your_custom_field_here', true)); ?>