Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom fields to post tages
<?php
/*
Plugin Name: Custom Field to Tag
Author: Christopher Davis
Author URI: http://www.christopherguitar.net/
*/
/**
* CHANGE THIS! what is your custom field's name?
*/
define( 'WPSE29498_FIELD', 'custom_field_name' );
/**
* CHANGE THIS! what post type?
*/
define( 'WPSE29498_TYPE', 'post' );
// stop editing here.
register_activation_hook( __FILE__, 'wpse29498_field_to_tag' );
function wpse29498_field_to_tag()
{
$posts = get_posts(
array(
'post_type' => WPSE29498_TYPE,
'post_status' => array( 'publish', 'draft', 'pending', 'future' ),
'numberposts' => -1,
'meta_key' => WPSE29498_FIELD
)
);
if( empty( $posts ) ) return;
foreach( $posts as $p )
{
if( $meta = get_post_meta( $p->ID, WPSE29498_FIELD, true ) )
{
wp_set_post_terms( $p->ID, $meta, 'post_tag', true );
}
}
}
add_action( 'save_post', 'wpse29498_save_post' );
function wpse29498_save_post( $post_id )
{
if( $meta = get_post_meta( $post_id, WPSE29498_FIELD, true ) )
{
// get the current post tag
$terms = wp_get_object_terms( $p->ID, 'post_tag', 'name' );
// if our term is already there, bail
if( in_array( $meta, $terms ) ) return;
// add the term if not
wp_set_post_terms( $post_id, $meta, 'post_tag', true );
}
}
@elundmark

This comment has been minimized.

Copy link

@elundmark elundmark commented Apr 6, 2012

Works like a charm! :) Yuo saved me countless hours of work, exporting 22.000 entries to tags...

@smdhtv

This comment has been minimized.

Copy link

@smdhtv smdhtv commented Apr 26, 2012

This plugin is awesome but requires admin to save. Do you have a way to make this work for anytime a post is published. I am using autoblogged and it doesn't trigger this plugin.

@smdhtv

This comment has been minimized.

Copy link

@smdhtv smdhtv commented Apr 26, 2012

Also, how would you modify it so it works with multiple fields.

@chrisguitarguy

This comment has been minimized.

Copy link
Owner Author

@chrisguitarguy chrisguitarguy commented Apr 30, 2012

It should get triggered if your auto blogger is using wp_insert_post. to make it work with multiple fields, just loop in the wpse29498_save_post function.

eg.

<?php
foreach($meta_fields as $meta_key)
{
    // check like agove, but use continue instead of return
}
@guynext2

This comment has been minimized.

Copy link

@guynext2 guynext2 commented Jan 5, 2016

hello could you tell me how to make it work for all custom fields, so that it would add each field's value to new tag. Not just one field and one tag. Thank you.

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