Skip to content

Instantly share code, notes, and snippets.

@chrdesigner
Last active December 20, 2024 14:37
Show Gist options
  • Select an option

  • Save chrdesigner/13ebaa46f4936bf4464e59d05f1a3bd0 to your computer and use it in GitHub Desktop.

Select an option

Save chrdesigner/13ebaa46f4936bf4464e59d05f1a3bd0 to your computer and use it in GitHub Desktop.
Filtragem Dinâmica de Posts sem Plugins no WordPress
<?php
/*
* Template para listagem dinâmica de posts
*/
get_header();
?>
<div id="post-filters">
<form id="filter-form">
<select name="category" id="category-filter">
<option value="">Todas as Categorias</option>
<?php
$categories = get_categories();
foreach ($categories as $category) {
echo '<option value="' . $category->term_id . '">' . $category->name . '</option>';
}
?>
</select>
<select name="tag" id="tag-filter">
<option value="">Todas as Tags</option>
<?php
$tags = get_tags();
foreach ($tags as $tag) {
echo '<option value="' . $tag->term_id . '">' . $tag->name . '</option>';
}
?>
</select>
<button type="submit">Filtrar</button>
</form>
</div>
<div id="post-results">
<!-- Posts serão carregados aqui dinamicamente -->
</div>
<?php
get_footer();
<?php
// Adiciona endpoint para a página "listagem"
function adicionar_endpoint_listagem() {
add_rewrite_rule(
'^listagem/?$',
'index.php?is_listagem=1',
'top'
);
add_rewrite_tag('%is_listagem%', '([0-9]+)');
}
add_action('init', 'adicionar_endpoint_listagem');
// Garante que as regras sejam registradas após ativação do tema
function flush_rewrite_rules_on_activation() {
adicionar_endpoint_listagem();
flush_rewrite_rules();
}
add_action('after_switch_theme', 'flush_rewrite_rules_on_activation');
// Carrega o template correto para o endpoint
function carregar_template_listagem($template) {
if (get_query_var('is_listagem')) {
return get_template_directory() . '/page-listagem.php';
}
return $template;
}
add_filter('template_include', 'carregar_template_listagem');
// Define o título personalizado para o endpoint "listagem"
function custom_document_title_listagem($title) {
if (get_query_var('is_listagem')) {
$project_name = get_bloginfo('name');
$title['title'] = "Listagem de Posts - " . $project_name;
}
return $title;
}
add_filter('document_title_parts', 'custom_document_title_listagem');
<?php
add_action('wp_ajax_filter_posts', 'filter_posts');
add_action('wp_ajax_nopriv_filter_posts', 'filter_posts');
function filter_posts() {
$args = [
'post_type' => 'post',
'posts_per_page' => -1,
];
// Filtro por categoria
if (!empty($_POST['category'])) {
$args['cat'] = sanitize_text_field($_POST['category']);
}
// Filtro por tag
if (!empty($_POST['tag'])) {
$args['tag_id'] = sanitize_text_field($_POST['tag']);
}
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<div class="post-item">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
</div>
<?php
}
} else {
echo '<p>Nenhum post encontrado.</p>';
}
wp_die();
}
document.getElementById('filter-form').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch(ajaxurl, {
method: "POST",
body: new URLSearchParams({
action: 'filter_posts',
category: formData.get('category'),
tag: formData.get('tag')
})
})
.then(response => response.text())
.then(data => {
document.getElementById('post-results').innerHTML = data;
});
});
#post-filters {
margin-bottom: 20px;
}
#post-filters select, #post-filters button {
margin-right: 10px;
padding: 10px;
font-size: 16px;
}
#post-results .post-item {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
#post-results .post-item h2 {
margin: 0 0 10px;
}
<?php
function registrar_scripts_filtragem() {
wp_enqueue_script('filtragem-ajax', get_template_directory_uri() . '/js/filtragem.js', ['jquery'], filemtime(get_template_directory() . '/js/filtragem.js'), true);
wp_localize_script('filtragem-ajax', 'ajaxurl', admin_url('admin-ajax.php'));
wp_enqueue_style('filtragem-css', get_template_directory_uri() . '/css/filtragem.css', [], filemtime(get_template_directory() . '/css/filtragem.css'));
}
add_action('wp_enqueue_scripts', 'registrar_scripts_filtragem');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment