How to relate a user object to taxonomy term?

Question

I am attempting to import several users, who each should have a connection with a term in a taxonomy named “firm” – but I don’t know how to make the connection…

Background:

FYI, I have already enabled WordPress taxonomy support for Users using plugin LH User Taxonomies, and taxonomy “firm” has already been registered. I am importing using plugin WPAllImport.

65 “firms” terms have been created via prior WPAllImport import. Term slugs underwent text processing on inbound company name field $company to strip spaces and convert to lowercase, in order to create a clean term slug.

All this is set up, and the question is not about enabling taxonomy support for Users.

The problem:

I am now importing many Users, and need to connect them to an existing “firm” term (ie. the company they work for). Unfortunately, WPAllImport does not support import to taxonomy terms for Users – but it does support PHP functions executed upon each user import, and actions like pmxi_after_xml_import, which fires after import.

The best way to match seems to be via slug – that is, matching inbound User field $company, after stripping spaces, against a “firm” term with matching unique slug. But how do I do this, and then how do we make the association in the database?

On each individual User import, logic may look something like this:

  • Identify inbound string $company
  • Strip spaces and make $company lowercase using my convert_company_name() function.
  • Identify taxonomy “firms”.
  • Step through “firms” taxonomy to find a term whose slug matches our processed $company string (eg. “widgetsinc” for User’s processed $company, matching “widgetsinc” term slug)
  • Associate this User with that slug, ie. set the term.
  • Any appropriate fallback.

I’m not sure how any of the code would be written for this.

wp set object terms seems like it might be involved?

Edit (2):

I think I have learned how to do a lot here. This seems to work, to a point…

// Relate user to "firm" taxonomy terms
function relate_user_to_firm($company, $username){

  // convert company name to slug format
  $company_slug = lowercase_and_strip($company);

  // use slug to find corresponding taxonomy term
  $term = get_term_by('slug', $company_slug, 'firm');
  // get the object id of this term
  $mytermid = $term->term_id;

  // get user's ID
  $user = get_user_by('login', $username);
  $user_id = $user->ID;

  // *** relate user to this term ***
  wp_set_object_terms( $user_id, $mytermid, 'firm' );

}

The trouble is, whilst the correct terms show under the “Firms” column on my Users listing page, the Users count against the actual term on the Firms listing page is not updated, it still shows 0. What’s going on there?

0
, Robert Andrews 4 years 2017-07-16T10:26:31-05:00 0 Answers 99 views 0

Leave an answer

Browse
Browse