Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created December 16, 2015 09:46
Show Gist options
  • Save fumikito/14f6b459b53a2e6bf8a2 to your computer and use it in GitHub Desktop.
Save fumikito/14f6b459b53a2e6bf8a2 to your computer and use it in GitHub Desktop.
Add term meta example
<?php
the_post();
/**
* Get color function.
*
* Get term meta on loop is little bit annoying.
* You should define some wrapper function.
*/
function get_color($tag){
$term = get_term_by('name', $tag, 'post_tag');
return get_term_meta($term->term_id, 'my_color', true);
}
// If color is set, background-color will change.
$color = false;
if( has_tag('テストタグ') ){
foreach( get_the_tags() as $tag ){
$color = get_term_meta($tag->term_id, 'my_color', true);
}
var_dump($color);
}
?>
<?php if( $color ): ?>
<div style="background-color: #<?= ltrim($color, '#') ?>">
<?php else: ?>
<div>
<?php endif; ?>
<h1><?php the_title() ?></h1>
<div><?php the_content() ?></div>
</div>
<?php
/**
* Show field on amdmin screen
* @param stdClass $term
* @param string $taxonomy
*/
add_action( 'post_tag_edit_form_fields', function ( $term, $taxonomy ) {
// Load Iris (WP's color picker)
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script('wp-color-picker');
?>
<tr>
<script>
jQuery(document).ready(function($){
$('#my-color').wpColorPicker();
});
</script>
<?php wp_nonce_field( 'term_color', '_my_termmeta', false ); ?>
<th><label for="my-color">テーマカラー</label></th>
<td>
<input type="color" name="my-color" id="my-color"
value="<?= esc_attr( get_term_meta( $term->term_id, 'my_color', true ) ) ?>" placeholder="#ffffff"/>
</td>
</tr>
<?php
}, 10, 2 );
/**
* Save term meta
*
* @param int $term_id
* @param string $taxonomy
*/
add_action( 'edited_terms', function ( $term_id, $taxonomy ) {
// Check and verify nonce.
if ( 'post_tag' == $taxonomy && isset( $_POST['_my_termmeta'] ) && wp_verify_nonce( $_POST['_my_termmeta'], 'term_color' ) ) {
// Save term meta
update_term_meta( $term_id, 'my_color', $_POST['my-color'] );
}
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment