我有一个定制的播客帖子类型,但我无法让类别过滤器工作.我创建了名为Podcast Categories的定制分类.当我点击其中一个类别时,它们仍然显示.每个添加的播客都有不同的类别.我想不出该怎么做,所以如果有任何帮助,我将不胜感激!

这是我的unctions.php文件-

//Podcasts
function podcast_custom_post_type () {
    $labels = array (
        'name' => 'Podcasts',
        'singular_name' => 'Podcast',
        'add_new' => 'Add New Podcast',
        'all_items' => 'All Podcasts',
        'add_new_item' => 'Add A Podcast',
        'edit_item' => 'Edit Podcast',
        'new_item' => 'New Podcast',
        'view_item' => 'View Podcast',
        'parent_item_colon' => 'Parent Item',
        'rewrite' => array( 'slug' => 'podcast' )
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'show_in_rest' => true,
        'has_archive' => true,
        'publicly_queryable' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_icon' => 'dashicons-admin-users',
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'thumbnail',
            'custom-fields',
            'revisions',
            'page-attributes'
        ),
    //'taxonomies' => array('category', 'post_tag'),
    'menu_position' => 10,
    'exclude_from_search' => false
    );
register_post_type('podcast', $args);
}
add_action('init', 'podcast_custom_post_type');

function podcast_custom_taxonomies() {

    $labels = array(
        'name' => 'Podcast Categories',
        'singular_name' => 'Podcast Category',
        'search_items' => 'Search Podcast Categories',
        'all_items' => 'All Podcast Category',
        'parent_item' => 'Parent Podcast Category',
        'parent_item_colon' => 'Parent Podcast Category:',
        'edit_item' => 'Edit Podcast Category',
        'update_item' => 'Update Podcast Category',
        'add_new_item' => 'Add New Podcast Category',
        'new_item_name' => 'New Podcast Category',
        'menu_name' => 'Podcast Categories'
    );

    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'podcast_category' )
    );

    register_taxonomy('podcast_category', array('podcast'), $args);
}
add_action( 'init' , 'podcast_custom_taxonomies' );



add_action('pre_get_posts', 'altering_podcast_archive_query', 99);
function altering_podcast_archive_query($query)
{
    if (
        is_post_type_archive('podcast') 
        && 
        get_query_var('orderby')
       ) 
    {
        $tax_query = array(
            array(
                'taxonomy' => 'podcast_category',
                'field' => 'slug',
                'terms' => sanitize_text_field(get_query_var('orderby')),
            )
        );
        $query->set('tax_query', $tax_query);
    };
};

这是我创建的主题页面-

<?php
    /*Template Name: News & Media */
    get_header();
?>

<div class="singlewidth">
<div id="primary">

<form method='GET'>
  <select name='orderby' id='orderby'>
    <?php
    $terms = get_terms([
      'taxonomy' => 'podcast_category',
      'hide_empty' => 'false'
    ]);
    foreach ($terms as $term) :
    ?>

      <option value='<?php echo $term->slug; ?>' <?php echo selected(sanitize_text_field($_GET['orderby']), $term->slug); ?>><?php echo $term->name; ?></option>

    <?php endforeach; ?>
  </select>
  <button type='submit'>Filter</button>
</form>

<div class="podcasts">



<ul>


 <?php
    query_posts(array(
       'post_type' => 'podcast'
    )); ?>
    <?php
    while (have_posts()) : the_post(); ?>
   



<li>
 <?php if ( has_post_thumbnail() ) { /* loades the post's featured thumbnail, requires Wordpress 3.0+ */ echo '<div class="featured-thumb clearfix">'; the_post_thumbnail(); echo '</div>'; } ?>


<div class="podcasttext">
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'azurebasic' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>


<?php if( get_field('podcast_text') ): ?>
    <?php the_field('podcast_text'); ?>
<?php endif; ?>
</div>

<div class="podcastplayer">
<?php if( get_field('add_podcast') ): ?>
    <?php the_field('add_podcast'); ?>
<?php endif; ?>
</div>

</li>

<?php 
endwhile; 
?>

</ul>

</div>
</div>
</div>

<?php  get_footer();  ?>

这是它所在的网页- https://baptist.tfm-dev.com/resources/news-resources

推荐答案

以下是一些建议:

  • 将分类podcast_category连接到自定义帖子类型podcast
  • 将 Select 表单域名称更改为orderby(如果可能)
  • 将(新命名的)orderby参数添加到WP_QUERY以用作过滤器
  • 避免query_posts()

下面是解释和更新的代码示例.

将分类podcast_category连接到自定义帖子类型podcast

WP Docs for register_post_type%的人说:

任何分类连接都应通过$TASTERIONIES参数注册

当调用register_taxonomy()时,将$object_type参数设置为null wordpress.stackexchange.com虽然有其他方法可以完成同样的事情,但这种方法很容易理解.

Code in the podcast_custom_taxonomies() function would need to change from this:


    register_taxonomy('podcast_category', array('podcast'), $args);
}

...到这个...


    register_taxonomy('podcast_category', null, $args);
}

Code in the podcast_custom_post_type() function would need to change from this:

            'revisions',
            'page-attributes'
        ),
    //'taxonomies' => array('category', 'post_tag'),
    'menu_position' => 10,
    'exclude_from_search' => false
    );

...到这个...

            'revisions',
            'page-attributes'
        ),
    'taxonomies' => array('podcast_category', 'category', 'post_tag'),
    'menu_position' => 10,
    'exclude_from_search' => false
    );

将 Select 表单域名称更改为orderby(如果可能)

get_query_var()中使用orderby作为参数可能会导致问题.orderby是用于对帖子列表进行排序的现有WP_Query public query variable.您的代码似乎没有将orderby用作排序键,而是用作过滤器.当你的代码调用get_query_var('orderby')时,它检索的是orderby的现有值WP_Query parameter,而不是HTML表单提交的orderby的值.

HTML表单 Select 选项podcast categories用作filter.为了减少混淆,我建议将HTML表单的select标记名称和ID更改为podcast_category_filter.


将(新命名的)orderby参数添加到WP_QUERY以用作过滤器

假设orderby已更改为podcast_category_filter,只有在字段podcast_category_filter已添加到WP_Query公共查询变量列表中后,才可以调用get_query_var()函数以获取HTML表单提交的值.一旦添加到列表中,WordPress将知道当它在URL中看到podcast_category_filter(例如https://example.com/podcast?podcast_category_filter=sports)时,podcast_category_filter及其值应该添加到WP_Query.然后可以使用get_query_var('podcast_category_filter')检索podcast_category_filter的值.

要将podcast_category_filter添加到WP_QUERY公共查询变量列表中,请在您的主题或插件中使用query_vars过滤器挂钩:

function myplugin_query_vars( $qvars ) {
    $qvars[] = 'podcast_category_filter';
    return $qvars;
}
add_filter( 'query_vars', 'myplugin_query_vars' );

避免query_posts()

请注意WordPress Docs号中有关使用query_posts()函数的警告:

注意:此函数将完全覆盖主查询,不适用于插件或主题.它修改主查询的过于简单的方法可能会有问题,应该尽可能避免.[.]这不能在WordPress循环中使用.

WordPress建议在WP_Query内使用pre_get_posts个动作.

为避免query_posts()次代码更改,代码可能如下所示:

从你的主题页面中删除这个:

query_posts(array(
   'post_type' => 'podcast'
)); ?>

Remove the pre_get_posts action hook:

为了生成由podcast_category过滤的帖子列表,不需要pre_get_posts.pre_get_posts修改主循环(主)查询.过滤后的帖子列表不是从主循环生成的,而是从辅助循环生成的.第二个循环来自下面更新后的代码示例中的$podcast_query.

Updated code

添加到函数.php

<?php
/**
 * functions.php (partial)
 *
 * To be included in the (child) theme's functions.php file.
 */

//Podcasts
function podcast_custom_taxonomies() {
    $labels = array(
        'name' => 'Podcast Categories',
        'singular_name' => 'Podcast Category',
        'search_items' => 'Search Podcast Categories',
        'all_items' => 'All Podcast Category',
        'parent_item' => 'Parent Podcast Category',
        'parent_item_colon' => 'Parent Podcast Category:',
        'edit_item' => 'Edit Podcast Category',
        'update_item' => 'Update Podcast Category',
        'add_new_item' => 'Add New Podcast Category',
        'new_item_name' => 'New Podcast Category',
        'menu_name' => 'Podcast Categories'
    );

    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'show_in_rest' => true, // Make available in Edit Post block options (for testing).
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'podcast_category' )
    );

    \register_taxonomy('podcast_category', null, $args);
}

// Priority must be a lower number than register_post_type.
// register_taxonomy must be called before register_post_type.
add_action( 'init', 'podcast_custom_taxonomies', 10 );


function podcast_custom_post_type () {
    $labels = array (
        'name' => 'Podcasts',
        'singular_name' => 'Podcast',
        'add_new' => 'Add New Podcast',
        'all_items' => 'All Podcasts',
        'add_new_item' => 'Add A Podcast',
        'edit_item' => 'Edit Podcast',
        'new_item' => 'New Podcast',
        'view_item' => 'View Podcast',
        'parent_item_colon' => 'Parent Item',
        'rewrite' => array( 'slug' => 'podcast' )
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'show_in_rest' => true,
        'has_archive' => true,
        'publicly_queryable' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_icon' => 'dashicons-admin-users',
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'thumbnail',
            'custom-fields',
            'revisions',
            'page-attributes'
        ),
        'taxonomies' => array('podcast_category', 'category', 'post_tag'),
        'menu_position' => 10,
        'exclude_from_search' => false
    );

    \register_post_type('podcast', $args);
}

// Priority must be a higher number than register_taxonomy.
// register_post_type must be called after register_taxonomy.
add_action( 'init', 'podcast_custom_post_type', 20 );


function myplugin_query_vars( $qvars ) {
    $qvars[] = 'podcast_category_filter';
    return $qvars;
}

add_filter( 'query_vars', 'myplugin_query_vars' );

<child_theme_root_folder>/page-template/template-podcast-newsandmedia.php

<?php
/*
    Template Name: News & Media
    Template Post Type: podcast, post, page
*/

/**
 * File: <child_theme_root_folder>/page-template/template-podcast-newsandmedia.php
 *
 * The file name follows this convention: page-template/template-<custom_post_type>-<filename>.php
 */

\get_header();
?>

<div class="singlewidth">
<div id="primary">

<?php
$filter = \get_query_var( 'podcast_category_filter' );

// If you don't need special class names or custom attributes in the
// select or option tags consider using wp_dropdown_categories()
// @see {@link https://developer.wordpress.org/reference/functions/wp_dropdown_categories/}
$args = array(
    'taxonomy'          => 'podcast_category',
    'selected'          => \sanitize_text_field( $filter ),
    'name'              => 'podcast_category_filter',
    'hide_empty'        => false,  // Set to true to avoid an empty result from the filter.
    'orderby'           => 'name', // Default. Sort list alphabetically.
    'value_field'       => 'slug',
    'echo'              => false,  // Set to true to echo the HTML directly rather than save the HTML to a variable.
    'show_option_all'   => 'All podcasts',
    'option_none_value' => 0       // Value to use when no category is selected. Same value as 'All podcasts'.
);
$select_category_html = \wp_dropdown_categories( $args );
?>

<form method='GET'>
    <?php echo $select_category_html ?>
    <button type='submit'>Filter</button>
</form>

<div class="podcasts">

<ul>
    <?php $tax_query = array();

    // Be careful here. When the HTML form select option "All podcasts" is selected
    // the number zero (0) is assigned to the form field "podcast_category_filter". When
    // this happens, get_query_var( 'podcast_category_filter' ) returns zero which is implicitly
    // cast as the Boolean value "false". Although unnecessary, it is a good idea to explicitly
    // test for the conditions that causes the if-statement to fail.
    // You may want to add error checking here to test that 'podcast_category_filter' is an
    // exact match with a valid podcast category name.
    if ( ( 0 != $filter ) && is_string( $filter ) && ( '' != $filter ) ) {
        $tax_query = array(
            array(
                'taxonomy' => 'podcast_category',
                'field'    => 'slug',
                'terms'    => \sanitize_text_field( $filter ),
            )
        );
    }

    // Create a secondary query to avoid using the main query.
    // You may need to update the $args argument to handle pagination
    // if you want to avoid a very long list in the results.
    // @see {@link https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters}
    $args = array_merge(
        array( 'post_type' => 'podcast' ),
        array( 'tax_query' => $tax_query )
    );
    $podcast_query = new \WP_Query( $args );

    if ( $podcast_query->have_posts() ) :
        while ( $podcast_query->have_posts() ) : $podcast_query->the_post(); ?>
            <li>
                <?php
                // loads the post's featured thumbnail, requires Wordpress 3.0+
                if ( \has_post_thumbnail() ) {
                    echo '<div class="featured-thumb clearfix">';
                    \the_post_thumbnail();
                    echo '</div>';
                }
                ?>

                <div class="podcasttext">
                    <h2 class="entry-title">
                        <a
                            href="<?php \the_permalink(); ?>"
                            title="<?php printf(
                                \esc_attr__( 'Permalink to %s', 'azurebasic' ),
                                \the_title_attribute( 'echo=0' )
                            ); ?>"
                            rel="bookmark"
                        >
                            <?php \the_title(); ?>
                        </a>
                    </h2>

                    <?php
                    if( get_field('podcast_text') ) :
                        the_field('podcast_text');
                    endif;
                    ?>
                </div>

                <div class="podcastplayer">
                    <?php
                    if( get_field('add_podcast') ) :
                        the_field('add_podcast');
                    endif;
                    ?>
                </div>
            </li>
        <?php
        endwhile;

        // Reset global $post variable back to the main query.
        \wp_reset_postdata();
    else :
        // Display something if there are no posts.
    endif;
    ?>
</ul>

</div>
</div>
</div>

<?php \get_footer(); ?>

Php相关问答推荐

文件大小在php下载读取文件中不可见

Laravel 11发送邮箱时奇怪的未定义数组键名称

PHP -使用preg_match在字符串中进行匹配

在不刷新页面的情况下无法使用JQuery更新id

无法添加ProxyClass__setInitialized()上的忽略

累加平面数组中数字子集的所有组合,以生成组合及其乘积的二维数组

在ShipStation for WooCommerce中使用自定义订单项目元数据

有什么方法可以阻止WordPress主题升级通知吗?

在WooCommerce产品变体SKU字段旁边添加自定义输入字段

根据WooCommerce中的客户计费国家/地区更改产品价格

在laravel 9或10 php中向中间件响应添加自定义数据

WooCommerce中基于用户角色的不同产品差价

将数据推入所有子数组条目

服务器升级到新的mysql版本8.0.34后查询错误

Google Drive API:为什么使用服务帐户在下载文件时会将我带到 Google Drive 登录窗口?

添加产品标签以通过 WooCommerce 邮箱通知订购商品

PHP简单地将物品装在盒子里会导致未使用的空间,但还有剩余容量

Laravel Eloquent(where 子句)

正则表达式 (php) 匹配单个 [ 或单个 ] 但忽略 [[ ]] 之间的任何内容?

Docker: unixodbc.h 没有这样的文件或目录.已安装 unixodbc-dev 时出现pecl install sqlsrv错误