Automatically generate tags based on Post Object (ACF) titles in WordPress - wordpress

I'm creating a custom post type for our projects page. I've also made a custom posts type for our employees.
With ACF I've made a Relationship field which where you can add the team members to a project and it's displayed on the website.
Based in the selected team members posts in the relationship field I would like the generate a tag for each title (Employee name) that is loaded in the relationship field.
This is were I'm stuck now.
The name in the Post Object is called teamleden. I've tried adding code to my customs posts type file but it doesn't work.
<?php
// save post action
add_action('acf/save_post', 'set_employee_tags_on_save_update', 20);
/**
* #param $post_id int|string
*/
function set_employee_tags_on_save_update($post_id) {
// get our current post object
$post = get_post($post_id);
// if post is object
if(is_object($post)) {
// check we are on the projects custom type and post statuses are either publish or draft
// change 'projects' post type to your post type name which has the relationship field
if($post->post_type === 'projects' && ($post->post_status === 'publish' || $post->post_status === 'draft')) {
// get relationship field employees
// this example uses Post Object as the Return Format and is a multiple value
// change get field param 'employees' to your relationship field name
$employees = get_field('employees');
// team member tags to set empty array
$team_member_tags_to_set = [];
// if employees has value or values
if($employees) {
// get all of our current team member tags
// change 'team_members' taxonomy value to your members taxonomy name
$team_member_tags = get_terms([
'taxonomy' => 'team_members',
'orderby' => 'name',
'order' => 'ASC'
]);
// empty array for existing team member tags
$existing_team_member_tags = [];
// if we have existing team member tags
if(!empty($team_member_tags)) {
// foreach team member tags as team member tag
foreach($team_member_tags as $team_member_tag) {
// add existing team member to our existing team member tags array by tag ID => tag name
// this is so we can use this later to check if a team member tag already exists so we dont create duplicates
$existing_team_member_tags[$team_member_tag->ID] = $team_member_tag->name;
}
}
// foreach employees as employee
foreach($employees as $employee) {
// get the title for current employee
$title = get_the_title($employee->ID);
// search existing team members array and return the tag id via key
$existing_team_member_tag_id = array_search($title, $existing_team_member_tags);
// if we have an existing team member tag id
if($existing_team_member_tag_id) {
// add the existing team member tag id as integer to array
$team_member_tags_to_set[] = (int)$existing_team_member_tag_id;
} else {
// else create a new tag for team member by adding title (name) as string to array
$team_member_tags_to_set[] = (string)$title;
}
}
}
// remove the action
remove_action('acf/save_post', 'acf_save_post');
// set post tags for this post id, removing any unused team member tags if relationship field team members are changed
wp_set_object_terms($post_id, $team_member_tags_to_set, $taxonomy = 'team_members', false);
// re add the action
add_action('acf/save_post', 'acf_save_post');
}
}
// finally return
return;
}

This is not tested but should get you on the right track.
You will need to add this in your function.php.
Reference to things you will need to change in my example code...
projects post_type is the post type name which this code fires when post is saved or updated.
employees is the name of the acf relationship field in the projects post type.
team_members is the custom tag taxonomy name which you should have working on your projects post type.
Basically what this code does, is when a projects post is saved, published or updated using the acf/save_post action. It gets the acf relationship field member data for this post. If there are members in the field, it then gets all existing team member tags and creates a simple array of existing member tags by ID => Title(name).
It then loops through all members in the relationship field, and checks if tag already exists for member, if it does it adds the existing member tag (int) ID to the $team_member_tags_to_set array. If no existing member tag is found, we just add the member title (name) as a (string) to the $team_member_tags_to_set array.
After all this is done, we simply use wp_set_post_tags() passing our $team_member_tags_to_set array to update team_members taxonomy terms for the current projects post.
I've also set append to false in wp_set_post_tags() which removes all previous tags and creates a new set of tags. This will help if members get updated in the acf relationship field.
https://developer.wordpress.org/reference/functions/wp_set_post_tags/
See code below, and read my comments so you know whats happening.
<?php
// save post action
add_action('acf/save_post', 'set_employee_tags_on_save_update', 20);
/**
* #param $post_id int|string
*/
function set_employee_tags_on_save_update($post_id) {
// get our current post object
$post = get_post($post_id);
// if post is object
if(is_object($post)) {
// check we are on the projects custom type and post statuses are either publish or draft
// change 'projects' post type to your post type name which has the relationship field
if($post->post_type === 'projects' && ($post->post_status === 'publish' || $post->post_status === 'draft')) {
// get relationship field employees
// this example uses Post Object as the Return Format and is a multiple value
// change get field param 'employees' to your relationship field name
$employees = get_field('employees');
// team member tags to set empty array
$team_member_tags_to_set = [];
// if employees has value or values
if($employees) {
// get all of our current team member tags
// change 'team_members' taxonomy value to your members taxonomy name
$team_member_tags = get_terms([
'taxonomy' => 'team_members',
'orderby' => 'name',
'order' => 'ASC'
]);
// empty array for existing team member tags
$existing_team_member_tags = [];
// if we have existing team member tags
if(!empty($team_member_tags)) {
// foreach team member tags as team member tag
foreach($team_member_tags as $team_member_tag) {
// add existing team member to our existing team member tags array by tag ID => tag name
// this is so we can use this later to check if a team member tag already exists so we dont create duplicates
$existing_team_member_tags[$team_member_tag->ID] = $team_member_tag->name;
}
}
// foreach employees as employee
foreach($employees as $employee) {
// get the title for current employee
$title = get_the_title($employee->ID);
// search existing team members array and return the tag id via key
$existing_team_member_tag_id = array_search($title, $existing_team_member_tags);
// if we have an existing team member tag id
if($existing_team_member_tag_id) {
// add the existing team member tag id as integer to array
$team_member_tags_to_set[] = (int)$existing_team_member_tag_id;
} else {
// else create a new tag for team member by adding title (name) as string to array
$team_member_tags_to_set[] = (string)$title;
}
}
}
// remove the action
remove_action('acf/save_post', 'acf_save_post');
// set post tags for this post id, removing any unused team member tags if relationship field team members are changed
wp_set_post_tags($post_id, $team_member_tags_to_set, false);
// re add the action
add_action('acf/save_post', 'acf_save_post');
}
}
// finally return
return;
}

Related

How to set the value of an entity reference field with the value of another entity reference field in a hook function - D9

I am using a hook function to create a commerce product when a node type of PL is created.
I have 2 Entity Reference fields:
Name of Project - Which references content
Type of Use - Which references a taxonomy term
Everything works and the title field is set correctly except for the 2 field values, field_name_of_project and field_type_of_use.
What could I be doing wrong.
Here's my code:
<?php
/**
* #file
* file for the PL Product Creation module, which creates a product and product variations when a Pl node is created.
*
*/
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Implementation of hook_entity_insert().
*/
function pl_product_creation_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'pl_node') {
// Get the pl node properties
$name_of_project = $entity->field_name_of_project->entity->getTitle();
$type_of_use = $entity->field_type_of_use->entity->getName();
// Load the product
$pl_product_title = 'Products at ' . $name_of_project;
// Load the product storage.
$entity_type_manager = \Drupal::service('entity_type.manager');
$product_storage = $entity_type_manager->getStorage('commerce_product');
// Load the product by title.
$pl_product = $product_storage->loadByProperties(['title' => $pl_product_title]);
// Check if the Pl product exists
if (!empty($pl_product)) {
// Load the Pl product
$pl_product = reset($pl_product);
}
else {
// Create a new Pl product
$pl_product = Product::create([
'type' => 'pl',
]);
// Set the title field.
$pl_product->setTitle($pl_product_title);
// Set the values of the custom fields.
$pl_product->set('field_name_of_project', $name_of_project);
$pl_product->set('field_type_of_use', $type_of_use);
// Save the product entity.
$pl_product->save();
}
}
}
I was finally able to figure it out. Posting here in case someone needs this in the future.
// Set the values of the custom fields.
$pl_product->set('field_name_of_project', $entity->field_name_of_project->entity);
$pl_product->set('field_type_of_use', $entity->field_type_of_use->entity);

Populate WordPress Post dynamically on Gravity Forms

I have a custom post type named Student on WordPress that Adds new students. You can fill out the Students name, Student description and Student Admission Number.
I have also created a gravity form where a potential sponsor can submit their details when they want to sponsor a student. However, the sponsors need to fill in the Students Name and Student Admission Number on the form. Is it possible to have the fields Student Name and Student Admission Number populate dynamically on the gravity form?
The form is being displayed on the same page as the student post. The student name is the post title. The student registration number is a custom field created using advanced custom field plugin.The field label for student admission number is Student Admission Number and field name is student_admission_number on the custom field. On gravity form, we have Student Name and Student Admission Number as form fields.
How can I have the fields Student Name and Student Admission Number populate dynamically on the gravity form?
I tried adding the following code to my functions.php file but it did not work.
// Add a custom shortcode to display the form
function custom_gravity_form_shortcode( $atts ) {
$current_post = get_post();
// Get the student name and admission number from the current post
$student_name = $current_post->post_title;
$student_admission_number = get_field('student_admission_number', $current_post->ID);
// Get the form ID from the shortcode attributes
$form_id = $atts['id'];
// Prepare the form arguments
$form_args = array(
'field_values' => array(
'student_name' => $student_name,
'student_admission_number' => $student_admission_number,
),
);
// Render the form
return gravity_form( $form_id, false, false, false, $form_args, true );
}
add_shortcode( 'gravityform', 'custom_gravity_form_shortcode' );
Try the following (The shortcode you would use on the page is [stud_gravityform]:
function custom_gravity_form_shortcode($atts = array()){
$details = shortcode_atts( array(
'form_id'=>'176'//change 176 to your form id
), $atts );
$current_post = get_post();
// Get the student name and admission number from the current post
$student_name = $current_post->post_title;
$student_admission_number = get_field('student_admission_number', $current_post->ID);
// Get the form ID from the shortcode attributes
$form_id = $details['form_id'];
// Prepare the form arguments
$form_args = array(
'field_values' => array(
'student_name' => $student_name,
'student_admission_number' => $student_admission_number
)
);
// Render the form
return gravity_form( $form_id, false, false, false, $form_args, true );
}
add_shortcode( 'stud_gravityform', 'custom_gravity_form_shortcode' );//the gravityform shortcode is already taken so I changed it to "stud_gravityform"
It might be easier to rely on the {custom_field} merge tag set in the default value setting of each field that should be dynamically populated. With this, it would fetch whatever custom field you specify from the post on which the form is embedded.
Less code. And easier to configure.

Trying to get shipping fields with a new custome field created

I am trying to get the array for all the shipping forms with a new custom element that I already added. This code is not working:
$newObj = new WC_Checkout();
$shipping_fields = $newObj->get_checkout_fields($fieldset = 'shipping');
Woocommerce WC_Checkout methods:
Visit https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#197-281 for more info!
https://superuser.com?
I get NULL so the object is not existing
In detail:
I'm developing a website, where the total price is calculated according to a delivery area in some city. I decided to create a custom field within the shipping-form:
// Adding districts for the city of Lima on shipping form
add_filter('woocommerce_checkout_fields', 'custom_district_checkout_field');
function custom_district_checkout_field($fields) {
//the list for this example was shortened
$option_cities = array(
'' =>__('Select your district'),
'chorrillos' =>'Chorrillos',
'miraflores' =>'Miraflores'
};
$fields['shipping']['shipping_district']['type'] = 'select';
$fields['shipping']['shipping_district']['options'] = $option_cities;
$fields['shipping']['shipping_district']['class'] = array('update_totals_on_change');
$fields['shipping']['shipping_district']['input_class'] = array('wc-enhanced-select');
$fields['billing']['billing_district']['type'] = 'select';
$fields['billing']['billing_district']['options'] = $option_cities;
$fields['billing']['billing_district']['input_class'] = array('wc-enhanced-select');
wc_enqueue_js("jQuery( ':input.wc-enhanced-select' ).filter( ':not(.enhanced)' ).each( function() {var select2_args = { minimumResultsForSearch:5};jQuery( this ).select2( select2_args ).addClass( 'enhanced' );})");
return $fields;
I can confirm that the custome field is working. For other hand I'm trying to change the way the WooCommerce Advance Shipping plugin works as Jeroen Sormani (who is the developer) explain in his blogs:
How the plugin works!
and WAS Shipping fields conditions
The idea is to add to the condition list the shipping fields, the plugin shows by default this fields: WC Advanced Shipping Fields by Default
The goal is to been able to select the newly created field in the conditions (for example: "districts") so the price would appear in the cart when the user select the correct option, the plugin already has a list of the different districts with their respective prices. However, there is an error in the plugin because this line is not working (check the Github for the WAS Shipping fields conditions inside the first function:
$shipping_fields = WC()->checkout()->checkout_fields['shipping'];
I have been trying to solve this for weeks, hence the original ask in this post.
/**
* WAS all checkout fields
*/
add_filter('was_conditions', 'was_conditions_add_shipping_fields', 10, 1);
function was_conditions_add_shipping_fields($conditions) {
$newObj = new WC_Checkout();
$shipping_fields = $newObj->get_checkout_fields($fieldset = 'shipping');
debugToConsole($shipping_fields);
foreach ($shipping_fields as $key => $values) :
if (isset($values['label'])) :
$conditions['Shipping Fields'][$key] = $values['label'];
endif;
endforeach;
return $conditions;
}
The above results in a NULL with the debugToConsole function.

Modifying a field collection programmatically missing hostEntity fields

I am trying to modify a field collection in a node that already exists so I can change an image on the first element in an array of 3. The problem is, the hostEntity info is not set when I do a entity_load or entity_load_single so when I do a:
$field_collection_item->save(true); // with or without the true
// OR
$fc_wrapper->save(true); // with or without the true
I get the following error:
Exception: Unable to save a field collection item without a valid reference to a host entity. in FieldCollectionItemEntity->save()
When i print_r the field collection entity the hostEntity:protected fields are indeed empty. My field collection is setup as follows:
field_home_experts
Expert Image <--- Want to change this data only and keep the rest below
field_expert_image
Image
Expert Name
field_expert_name
Text
Expert Title
field_expert_title
Text
Here is the code I am trying to use to modify the existing nodes field collection:
$node = getNode(1352); // Get the node I want to modify
// There can be up to 3 experts, and I want to modify the image of the first expert
$updateItem = $node->field_home_experts[LANGUAGE_NONE][0];
if ($updateItem) { // Updating
// Grab the field collection that currently exists in the 0 spot
$fc_item = reset(entity_load('field_collection_item', array($updateItem)));
// Wrap the field collection entity in the field API wrapper
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
// Set the new image in place of the current
$fc_wrapper->field_expert_image->set((array)file_load(4316));
// Save the field collection
$fc_wrapper->save(true);
// Save the node with the new field collection (not sure this is needed)
node_save($node);
}
Any help would be greatly appreciated, I am still quite new to Drupal as a whole (end-user or developer)
Alright so I think I have figured this out, I wrote up a function that will set a field collection values:
// $node: (obj) node object returned from node_load()
// $collection: (string) can be found in drupal admin interface:
// structure > field collections > field name
// $fields: (array) see usage below
// $index: (int) the index to the element you wish to edit
function updateFieldCollection($node, $collection, $fields = Array(), $index = 0) {
if ($node && $collection && !empty($fields)) {
// Get the field collection ID
$eid = $node->{$collection}[LANGUAGE_NONE][$index]['value'];
// Load the field collection with the ID from above
$entity = entity_load_single('field_collection_item', array($eid));
// Wrap the loaded field collection which makes setting/getting much easier
$node_wrapper = entity_metadata_wrapper('field_collection_item', $entity);
// Loop through our fields and set the values
foreach ($fields as $field => $data) {
$node_wrapper->{$field}->set($data);
}
// Once we have added all the values we wish to change then we need to
// save. This will modify the node and does not require node_save() so
// at this point be sure it is all correct as this will save directly
// to a published node
$node_wrapper->save(true);
}
}
USAGE:
// id of the node you wish to modify
$node = node_load(123);
// Call our function with the node to modify, the field collection machine name
// and an array setup as collection_field_name => value_you_want_to_set
// collection_field_name can be found in the admin interface:
// structure > field collections > manage fields
updateFieldCollection(
$node,
'field_home_experts',
array (
'field_expert_image' => (array)file_load(582), // Loads up an existing image
'field_expert_name' => 'Some Guy',
'field_expert_title' => 'Some Title',
)
);
Hope this helps someone else as I spent a whole day trying to get this to work (hopefully I won't be a noob forever in Drupal7). There may be an issue getting formatted text to set() properly but I am not sure what that is at this time, so just keep that in mind (if you have a field that has a format of filtered_html for example, not sure that will set correctly without doing something else).
Good luck!
Jake
I was still getting the error, mentioned in the question, after using the above function.
This is what worked for me:
function updateFieldCollection($node, $collection, $fields = Array(), $index = 0) {
$eid = $node->{$collection}[LANGUAGE_NONE][$index]['value'];
$fc_item = entity_load('field_collection_item', array($eid));
foreach ($fields as $field => $data) {
$fc_item[$eid]->{$field}[LANGUAGE_NONE][0]['value'] = $data;
}
$fc_item[$eid]->save(TRUE);
}
I hope this helps someone as it took me quite some time to get this working.

Drupal: Modifying a User at Registration

I needed to create a custom select list for the user registration page that pulls a SQL query from nodes I need to link to users. I have successfully accomplished this task.. :)
However, when I submit the value, I can't seem to control where the value is stored. In fact, I can't store the value at all. I have created a custom field for my value, but only the new field name is stored, and it is serialized and stored in the Data column of the user table.
Below is my code, I've commented my issues in it. Any help would be appreciated!
<?php
// $Id$
//create the additional user form field, a select list named "account_name"
//then calls the next function to populate it.
function accountselect_user($op, &$edit, &$account, $category = NULL) {
if ($op == 'register' || 'edit')
$fields['Information']['account_name'] = array(
'#type' => 'select',
'#title' => 'Account',
'#description' => t('Select the account to which the contact belongs'),
'#options' => accountselect_getclubs() ,
);
return $fields;
}
//contains query to pull results to select list...this part is working
function accountselect_getclubs() {
$return = array();
$sql = 'SELECT DISTINCT `title` FROM node WHERE type = \'accounts\' ';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$return[] = $row['title'];
}
return $return;
}
//CAN'T GET THIS PART TO WORK - query to update the row - the uid = 29 is for
//testing puposes. Once I get the test value to work
//the test value I will worry about updating the correct user.
function accountselect_submitaccount() {
$sql = "UPDATE users SET account = \'value\' WHERE uid = \'29\'";
db_query($sql);
drupal_set_message(t('The field has been updated.'));
}
//I SUSPECT THE PROBLEM IS HERE...call the submitaccount function.
//I have tried hook_form_alter as well...
function accountselect_submit(&$form, &$form_state) {
if($form_id == 'user-register')
drupal_execute('accountselect_submitaccount');
}
Have you checked Drupal's logs? It should be throwing errors, as this is not a valid query.
$sql = "UPDATE users SET account = \'value\' WHERE uid = \'29\'";
Should be:
$sql = "UPDATE users SET account = 'value' WHERE uid = '29'";
Additionally, in:
function accountselect_submit(&$form, &$form_state) {
if($form_id == 'user-register')
drupal_execute('accountselect_submitaccount');
}
$form_id is never defined.
You say you've created the field in the database, but it must match the name of the Drupal field to be automatically handled. You've got two different names for it - account_name in the Drupal field, but account in the database. Make them consistent and it should be automatically handled, no submit functions required.

Resources