admin管理员组文章数量:1122846
The following code displays posts based on subcategory. First dropdown is a custom taxonomy category, second dropdown narrows down the search to subcategories associated with selected category. My only struggle is to display posts from selected category when no subcategory is chosen.
custom-script.js
jQuery(document).ready(function($) {
$('.loading-spinner').hide();
// Handle tab clicks (using event delegation)
$(document).on('click', '.tabs button', function() {
// Hide all content divs
$('.content div').addClass('hidden');
// Show the clicked content div
var postID = $(this).data('post-id');
$('#content-' + postID).removeClass('hidden');
});
$(document).on('click', '.show-map', function() {
// Hide all content divs
$('.content div').addClass('hidden');
var postID = $(this).data('post-id');
$('#content-' + postID).removeClass('hidden');
});
$('.meta-info button.show-map:first').trigger('click');
});
//Reset button
jQuery(document).ready(function($) {
// Function to handle the click event of the "Wyczyść" button
$('.reset-filter').on('click', function() {
// Clear the selected option in the subcategory dropdown
$('#subcategory-dropdown').val('');
// Trigger the change event on the subcategory dropdown to reload the results
$('#subcategory-dropdown').trigger('change');
});
});
(function($) {
$(document).ready(function() {
// Function to handle AJAX requests
function handleAjaxRequest(url, type, data, successCallback, errorCallback) {
$('.loading-spinner').show();
$('<div class="spinner-overlay"></div>').appendTo('body');
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
successCallback(response);
},
error: function(jqXHR, textStatus, errorThrown) {
errorCallback(jqXHR, textStatus, errorThrown);
},
complete: function() {
$('.loading-spinner').hide();
$('.spinner-overlay').remove();
}
});
}
// Function to load posts based on category when no subcategory is selected
function loadPostsByCategory(categoryId) {
console.log('Loading posts for category ID:', categoryId);
// Perform AJAX request to load posts based on the selected category
handleAjaxRequest(
'.php', // Replace 'YOUR_ADMIN_AJAX_URL' with the actual URL
'POST',
{
action: 'load_category_posts',
category_id: categoryId
},
function(response) {
console.log('Response received for category ID:', categoryId);
console.log('Response:', response); // Log the response
$('#subcategory-posts').html(response);
showFirstPostMap();
},
function(jqXHR, textStatus, errorThrown) {
console.error('AJAX Error:', errorThrown);
}
);
}
// Event handler for category dropdown change
$('#category-dropdown').change(function() {
var categoryId = $(this).val();
console.log('Dropdown change Category ID:', categoryId);
if (categoryId !== '') {
$('#subcategory-dropdown').show();
$('#subcategory-row').show();
$('#additional-div').hide();
handleAjaxRequest(
'.php', // Replace 'YOUR_ADMIN_AJAX_URL' with the actual URL
'POST',
{
action: 'get_subcategories',
category_id: categoryId
},
function(response) {
$('#subcategory-dropdown').html(response);
},
function(jqXHR, textStatus, errorThrown) {
console.error('AJAX Error:', errorThrown);
}
);
} else {
loadPostsByCategory(categoryId); // Call the function when no subcategory is selected
}
});
// Event handler for subcategory dropdown change
$('#subcategory-dropdown').change(function() {
var subcategoryId = $(this).val();
var categoryId = $('#category-dropdown').val();
handleAjaxRequest(
'.php', // Replace 'YOUR_ADMIN_AJAX_URL' with the actual URL
'POST',
{
action: 'load_subcategory_posts',
subcategory_id: subcategoryId,
category_id: categoryId
},
function(response) {
$('#subcategory-posts').html(response);
showFirstPostMap();
},
function(jqXHR, textStatus, errorThrown) {
console.error('AJAX Error:', errorThrown);
}
);
});
// Function to show the map of the first post
function showFirstPostMap() {
var firstPostButton = $('.meta-info button.show-map:first');
firstPostButton.trigger('click');
}
});
})(jQuery);
functions.php
// Enqueue JavaScript file
function enqueue_custom_scripts() {
// Enqueue the JavaScript file
wp_enqueue_script('custom-script', get_template_directory_uri() . '/assets/js/custom-script.js', array('jquery'), null, true);
// Localize the script with nonce and AJAX URL
wp_localize_script('custom-script', 'ajax_params', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('lok_nonce'),
));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
function get_subcategories_callback() {
// if (!isset($_POST['lok_nonce']) || !wp_verify_nonce($_POST['lok_nonce'], 'lok_nonce')) {
// die('Permission denied from first callback');
// }
if (isset($_POST['category_id'])) {
$category_id = $_POST['category_id'];
$terms = get_terms(array(
'taxonomy' => 'wojewodztwa',
'hide_empty' => false,
'parent' => $category_id,
));
$options = '<option value="">' . pll__('Wybierz miasto', 'twentytwenty') . '</option>';
foreach ($terms as $term) {
$options .= '<option value="' . esc_attr($term->term_id) . '">' . esc_html($term->name) . '</option>';
}
echo $options;
}
die();
}
add_action('wp_ajax_get_subcategories', 'get_subcategories_callback');
add_action('wp_ajax_nopriv_get_subcategories', 'get_subcategories_callback');
/*--------------------------------------------------------
// Add AJAX handler for fetching subcategory posts
-------------------------------------------------------*/
function load_subcategory_posts_callback() {
$subcategory_id = isset($_POST['subcategory_id']) ? $_POST['subcategory_id'] : '';
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : '';
// Debugging: Output category ID
//echo "Category ID: " . $category_id;
// Initialize the query arguments
$args = array(
'post_type' => 'lokalizacje',
'posts_per_page' => -1,
);
// Check if a subcategory is selected
if (!empty($subcategory_id)) {
// If a subcategory is selected, filter posts by the subcategory
$args['tax_query'] = array(
array(
'taxonomy' => 'wojewodztwa',
'field' => 'id',
'terms' => $subcategory_id,
),
);
} elseif (!empty($category_id)) {
// If "Wybierz miasto" is selected, but a category is specified,
// display posts associated with the selected category
$args['tax_query'] = array(
array(
'taxonomy' => 'wojewodztwa',
'field' => 'id',
'terms' => $category_id,
),
);
}
// elseif (!empty($category_id) && empty($subcategory_id)) {
// $args['tax_query'] = array(
// array(
// 'taxonomy' => 'wojewodztwa',
// 'field' => 'id',
// 'terms' => $subcategory_id,
// ),
// );
// }
else {
$args['tax_query'] = array(
array(
'taxonomy' => 'wojewodztwa',
'field' => 'id',
'terms' => $category_id,
),
);
}
// Execute the query
$query = new WP_Query($args);
// Check if there are posts
if ($query->have_posts()) {
$posts_data = array();
// Loop through the posts and collect data
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$mapa_value = get_post_meta($post_id, 'textarea_mapa', true);
$tel = get_post_meta($post_id, 'tel_num_tel', true);
$adres = get_post_meta($post_id, 'text_adres', true);
// Store post data in an array
$posts_data[$post_id] = array(
'title' => get_the_title(),
'mapa' => $mapa_value,
'tel' => $tel,
'adres' => $adres
);
}
// Reset post data
wp_reset_postdata();
// Output the HTML structure
echo '<div class="tab-section">';
echo '<ul class="tabs">';
foreach ($posts_data as $post_id => $post) {
echo '<li class="tab" data-post-id="' . esc_attr($post_id) . '"><div><p class="store-name">' . esc_html($post['title']) . '</p>';
echo '<p>' . esc_attr($post['adres']) . '</p>';
echo '<div class="meta-info">';
if (!empty($post['tel'])) {
echo'<button class="is-phone-white"><svg aria-hidden="true" role="none" tabindex="-1" width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns=";><path d="M10.9249 7.35619L9.19487 6.35734C8.92996 6.20442 8.62084 6.16388 8.32452 6.24327C8.02819 6.32265 7.78073 6.51229 7.6278 6.77723C7.53907 6.93097 7.38364 7.12436 7.14721 7.1727C6.93156 7.2168 6.74119 7.17402 6.5652 7.04195C5.91502 6.55401 5.08892 5.72791 4.6009 5.07766C4.46884 4.90167 4.42605 4.71126 4.47016 4.49569C4.5185 4.25918 4.71189 4.10379 4.86563 4.01506C5.41343 3.69873 5.60178 2.99576 5.28552 2.44796L4.28667 0.717853C4.00057 0.222402 3.40638 0.0145907 2.87396 0.223653L2.85325 0.231783C2.02649 0.556357 1.42193 0.805443 1.17192 1.05545C0.717781 1.50963 0.257792 2.35474 0.645567 3.80191C1.39871 6.61279 5.03003 10.2441 7.84091 10.9973C8.22258 11.0996 8.56235 11.1429 8.86415 11.1429C9.70669 11.1429 10.2531 10.8053 10.5875 10.4709C10.8374 10.221 11.0864 9.61651 11.411 8.78998L11.4193 8.76893C11.6282 8.23644 11.4204 7.64229 10.9249 7.35619Z" fill="#212425"/></svg>';
}
echo esc_html($post['tel']) . '</button><button data-post-id="' . esc_attr($post_id) . '" class="is-phone-white show-map">' . pll__('pokaż na mapie', 'twentytwenty') . '</button></div></li>';
}
echo '</ul>';
echo '<div class="map-spinner-container"><div class="map-spinner"></div></div>';
echo '<div class="content">';
foreach ($posts_data as $post_id => $post) {
echo '<div id="content-' . esc_attr($post_id) . '" class="hidden"><iframe width="100%" height="600" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' . esc_url($post['mapa']) . '" loading="lazy" referrerpolicy="no-referrer-when-downgrade" style="width:100%"></iframe></div>';
}
echo '</div>';
echo '</div>';
} else {
// No posts found
echo pll__('Brak wpisów dla wybranej kategorii', 'twentytwenty');
}
die();
}
add_action('wp_ajax_load_subcategory_posts', 'load_subcategory_posts_callback');
add_action('wp_ajax_nopriv_load_subcategory_posts', 'load_subcategory_posts_callback');
template.php
get_header();
global $wp_query;
?>
<div class="page-container">
<div id="site-content">
<header><h1 class="secondary-header"><?php the_title();?></h1></header>
<main class="main" role="main">
<div class="page-wrapper">
<?php if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_content();
?>
<p class="blue"><?php if (the_field('tu_kupisz')) {the_field('tu_kupisz');} ?></p>
<div class="form-wrapper">
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="ajax-filter">
<?php
$categories = get_terms(array(
'taxonomy' => 'wojewodztwa',
'hide_empty' => false,
'parent' => 0,
));
if ($categories) : ?>
<div class="select-row">
<p><?php echo pll__('Wybierz województwo', 'twentytwenty');?>:</p>
<select id="category-dropdown" name="categoryfilter">
<option value=""><?php echo pll__('Wybierz region', 'twentytwenty');?></option>
<?php foreach ($categories as $category) : ?>
<?php if (is_object($category) && isset($category->name)) : ?>
<option value="<?php echo $category->term_id; ?>"><?php echo $category->name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
<div class="select-row" id="subcategory-row" style="display: none;">
<p><?php echo pll__('Wybierz miasto', 'twentytwenty');?>:</p>
<select id="subcategory-dropdown" name="subcategory">
</select>
<button type="button" class="reset-filter" data-target=""><?php echo pll__('Wyczyść', 'twentytwenty');?></button>
</div>
<input type="hidden" name="action" value="myfilter_2">
</form>
</div>
<div class="loading-spinner-container">
<div class="loading-spinner"></div>
<div id="subcategory-posts" class="relative">
<?php
$args = array(
'post_type' => 'lokalizacje',
'posts_per_page' => 10,
'order' => 'RAND'
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
$posts_data = array();
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$mapa_value = get_post_meta($post_id, 'textarea_mapa', true);
$tel = get_post_meta($post_id, 'tel_num_tel', true);
$adres = get_post_meta($post_id, 'text_adres', true);
$posts_data[$post_id] = array(
'title' => get_the_title(),
'mapa' => $mapa_value,
'tel' => $tel,
'adres' => $adres
);
}
wp_reset_postdata();
}
if (!empty($posts_data)) {
// Output the HTML structure
echo '<div class="tab-section">';
echo '<ul class="tabs reset-list-style">';
foreach ($posts_data as $post_id => $post) {
echo '<li class="tab reset-list-style" data-post-id="' . esc_attr($post_id) . '"><div><p class="store-name">' . esc_html($post['title']) . '</p>';
echo '<p>' . esc_attr($post['adres']) . '</p>';
echo '<div class="meta-info">';
if (!empty($post['tel'])) {
echo'<button class="is-phone-white call"><svg aria-hidden="true" role="none" tabindex="-1" width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns=";><path d="M10.9249 7.35619L9.19487 6.35734C8.92996 6.20442 8.62084 6.16388 8.32452 6.24327C8.02819 6.32265 7.78073 6.51229 7.6278 6.77723C7.53907 6.93097 7.38364 7.12436 7.14721 7.1727C6.93156 7.2168 6.74119 7.17402 6.5652 7.04195C5.91502 6.55401 5.08892 5.72791 4.6009 5.07766C4.46884 4.90167 4.42605 4.71126 4.47016 4.49569C4.5185 4.25918 4.71189 4.10379 4.86563 4.01506C5.41343 3.69873 5.60178 2.99576 5.28552 2.44796L4.28667 0.717853C4.00057 0.222402 3.40638 0.0145907 2.87396 0.223653L2.85325 0.231783C2.02649 0.556357 1.42193 0.805443 1.17192 1.05545C0.717781 1.50963 0.257792 2.35474 0.645567 3.80191C1.39871 6.61279 5.03003 10.2441 7.84091 10.9973C8.22258 11.0996 8.56235 11.1429 8.86415 11.1429C9.70669 11.1429 10.2531 10.8053 10.5875 10.4709C10.8374 10.221 11.0864 9.61651 11.411 8.78998L11.4193 8.76893C11.6282 8.23644 11.4204 7.64229 10.9249 7.35619Z" fill="#212425"/></svg>';
}
echo esc_html($post['tel']) . '</button><button data-post-id="' . esc_attr($post_id) . '" class="is-phone-white show-map">' . pll__('pokaż na mapie', 'twentytwenty') . '</button></div></li>';
}
echo '</ul>';
echo '<div class="map-spinner-container"><div class="map-spinner"></div></div>';
echo '<div class="content" >';
foreach ($posts_data as $post_id => $post) {
echo '<div id="content-' . esc_attr($post_id) . '" class="hidden"><iframe width="100%" height="600" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' . esc_url($post['mapa']) . '" loading="lazy" referrerpolicy="no-referrer-when-downgrade" style="width:100%"></iframe></div>';
}
echo '</div>';
echo '</div>';
}
// else {
// //echo pll__('Wybierz województwo, potem miasto', 'twentytwenty');
// $args['tax_query'] = array(
// array(
// 'taxonomy' => 'wojewodztwa',
// 'field' => 'id',
// 'terms' => $category_id,
// ),
// );
// };
?>
<?php wp_reset_postdata(); ?>
</div>
<?php
}
}
?>
</div><!-- form-wrapper -->
</div><!-- loading-spinner-container -->
</main>
</div><!-- #site-content -->
</div>
<?php
get_footer();
本文标签: phpDisplay posts based on the selected category when no subcategory is chosen
版权声明:本文标题:php - Display posts based on the selected category when no subcategory is chosen 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736310873a1934533.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论