Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alfredo-wpmudev/13b4e9c0f5fc875eb37f1a63423496b3 to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/13b4e9c0f5fc875eb37f1a63423496b3 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: [Forminator] Using ACF Fields as Categories and Tags
* Plugin URI: https://wpmudev.com/
* Description: Allow Forminator create a post and use the values on ACF fields for Categories and Tags.Categories and Tags will be created if does'nt exist.
* Author: Alfredo Galano Loyola @ WPMUDEV
* Author URI: https://wpmudev.com/
* License: GPLv2 or later
*
* @package Forminator_ACF_Fields_Categories_and_Tags
*/
defined( 'ABSPATH' ) || exit;
function wpmudev_forminator_intercept_data_post_info( $post, $field, $data ){
/*Custom Categories need to be and array if integers(categories ID) like array(12, 5, 7)*/
$custom_categories = array();
/*Custom tags need to be string, like "Tag1,Tag2,Tag3" */
$custom_tags = "";
/* Getting the ACF field DATA from the Forminator Pro Custom post, it is a list of fields with name and value*/
$acf_data = $data['post-custom'];
/*Checking the ACF list of fields to find the one needed for Categories and Tags */
foreach ($acf_data as $key => $acf_field) {
/* Checking the ACF fields, I used custom_categories as the name of my field for Categories */
if ($acf_field['key']=="custom_categories") {
/*Converting the Data in a list of categories like array("Cat1","Cat2","Cat3") */
$categories = explode(",",str_replace(', ', ',', $acf_field['value']));
/*Looping the list of categories selected for that post */
foreach ($categories as $category) {
/*Adding categories to the Database if not exist, $cat_id will handle the ID value of the category */
$cat_id = wp_create_category($category);
if ($cat_id > 0) {
/*Creating the list of ID for my custom categories for the post */
$custom_categories[] = (int) $cat_id;
}
}
}
/*Checking the ACF field related to the tags */
if ($acf_field['key']=="custom_tags") {
/*Cleaning white space near the comma and assigning the custom tags */
$custom_tags = str_replace(', ', ',', $acf_field['value']);
}
}
/* Adding the Categories to the post data */
$post['post_category'] = $custom_categories;
/* Adding the Tags to the post data */
$post['tags_input'] = $custom_tags;
/*The post data is returned to being added to the Database as a new post */
return $post;
}
add_filter('forminator_post_data_post_info','wpmudev_forminator_intercept_data_post_info', 999, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment