Categories
Uncategorized

WordPress: how to automatically convert custom fields to post tags

Hi all,

Sifting through stackoverflow.com I ran into this question: how do you add custom fields automatically as post tags in WordPress?

A while ago, someone asked something similar, and I put together a little script to help, but now I refined that script to be more encompassing. So, here’s a function to add custom fields automatically as post tags.

How it works

The vq20_convert_custom_fields_to_tags() function uses jQuery to retrieve the value of specific custom fields (which you can specify in an array, more on that below), and then adds those to the “tags” list on your post editor on save.

Instructions

  1. Put this script in your functions.php file in your WordPress install:
<?php

function vq20_convert_custom_fields_to_tags(){

    /*create list of custom fields to add as tags on save*/
    $custom_field_names = array();

    if(count($custom_field_names)>0) {?>
        <script type="text/javascript">
            jQuery(document).ready(function($){
            $('form#post').submit(function(event){
            <?php
                foreach($custom_field_names as $name){?>
                    cf_key = $('input[value="<?php echo $name; ?>"]').attr('id').replace('meta[', '').replace('][key]', '');
                    $('#new-tag-post_tag').val($('textarea[id*='+cf_key+']').val());
            <?php } ?>});
            });
        </script>
<?php
    }
}

add_action('admin_footer', 'vq20_convert_custom_fields_to_tags');

?>

 

* * * UPDATE * * *

A couple of  users in the comments below pointed out that the previous code was only adding the last custom field to the tag list, so I decided to go ahead and revamp the whole thing. Use this code instead:

<?php 

function vq20_convert_custom_fields_to_tags(){ ?>

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

    	// Create list of custom fields to add as tags on save
    	// (e.g. var custom_field_names = ['my_custom_field', 'my_other_custom_field', 'yet_another_custom_field'];)
    	var custom_field_names = [];

    	$('form#post').submit(function(){
    		if(custom_field_names.length > 0) {
	    		var custom_field_values = [];
	    		$('#postcustom tr[id^="meta-"]').each(function(){
	    			var meta_id = $(this).attr('id').substring($(this).attr('id').indexOf('-')).replace('-','');
	    			if ($.inArray($(':text[id="meta[' + meta_id + '][key]"]').val(), custom_field_names) !== -1) {
	    				custom_field_values.push($('textarea[id="meta[' + meta_id + '][value]"]').val().toLowerCase());
	    			}
	    		});
	    		var tags = custom_field_values.join(',');
	    		$('#new-tag-post_tag').val(tags);
	    	}
    	});

    });
  </script>
<?php }
add_action('admin_footer', 'vq20_convert_custom_fields_to_tags');

?>

 

  1. Add the names of the custom fields you would like to automatically add as tags to the custom_field_names array
    
    // Create list of custom fields to add as tags on save 
    // (e.g. var custom_field_names = ['my_custom_field', 'my_other_custom_field', 'yet_another_custom_field'];) 
    var custom_field_names = ['my_custom_field', 'my_other_custom_field'];


 

  1. Save/upload your functions.php file, and then go to your post, add the matching custom field(s), and their values should be added as tags as soon as you save the post.

Note: this only works for custom fields holding individual values!!! (i.e. only one value per custom field will be added as a tag)

Let me know what you think!

Happy tagging!

Categories
Uncategorized

Lesson learned: You can’t access DOM elements within an external iFrame

While working with Google Custom Search Engine (CSE), I needed to access elements within the <iframe> containing the search results it generated. Using jQuery, I tried to select the iframe first and its content:

$('#cse-search-results iframe').contents();

But as soon as I tried to do something with it, I’d get a “Error: Permission denied to access property ‘nodeType’” message.

Turns out, <iframes> follow the same origin policy, which prevents you from accessing them directly if they weren’t generated from your own domain. Of course, you can create a proxy file with PHP to retrieve the data first and then add the resulting HTML to your script to get around this problem.

I know, I know… it makes sense now. But I just didn’t know, so, lesson learned!

Categories
Uncategorized

My response to Stackoverflow’s ““invalid label” Firebug error with jQuery getJSON” question

“Invalid label” Firebug error with jQuery getJSON

Categories
Uncategorized

Smashing Magazine – jQuery Plugin Checklist: Should You Use That jQuery Plug-In?

jQuery Plugin Checklist: Should You Use That jQuery Plug-In?

Categories
Uncategorized

How to load CSS stylesheets dynamically with jQuery

Sometimes you may want to load a CSS stylesheet dynamically after your HTML page has loaded and certain conditions are met (for example, if an element with a specific class exists in the DOM). jQuery can help you accomplish that with only a few lines of code.

How to get there:

The HTML:

For this example, let’s say we need to load a stylesheet to format a div tag in the following HTML code:

<html>
<head>
<title>jQuery - Load CSS</title>
</head>
<body>
<div id="container" class="class">
<p>This is a div tag that was formatted using <a href="http://www.jquery.com" alt="Link to jQuery.com">jQuery</a>
</p></div>
</body>
</html>

The CSS:

This will be the CSS code in our sample stylesheet, “style.css”:

#container{
   border: 1px solid #000;
   background-color:#EEE;
   padding:8px;
   margin:8px;
   width: 200px;
}

The jQuery:

These are the jQuery functions we’ll use to get this done:

  • $() wrapper: as the main and most powerful jQuery function, we’ll use it to:
    • Execute code once the document has been loaded
    • Determine whether the #container div element exists in the DOM and, if true,
    • Create new HTML to link the style.css stylesheet to our page
  • append(): this jQuery function allows you to append new HTML code to any element in the DOM. For this example, we’ll attach a new <link> element to the <head> element of our document.

Bringing it all together:

With our HTML and CSS files in place, let’s get this done:

Load jQuery

  • Add the following code between the </body> and </html> tags in your HTML document (Note: your actual path might be different than the one on this example, depending on where your jquery.js file has been stored)
<script type="text/javascript" src="../jquery-1.4.2.min.js"></script>

Add the jQuery code

  • Right under the last line, add the following code:
<script type="text/javascript">

$(document).ready(function(){ //Once the document is ready, run the following code

   if($("#container").size()>0){ //Check if at least one element with the id "#container" exists within the DOM

      $("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />")); //if true, append the new <link> element to the <head> element in oor HTML page    }
});

</script>

 

 

* * * UPDATE * * *

Domenico Testa pointed out that the approach above doesn’t work correctly in IE. IE needs the  document.createStyleSheet() function to attach new stylesheet after loading the page:

document.createStyleSheet('style.css');

 

So, the final code should be:

<script type="text/javascript">
	$(document).ready(function(){

	if($("#container").size()>0){
			if (document.createStyleSheet){
				document.createStyleSheet('style.css');
			}
			else {
				$("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />"));
			}
		}
	});
</script>

View example here »

 

And that should be it. This technique is useful if your page has loaded and you want to load extra CSS files when certain elements exist in the DOM. This can help you save some bandwidth and make your page load faster.