Joel Nagy .com

web technology is a way of life

screen-shot-2010-07-28-at-35411-pm

Ever want to use the WordPress Media Gallery for inserting and managing images that you insert in a custom field?  Usually you would need to use the media buttons to add the image and copy and paste the URL to your custom field.  This is rather cumbersome and not really possible if you’ve decided to create a custom post-type that doesn’t use the description field.  With a little modification of a core file and your own custom post-type you can add some additional functionality to pop open the media gallery and insert the URL into your custom field, even display the thumbnail as well. This first block of code contains a javascript function that will respond to the link we’ll create in the media gallery to insert the URL of the chosen image into your custom field. The next bit of code is the custom label and input for the custom field. And then a link to call the Media Gallery. Here we’ve added a parameter called location that identifies the id of the new input.

<script type="text/javascript">
function JNSetCustomMedia(loc, url) {
alert(loc+':'+url);
	try {
		jQuery('#'+loc).attr('value', url);
	} catch (e) { }
}
</script>

<label class="customLabel">URL:</label><input class="customInput" name="myURL" id="myURL" value="<?php echo $URL; ?>" size="60" />

<a class="thickbox" id="set-post-thumbnail" href="media-upload.php?post_id=77&amp;type=image&amp;location=myURL&amp;TB_iframe=1&amp;width=640&amp;height=394" title="Upload custom image">Upload custom image</a>

Inside wp-admin/includes/media.php search for “WPSetAsThumbnail” and before the if statement that checks ($send || $thumbnail || $delete) you need to add this code to add our new code to the $thumbnail html so the URL for the image can be passed back:


if (isset($_GET['location'])) { // look for a call to place image into specific custom field
 		$thumbnail .= ' <a href="javascript:(window.dialogArguments || opener || parent || top).JNSetCustomMedia(\''. $_GET['location'] .'\',\''.
 wp_get_attachment_url($post->ID) .'\');" style="margin: 0 0 0 -15px !important;">Insert custom image</a>';
	}


I’ve only tested this with WordPress 3.0 so far. I’m going to look into adding this functionality as a plugin so that the core media.php file will not need to be edited.

UPDATE: I’ve written a way to insert the links in the media gallery using JavaScript.  It works for all 4 methods (From Computer, From URL, Gallery, and Media Library.)  The code isn’t fully optimized but works well, simply place in your plugin via a call to a function from add_action: add_action(“admin_head”, array(&$this, “admin_custom_head”));

<script type="text/javascript">
//<![CDATA[
// Attach all query vars to the window object for easy access
window.query = new Object();
window.query.length = 0;
window.location.search.replace(
	new RegExp('([^?=&]+)=([^&#]*)?', 'g'),
	// populate the object with the values by name
	function($0, $1, $2) { window.query[$1] = $2; window.query.length++; }
);

function noop() { return; }

function checkForMediaInsert(loc) {
	// If there are Insert into Post buttons we move forward
	if (loc == null || loc == '') return;

	var submit = jQuery('td.savesend input.button').add('#go_button');
	if (submit.length > 0)
		submit.each(function() {
			insertMediaLocation(jQuery(this), loc);
		});

	setTimeout('checkForMediaInsert("'+ loc +'");', 1750);
}

function insertMediaLocation($t, loc) {
	// If we have not already added the link add it
	if ($t == null || loc == null || loc == '') return;
	var $d = null, url = '', $loc = jQuery('#insert-'+loc), href = '';
	var noophref = 'javascript:noop();';
	var id = $t.attr('name').replace(/send\[(\d+)\]/, '$1');

	// Grab URL from either place based on where we are
	if ($t.attr('id') == 'go_button')
		url = jQuery('#src')[0].value;
	else if (id != '')
		url = jQuery('THEAD#media-head-'+id+' +TBODY .urlfile').attr('title');
	if (url == '')
		href = noophref;
	else
		href = 'javascript:(window.dialogArguments || opener || parent || top).JNSetCustomMedia(\''+ loc +'\',\''+ url +'\');';

	if (!$t.hasClass(loc)) {
		// Drop in the link
		$d = jQuery('<a id="insert-'+loc+'" href="'+ href +'" style="margin: 0 0 0 15px !important;">Insert hero image</a>');
		$t.addClass(loc);
		$t.after($d);
	} else if ($t.attr('id') == 'go_button') {
		// Update href on From URL as it can change
		$loc.attr('href', href);
	}

	// If we are on the From URL page color based on whether the image is good
	if ($t.attr('id') == 'go_button') {
		$d = $loc;
		$d.css('color', $t.css('color')); // Get the disabled color (or active, but that'll be changed if all good)
		var goodbutton = jQuery('#status_img img[src$="yes.png"]');
		if (goodbutton.length > 0)
			$d.css('color', jQuery('A:first').css('color'));
		else
			$loc.attr('href', noophref);
	}
}

jQuery(function() {
	// If we have a location request we move forward
	var loc = window.query['location'];
	if (loc == null || loc == '') return;
	setTimeout('checkForMediaInsert("'+ loc +'");', 250);
});
//]]>
</script>
Enhanced by Zemanta
  • Comments Off
  • Filed under: Code
  • Facebook, Inc.
    Image via Wikipedia

    It’s quite simple to add the Facebook Like button to your blog.  If you don’t mind editing code and don’t want to deal with a plug-in you can simply drop in this bit of code (to your index.php & single.php files); note that the URL I’m using is based on a previous post for creating your own shortURL for WP:

    <iframe src="http://www.facebook.com/plugins/like.php?href=http://joelnagy.com/p<?php the_ID(); ?>&layout=standard&show_faces=false&width=425&action=like&colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:425px; height:30px;"></iframe>

    So please share the love and Like this!

    Reblog this post [with Zemanta]
  • 2 Comments
  • Filed under: Thoughts
  • Make Your Own Short URLs with WordPress

    Based on an earlier post about short URL issues I decided to update my blog to support it’s own short URL using the wordpress post ID.  So now any post on my site can be referenced via a shortURL, this one in fact is http://joelnagy.com/p176.

    In order for this to work I added this line to my .htaccess file in the root of my site to set it to redirect the short URL to the actual page (you need the full domain in the rule since WordPress works based on the REQUEST_URI) :

    RewriteRule ^/?p(\d+).*$ http://example.com/?p=$1 [QSA,L]
    

    This code is for use in header.php to create the <link> tags that will identify your page’s shorturl. First at the top of the page:

    <?php
    $this_ID = this_ID();
    $shortlinkid = ($this_ID != ''? $this_ID: (isset($_REQUEST['p']) && $_REQUEST['p'] != ''? $_REQUEST['p']: ''));
    $uri =  $_SERVER['REQUEST_URI'];
    if ($uri != '/blog/' && $shortlinkid != '')
    	$shortlinkid = "/p{$shortlinkid}";
    else if ($uri != '/blog/')
    	$shortlinkid = $uri;
    header("Link: <http://example.com{$shortlinkid}>; rel=\"shortlink\"");
    ?>
    

    Then inside the <head> (near other <link>s):

    <link rel="shorturl" href="http://example.com/<?php echo $shortlinkid; ?>" />
    <link rel="shortlink" type="text/html" href="http://example.com/<?php echo $shortlinkid; ?>" />
    <link rev="canonical" rel="self alternate shorter shorturl shortlink" href="http://example.com/<?php echo $shortlinkid; ?>" />
    

    Here is the this_ID() function that needs to be added to functions.php:

    function this_ID($force = false) {
    global $wp_query;
    	if (count($wp_query->posts) == 1 || $force)
    		return $wp_query->post->ID;
    	return '';
    }
    

    You can also add this code for tweeting the short URL (via chuchcrunch.com):

    <!-- This is a link to tweet the post using the new short URL -->
    <a rel="nofollow" target="_blank" href="http://twitter.com/home/?status=Just Read : <?php the_title();?> : http://example.com/p<?php the_ID(); ?>">Tweet This Post!</a>
    
  • Comments Off
  • Filed under: Code
  • Building off my previous entry Posting to WordPress via BlackBerry I’ve updated my wp-mail.php script to work with twitter_updater. It’s not the best solution but it works for now.

    require_once(ABSPATH.'/wp-content/plugins/twitter_updater/twitter_updater.php');
    
    do_action('publish_phone', $post_ID); // current update to WP
    
    if (function_exists(vc_doTwitterAPIPost)) { // if twitter_updated exists: update
    	$twitterURI = "/statuses/update.xml";
    	$twit = $post_title . ' ( ' . get_permalink($post_ID) . ' )';
    	$sendToTwitter = vc_doTwitterAPIPost('status='. $twit, $twitterURI);
    	echo "\n<p>" . sprintf(__('<strong>Twitter:</strong> %s : %s'), $sendToTwitter, wp_specialchars($post_title)) . '</p>';
    }

    I also made some other updates to compensate for some changes to my email system which now base64 encodes part of the message. Here I added this code to split at the “base64″ marker instead or “quoted-printable” marker:

    if (strpos($content, "Content-Transfer-Encoding: base64") !== false) {
    	$content = explode('Content-Transfer-Encoding: base64', $content);
    	$base64 = true;
    }
    $content = $content[1];
    if ($base64) $content = base64_decode($content);
    
    Reblog this post [with Zemanta]
  • Comments Off
  • Filed under: Code
  • Posting to WordPress via BlackBerry

    Yesterday, I posted my first post via BlackBerry after dealing with a few issues in WordPress that required a little modification to the wp-mail.php file. Seems that HTML emails don’t get through very well. So here are two basic steps to posting via email with your BlackBerry.

    Set up your BlackBerry user account as an Author. From the Dashboard, go to Users and add the email account you use on your Blackberry, your name and a different login and password (you won’t really need these as this account is for email posting) and the Role to Author.  Optionally, after you save go back to the new user and set the Display name as your name, so all posts look the same.

    Now overwrite your wp-mail.php file with this one.

    Here’s the code I changed:

    if ($content_type == 'multipart/alternative') {
    $content = explode('--'.$boundary, $content);
    $content = $content[2];
    $content = explode('Content-Transfer-Encoding: quoted-printable', $content);
    
    // BlackBerry Conversion Code
    $content = $content[0];
    $BODY = strpos($content, '<BODY>');
    if ($BODY !== false && $BODY > 0 && $body === false) $content =     substr($content, $BODY);
        $patterns = array ( '/<FONT FACE\=3D\"Verdana, Helvetica, Arial\"><SPAN STYLE\=3D\'font-size\:12\.0px\'>/',
            '/<\/SPAN><\/FONT>/',
            '/\=[\n\r]+/',
            '/<BODY>[\n\r]+/',
            '/<\/BODY>[\n\r]+/',
            '/<HTML>[\n\r]+/',
            '/<\/HTML>[\n\r]+/',
            '/<BR>/');
        $replace = array ('', '', '', '', '', '', '', '<br />');
        $content = preg_replace($patterns, $replace, $content) . '</p>'; // replace and add trailing P tag
        $content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><span><div>');
    } else if (stripos($content_transfer_encoding, 'quoted-printable') !== false) {
        $content = quoted_printable_decode($content);
    }
    $content = trim($content);

    Try it out, let me know if you have any issues.

  • 9 Comments
  • Filed under: Code