Create a gist now

Instantly share code, notes, and snippets.

This shortcode will reference a media item, configurable via attributes. Using a shortcode is more flexible and won't require database search/replace when migrating domains. Core would benefit from utilizing this system rather than inserting absolute paths to media URLs. A shortcode would keep media references relative to the site's domain.
<?php
/*
* Plugin Name: Media Shortcode
* Author: developdaly
* Version: 1.0
* Description: This shortcode will reference a media item, configurable via attributes. Using a shortcode is more flexible and won't require database search/replace when migrating domains.
*
* ex. [media id="97"] = <img src="http://example.com/97-300x150.jpg" class="thumbnail">
*
*/
add_shortcode( 'media', 'shortcode_media' );
add_filter( 'image_send_to_editor', 'shortcode_media_send_to_editor', 10, 7);
function shortcode_media_send_to_editor($html, $id, $alt, $title, $align, $url, $size ) {
$url = wp_get_attachment_url($id); // Grab the current image URL
$html = '[media id="' . $id . '" alt="' . $alt . '" title="' . $title . '" classes="' . $align . '" size="' . $size . '"]';
return $html;
}
function shortcode_media( $atts ) {
extract( shortcode_atts( array(
'id' => false,
'size' => 'medium',
'classes' => 'thumbnail',
'icon' => false,
'permalink' => false
), $atts ) );
// Get mime type
$type = get_post_mime_type( "{$id}" );
switch ( $type ) {
case 'image/jpeg' || 'image/png' || 'image/gif':
$image = wp_get_attachment_image_src( "{$id}", "{$size}", "{$classes}", "{$icon}" );
$before = '';
$after = '';
if( "{$permalink}" == true ) {
$before = '<a href="'. wp_get_attachment_url( "{$id}" ) .'" rel="attachment wp-att-'. "{$id}" .'">';
$after = '</a>';
}
$output = $before .'<img src="'. $image[0] .'" height="'. $image[2] .'" width="'. $image[1] .'" class="'. "{$classes}" .'">'. $after;
break;
case 'video/mpeg':
case 'video/mp4':
case 'video/quicktime':
return $base . "video.mov"; break;
case 'text/csv':
case 'text/plain':
case 'text/xml':
return $base . "text.txt"; break;
default:
return $base . "file.file";
}
return $output;
}
@developdaly
Owner

Two issues I can think of that would need to be resolved:

  1. The shortcode would have to be forced to render in the editor since shortcodes aren't executed there.
  2. While the media is flexible to its environment, the user may want the image to be hardcoded.
@briancnolan

This works great. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment