0

I hope you can show me the way please. I will explain through an example which is easier. I have a custom post type "juicing_fruits", this post type has a few custom fields that are saved in an array:

custom 1 has a label "fruits" and contains the options: apple, pear, orange, cherry

custom 2 has a label "type" and contains the options: smoothie, juice, iced

custom 3 has a label "link" that is just a text for a URL.

The Categories available for the custom_type post are the merge of fruits and type, so: apple, pear, orange, cherry, smoothie, juice, iced.

The plugin that I am using for the custom type has a function that can return the custom fields values through an array in the following format

Array ( [fruits] => apple, orange[type] => juice, iced [link] => http://blablabla )

My aim is to automatically set the categories of a post, when this is saved/published, depending the fruits and type selected. So if for example the custom fields are like above (fruits: apple and orange, type: juice and iced) then the categories will be the same (apple, orange, juice, iced).

Hope this all make sense. Thank you in advance.

0

Ok after some research and tests this is the solution I coded

function auto_set_event_categories ( int $post_ID ){
//Post Type of Tribe Events
$post_type = "tribe_events";

//If it is not an Event, exit
if( get_post_type($post_ID) != $post_type){
    return;
}

//Get the values of the custom fields
$customfields = tribe_get_custom_fields ( $post_ID );

//Extract the relevant custom fields
$dance_style = explode( ",", $customfields["Dance Style"] );
$event_type = explode( ",", $customfields["Event Type"] );

//Merge the arrays to have a unique, create the array for the ids
$post_categories = array_merge($dance_style, $event_type);
$post_categories_id = array();

//Scan the taxonomies and find the IDs for the custom categories
foreach( $post_categories as $catdesc){
    $term = get_term_by( "name", $catdesc, "tribe_events_cat" );
    $id = (int)$term->term_id;
    if( $id != 0 ){
        array_push( $post_categories_id, $id );
    }
}

//If no categories selected, exit
if( empty($post_categories_id) ){
    return;
}

//Set the Category

wp_set_post_terms( $post_ID, $post_categories_id, "tribe_events_cat" );

return $post_ID;

}

//Add hook to execute auto_set_event_categories when a post is created/saved
add_action( "save_post", "auto_set_event_categories", 100);

Any suggestion to improve the code will be appreciated Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.