wordpress 如何按类别过滤自定义文章类型

yeotifhr  于 2023-11-17  发布在  WordPress
关注(0)|答案(2)|浏览(136)

我有一个自定义的播客文章类型,但我不能得到类别过滤器的工作.我创建了自定义分类称为播客类别.当我点击其中一个类别,他们都仍然显示.每个播客添加有不同的类别.我不知道如何使它工作,所以任何帮助将不胜感激!!
这是我的functions.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

ztmd8pv5

ztmd8pv51#

一些建议:

  • 将分类podcast_category连接到自定义文章类型podcast
  • 更改orderby的选择表单字段名称(如果可能)
  • 将(新命名的)orderby参数添加到WP_Query以用作筛选器
  • 避免query_posts()

下面是说明和更新的代码示例。

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

WP Docs for register_post_type说:
任何分类连接都应该通过$taxonomies参数注册
当调用register_taxonomy()时,将$object_type参数设置为null(请参阅wordpress.stackexchange.com answer here),并在对register_post_type()的调用中使用'taxonomies'属性将podcast_category分类连接到podcast自定义post类型。虽然还有其他方法可以完成相同的事情,但这种方法很容易理解。

podcast_custom_taxonomies()函数中的代码需要从以下内容更改:

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

字符串
...这个...

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

podcast_custom_post_type()函数中的代码需要从以下内容更改:

'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
    );

修改orderby的选择表单字段名(如果可能)

get_query_var()中使用orderby作为参数可能会导致问题。orderby是用于对帖子列表进行排序的现有WP_Query public query variable。您的代码似乎没有将orderby用作排序键,而是用作筛选器。当您的代码调用get_query_var('orderby')时,它正在检索orderby的现有WP_Query参数值,而不是HTML表单提交的orderby的值。
HTML表单的选择选项是 podcast categories,用作 filter。为了减少混淆,我建议将HTML表单的选择标记名称和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'
)); ?>

移除pre_get_posts动作钩子:

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

代码更新

添加到functions.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(); ?>

xpcnnkqh

xpcnnkqh2#

<?php

  // Query Arguments
  $args = array(
    //
    // your custom post type
    //
    'post_type' => 'podcast',
    //
    // your taxonomy info to filter
    //
    'tax_query' => array(
      array(
        //
        // your custom taxonomy
        //
        'taxonomy' => 'podcast_category',
        //
        // eg. we filter by slug
        //
        'field'    => 'slug',
        //
        // replace 'the-slug' with your target slugs to filter
        //
        'terms'    => array('the-slug'),  
      ),
    ),
  );

  query_posts($args);
?>

字符串
如果我明白你的意思的话,就这样吧。
我相信有数百个这样的职位来解决这个问题。

相关问题