Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save dantetesta/7d9b7010a18449ccd58accfe9ea12a89 to your computer and use it in GitHub Desktop.

Select an option

Save dantetesta/7d9b7010a18449ccd58accfe9ea12a89 to your computer and use it in GitHub Desktop.
Mostrar Termos Existentes no Relation-Taxonomias do User
Script JS
---------------
document.addEventListener('DOMContentLoaded', function () {
// Função para filtrar os options do select box
function filtrarOptionsSelectBox(termIds) {
// Obtem o select box pela classe (ajuste conforme necessário)
const selectBox = document.querySelector('.jet-select__control[name="filial"]');
if (!selectBox) return;
// Obtem todos os options do select box
const options = selectBox.options;
// Itera sobre os options e remove os que não estão na lista de IDs
for (let i = options.length - 1; i >= 0; i--) {
const option = options[i];
if (option.value && !termIds.includes(parseInt(option.value))) {
selectBox.remove(i);
}
}
}
// Função para realizar a chamada AJAX e obter os termos relacionados
function carregarTermos() {
fetch('/wp-admin/admin-ajax.php?action=obter_termos_relacionados_usuario_logado_filial')
.then(response => response.json())
.then(terms => {
if (terms) {
const termIds = Object.keys(terms).map(id => parseInt(id));
filtrarOptionsSelectBox(termIds);
}
})
.catch(error => console.error('Erro ao obter os termos relacionados:', error));
}
// Monitorar mudanças no DOM para detectar quando os filtros são carregados pelo JetSmartFilters
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length || mutation.removedNodes.length) {
carregarTermos();
}
});
});
// Configurar o observer para monitorar o contêiner dos filtros
const targetNode = document.querySelector('.jet-smart-filters-container');
if (targetNode) {
observer.observe(targetNode, {
childList: true,
subtree: true
});
} else {
// Carrega os termos se o contêiner não foi encontrado
carregarTermos();
}
});
-------------------
Script PHP
/**
* Obtem os termos relacionados aos posts do CPT 'documentos' para o usuário logado.
*
* @return array Lista de termos relacionados.
*/
function obter_termos_relacionados_usuario_logado_filial() {
global $wpdb;
// Verifica se o usuário está logado
if (!is_user_logged_in()) {
return [];
}
// Obtem o usuário logado
$current_user_id = get_current_user_id();
// Consulta para obter os child_object_id associados ao parent_object_id do usuário logado
$query = $wpdb->prepare("SELECT child_object_id FROM {$wpdb->prefix}jet_rel_10 WHERE parent_object_id = %d", $current_user_id);
$child_object_ids = $wpdb->get_col($query);
// Se não houver child_object_ids, retorna uma lista vazia
if (empty($child_object_ids)) {
return [];
}
// Obtem os termos da taxonomia 'filial' associados aos child_object_ids encontrados
$termos_relacionados = [];
foreach ($child_object_ids as $post_id) {
$terms = wp_get_post_terms($post_id, 'filial');
foreach ($terms as $term) {
if (!array_key_exists($term->term_id, $termos_relacionados)) {
$termos_relacionados[$term->term_id] = $term->name;
}
}
}
return $termos_relacionados;
}
// Adiciona o endpoint AJAX para obter os termos relacionados
add_action('wp_ajax_obter_termos_relacionados_usuario_logado_filial', 'ajax_obter_termos_relacionados_usuario_logado_filial');
add_action('wp_ajax_nopriv_obter_termos_relacionados_usuario_logado_filial', 'ajax_obter_termos_relacionados_usuario_logado_filial');
/**
* Endpoint AJAX para obter os termos relacionados da taxonomia 'filial'.
*/
function ajax_obter_termos_relacionados_usuario_logado_filial() {
// Obtem os termos relacionados
$termos_relacionados = obter_termos_relacionados_usuario_logado_filial();
// Retorna os termos como resposta JSON
wp_send_json($termos_relacionados);
}
/**
* Função para exibir os termos relacionados no shortcode.
*
* @return string Lista de termos relacionados.
*/
function shortcode_mostrar_termos_relacionados_filial() {
$termos_relacionados = obter_termos_relacionados_usuario_logado_filial();
if (empty($termos_relacionados)) {
return 'Nenhum termo encontrado para este usuário.';
}
// Converte os termos em uma lista legível
$output = '<ul>';
foreach ($termos_relacionados as $term_id => $term_name) {
$output .= '<li>' . esc_html($term_name) . ' (ID: ' . esc_html($term_id) . ')</li>';
}
$output .= '</ul>';
return $output;
}
/**
* Registra o shortcode [mostrar_termos_relacionados_filial].
*/
function registrar_shortcode_mostrar_termos_relacionados_filial() {
add_shortcode('mostrar_termos_relacionados_filial', 'shortcode_mostrar_termos_relacionados_filial');
}
add_action('init', 'registrar_shortcode_mostrar_termos_relacionados_filial');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment