Advertisement
luisabarca

Assign user custom term

Nov 4th, 2011
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.09 KB | None | 0 0
  1. <?php
  2. // add a select field to user profile
  3. add_action( 'show_user_profile', 'my_user_extra_profile_fields' );
  4. add_action( 'edit_user_profile', 'my_user_extra_profile_fields' );
  5.  
  6. function my_user_extra_profile_fields( $user )
  7. {
  8.     $args = array(
  9.         'taxonomy'         => 'luogolastminute',
  10.         'show_option_none' => '- Select -',
  11.         'name'             => '_mycategory',
  12.         'id'               => '_mycategory',
  13.         'selected'         => esc_attr( get_the_author_meta('_mycategory', $user->ID) ),
  14.         'hide_empty'       => 0
  15.     );
  16.  
  17.     ?>
  18.     <h3>Assigned category</h3>
  19.     <table class="form-table">
  20.         <tr>
  21.             <th><label for="_mycategory">Category</label></th>
  22.             <td>
  23.                 <?php wp_dropdown_categories( $args ) ?>
  24.                 <br />
  25.                 <span class="description">Select a category.</span>
  26.             </td>
  27.         </tr>
  28.     </table>
  29.     <?php
  30. }
  31.  
  32. // }}}
  33. // {{{
  34.  
  35. add_action( 'personal_options_update', 'my_save_extra_user_profile_fields' );
  36. add_action( 'edit_user_profile_update', 'my_save_extra_user_profile_fields' );
  37.  
  38. function my_save_extra_user_profile_fields( $user_id )
  39. {
  40.     if ( !current_user_can( 'edit_user', $user_id ) ) {
  41.         return false;
  42.     }
  43.    
  44.     if ( current_user_can('manage_options') ) {
  45.         $item = '';
  46.        
  47.         if ( isset($_POST['_mycategory']) && !empty($_POST['_mycategory']) ) {
  48.             $item = intval($_POST['_mycategory']);
  49.         }
  50.                
  51.         update_user_meta( $user_id, '_mycategory', $item );
  52.     }
  53. }
  54.  
  55. /*
  56.  * On save post
  57.  *
  58.  */
  59. add_action('save_post', 'my_save_postdata', 10, 2);
  60.  
  61. function my_save_postdata( $post_id )
  62.  
  63. {
  64.     // get the post from the post ID, to get the author ID
  65.     $post = get_post( $post_id );
  66.  
  67.     // get the ID from the user meta
  68.     $term_id = get_the_author_meta('_mycategory', $post->post_author );
  69.  
  70.     // get the term object
  71.     $term = get_term( $term_id, 'luogolastminute');
  72.  
  73.     // assign the term to the post
  74.     wp_set_object_terms( $post_id, $term->slug, $term->taxonomy );
  75. }
  76. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement