Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dantetesta/32660cb096c8640f1e7d18b7ac99f432 to your computer and use it in GitHub Desktop.
Save dantetesta/32660cb096c8640f1e7d18b7ac99f432 to your computer and use it in GitHub Desktop.
Salva Taxonomias via FrontEnd JetFormBuilder Call a Hook
<?php
add_action('jet-form-builder/custom-action/nome-do-seu-hook', 'add_terms_etc');
function add_terms_etc($request) {
try {
// Definir as taxonomias e seus respectivos campos no request
$taxonomies = [
'palavras-chave' => 'palavras-chave',
'tags' => 'tags',
// Adicione mais taxonomias conforme necessário
];
// Certificar-se de que o request é um array válido
if (!is_array($request)) {
$json_request = json_decode($request, true);
if (json_last_error() === JSON_ERROR_NONE) {
$request = $json_request;
} else {
throw new InvalidArgumentException('Requisição inválida no hook add_terms_etc');
}
}
// Obter e validar o ID do post
$post_id = $request['inserted_post_id'] ?? 0;
$post_id = absint($post_id);
if ($post_id <= 0) {
throw new InvalidArgumentException('ID de post inválido no hook add_terms_etc');
}
foreach ($taxonomies as $taxonomy => $field) {
// Obter e validar os termos do campo
$terms = $request[$field] ?? '';
if (!is_string($terms) || empty(trim($terms))) {
continue; // Pular se não houver termos válidos
}
// Converter string de termos em array único e sanitizado
$terms_array = array_unique(array_filter(array_map('sanitize_text_field', array_map('trim', explode(',', $terms)))));
if (empty($terms_array)) {
continue; // Pular se nenhum termo válido foi encontrado
}
// Processar cada termo e obter IDs
$term_ids = array_map(function ($term_name) use ($taxonomy) {
$existing_term = get_term_by('name', $term_name, $taxonomy);
if ($existing_term && !is_wp_error($existing_term)) {
return (int) $existing_term->term_id;
}
$new_term = wp_insert_term($term_name, $taxonomy);
return (!is_wp_error($new_term) && isset($new_term['term_id'])) ? (int) $new_term['term_id'] : null;
}, $terms_array);
$term_ids = array_filter($term_ids);
// Associar os termos ao post
if (!empty($term_ids)) {
$result = wp_set_object_terms($post_id, $term_ids, $taxonomy);
if (is_wp_error($result)) {
throw new RuntimeException("Erro ao associar termos à taxonomia {$taxonomy}");
}
}
}
return true;
} catch (Exception $e) {
error_log('Erro no hook add_terms_etc: ' . $e->getMessage());
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment