You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress:基于多分类法术语展示关联文章的实现问题

Solution for Displaying Same-Region City Posts in taxonomy-city.php

Let's walk through how to adjust your template to show posts from cities in the same region as the current city (like showing all Europe-region cities on the London page). Here's the complete, working code with explanations:

Full Updated Code

<?php
get_header();

$today = date('Ymd');
$current_city = get_queried_object();

// Verify we're on a valid city taxonomy archive
if ($current_city && $current_city->taxonomy === 'city') {
    // Step 1: Get the region associated with the current city
    // Option 1: Use term meta (most reliable - set this up with a plugin like ACF)
    $current_region_slug = get_term_meta($current_city->term_id, 'city_associated_region', true);

    // Option 2: Fallback - Pull region from a sample post in the current city
    if (empty($current_region_slug)) {
        $sample_post = get_posts([
            'tax_query' => [
                [
                    'taxonomy' => 'city',
                    'field' => 'slug',
                    'terms' => $current_city->slug,
                ]
            ],
            'posts_per_page' => 1,
            'fields' => 'ids',
            'post_status' => 'publish'
        ]);

        if (!empty($sample_post)) {
            $region_terms = wp_get_post_terms($sample_post[0], 'region', ['fields' => 'slugs']);
            $current_region_slug = !empty($region_terms) ? $region_terms[0] : '';
        }
    }

    // Step 2: Query posts from the same region
    if (!empty($current_region_slug)) {
        $region_posts_args = [
            'posts_per_page' => 9,
            'order' => 'ASC',
            'orderby' => 'meta_value_num',
            'post_status' => 'publish',
            'tax_query' => [
                // Target posts in the current city's region
                [
                    'taxonomy' => 'region',
                    'field' => 'slug',
                    'terms' => $current_region_slug,
                    'operator' => 'IN'
                ],
                // Optional: Ensure posts are tagged with a city term (filter out non-city content)
                [
                    'taxonomy' => 'city',
                    'field' => 'slug',
                    'operator' => 'EXISTS'
                ]
            ],
            'meta_query' => [
                // Replace with your existing meta logic (e.g., date filtering)
                [
                    'key' => 'event_date', // Example meta key
                    'value' => $today,
                    'compare' => '>=',
                    'type' => 'NUMERIC'
                ]
            ]
        ];

        $region_posts = new WP_Query($region_posts_args);

        // Display the results
        if ($region_posts->have_posts()) {
            $region_name = get_term_by('slug', $current_region_slug, 'region')->name;
            echo "<h2>Cities in {$region_name}</h2>";
            echo '<div class="city-grid">';
            
            while ($region_posts->have_posts()) {
                $region_posts->the_post();
                // Add your post template markup here
                echo '<div class="city-card">';
                the_title('<h3>', '</h3>');
                the_excerpt();
                echo '</div>';
            }
            
            echo '</div>';
            wp_reset_postdata(); // Reset query to avoid conflicts
        } else {
            echo '<p>No cities found in this region.</p>';
        }
    } else {
        echo '<p>No region associated with this city.</p>';
    }
} else {
    // Fallback for non-city archive pages
    echo '<p>This is not a valid city archive page.</p>';
}

get_footer();
?>

Key Changes & Explanations

  • Removed the OR relation: Your original tax query mixed current city posts with a hardcoded list of regions. We replaced this with a targeted query for only the region linked to the current city.
  • Dynamic region retrieval:
    • Option 1 (Recommended): Use term meta (e.g., with Advanced Custom Fields) to assign a region directly to each city term. This is the most reliable method for one-to-one city-region mappings.
    • Option 2 (Fallback): If you don't use term meta, we pull a sample post from the current city and extract its region tag.
  • Optional city filter: Added a EXISTS operator to ensure we only show posts tagged with a city term (matching your "city articles" requirement).
  • Cleaned up query logic: Ensured proper reset of post data after the custom query to avoid breaking default WordPress functionality.

Setup Tips

  1. Term Meta Setup: If using Option 1, install Advanced Custom Fields and create a "Region" select field for the city taxonomy, populated with terms from the region taxonomy.
  2. Style Adjustments: Replace the placeholder city-grid and city-card classes with your theme's existing styling classes.
  3. Meta Query: Update the meta_query section to match your existing date or custom field filtering logic.

内容的提问来源于stack exchange,提问作者Noel Sheppard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:16:12