如何动态获取某一类别下自定义帖子类型

时间:2020-04-03 作者:sialfa

我有一个自定义的帖子类型,我正在开发一个名为“产品”的主题,我将保存一个产品目录。我想对这些产品进行分类,我添加了分类法category 我将创建所需的类别,以便将每个帖子分配给正确的帖子。我对wordpress的功能了解不多,我想问一下如何获得分配给每个类别的自定义帖子类型。我想做多次WP_Query() 但我认为这对表演来说不是个好主意。还有别的办法吗?我要实现的解决方案是将ajax与vue结合使用。js与REST API一起创建一个类别列表,单击该列表将加载相关帖子和类别名称、描述。有hepl吗?

1 个回复
最合适的回答,由SO网友:simongcc 整理而成

我认为您可以通过使用以下WP内置功能来实现这一点。

  • $wp_taxonomies - 全局对象,它存储所有注册的分类法,包括默认分类法和自定义分类法get_post_types() - 让所有注册的帖子类型(包括默认和自定义)变得简单,下面分别是它们的用法示例。然后,您可以将它们组合起来,创建一个已注册的帖子类型列表,并提供一些条件,例如限制某些帖子类型。然后将其与注册的分类法进行比较。或者,您可以创建一个预设列表,其中包含帖子类型名称和注册的分类法,以进行比较。也许你有更好的方法。

    这是获取特定帖子类型的所有注册分类的示例。

    <?php
    // the taxonomy list is available in plugin, templates
    // example, I put it it a plugin
    global $wp_taxonomies;
    
        // loop through all custom taxonomy and use preg_match() to test which category is matched to the post_type
       // 1. assumed your post_type name is part of the category_name, for other checking logic, it is up to you and flexible
       // 2. the $post_type is passed somewhere, here is a hard-coded example
    
        $post_type = \'scusto\';
        foreach ($wp_taxonomies as $key => $value) {
               if( preg_match( "/{$post_type}*/", $key ) ) {
                        $registered_tax = $wp_taxonomies[$key]->name;
               }
        }
    
        // then you have the registered category stored in $registered_tax for manipulation
    ?>
    
    下面是获取所有注册帖子类型的函数

    <?php
        // all registered post types output in an array
        $post_types = get_post_types();
    ?>
    
    编辑/更新2020年4月4日23:47这里是利用上述信息和一些ajax过滤器的ajax解决方案。你需要准备四件事。以下是以插件的形式编写的,因为它实际上来自我的插件。你可以转向其他形式来满足需要。作为演示,我省略了所有测试和验证,例如nonce。您可能需要在实际情况中添加它们。有关WordPress中AJAX的详细信息,请参阅Plugin Handbook

    虽然我为后端添加了ajax侦听器过滤器,但这只是表明它可以做到这一点。管理页面中没有js排队。如果需要,可以添加admin_enqueue_scripts 滤器

    准备表单以向访问者显示接收ajax调用和操作按钮的javascript以进行交互并发送操作根据对您的问题的理解,这就是示例所做的:

    显示3个列表,帖子类型列表,类别列表,帖子列表当选择帖子类型时,它更新类别列表当选择类别时,它更新帖子列表

    class q363151_category_list {
        public function __construct() {
            //---------------------------------------
            // ajax update list
            // action name = update_cat_list, update_post_list
            //---------------------------------------
            // for frontend
            // ajax update category list
            add_action( \'wp_ajax_nopriv_update_cat_list\', array( $this, \'update_cat_list\' ) ); // non-logged in user
            add_action( \'wp_ajax_update_cat_list\', array( $this, \'update_cat_list\' ) ); // logged in user
    
            // for backend
            add_action( \'admin_post_update_cat_list\', array( $this, \'update_cat_list\' ) );
            add_action( \'admin_post_nopriv_update_cat_list\', array( $this, \'update_cat_list\' ) );
    
            // ajax update post list
            add_action( \'wp_ajax_nopriv_update_post_list\', array( $this, \'update_post_list\' ) ); // non-logged in user
            add_action( \'wp_ajax_update_post_list\', array( $this, \'update_post_list\' ) ); // logged in user
    
            // for backend
            add_action( \'admin_post_update_post_list\', array( $this, \'update_post_list\' ) );
            add_action( \'admin_post_nopriv_update_post_list\', array( $this, \'update_post_list\' ) );
    
            // enqueue scripts
            // add_action( \'admin_enqueue_scripts\', array( $this, \'scripts\' ), 1 );
            add_action( \'wp_enqueue_scripts\', array( $this, \'scripts\' ) );
    
            // output selection form
            add_action( \'somewhere_in_your_theme\', array( $this, \'render_form_list\' ) );
        }
    
        // load scripts if any
        public function scripts() {
            wp_enqueue_script( \'q363147-ajax-post-list\', plugins_url( \'/ajax-post-list.js\', __FILE__  ), array( \'jquery\' ), \'t\' . time(), true );
    
            // add ajax url
            $config = array( 
                \'ajaxurl\' => admin_url(\'admin-ajax.php\'),
            );
            wp_localize_script(\'q363147-ajax-post-list\', \'q363147\', $config);
        }
    
        // receive action from ajax call
        public function update_cat_list() {
            global $wp_taxonomies;
            // Error Handling
            // check the nonce
    
            $post_type = $_POST[\'post_type\'];
    
            // get taxonomy for specific post type
            $registered_tax = null;
            switch ( $post_type ) {
                case \'post\':
                    $tax_keyword = \'category\';
                break;
    
                default:
                    $tax_keyword = \'does_not_exist\';
                    break;
            }
    
            foreach ($wp_taxonomies as $key => $tax) {
                if( preg_match( "/^{$tax_keyword}/", $key ) ) {
                    $registered_tax = $tax; // assumed 1 taxonomy
                }
           }
    
            // output
    
            // category list
            // get terms(category name) for the found taxonomy
    
            $category_options = $this->return_options( \'category\' );
            if( ! empty( $registered_tax ) ) {
                $terms = get_terms([
                    \'taxonomy\' => $registered_tax->name,
                    \'hide_empty\' => false,
                ]);
    
                foreach ($terms as $key => $term) {
                    $category_options .= \'<option value="\' . $term->name . \'">\' . $term->name . \'</option>\';
                }
            }
    
            // action here after checking
            wp_send_json_success( array(
                \'message\' => __( \'List data preparation completed\', \'q363147\' ),
                \'post_type\' => $post_type,
                \'tax_keyword\' => $tax_keyword,
                \'taxonomy\' => ( $registered_tax->name ),
                \'tax_query_var\' => ( $registered_tax->query_var ),
                \'categories\' => $category_options,
    
                // for debug
                \'found_tax\' => preg_match( "/^{$tax_keyword}/", $key ),
                \'post_data\' => $_POST, 
            ) );
        }
    
        public function update_post_list() {
            $post_type = $_POST[\'post_type\'];
            $category = $_POST[\'selected_category\'];
            $tax_query_var = $_POST[\'tax_query_var\'];
            // $taxonomy = $_POST[\'taxonomy\']; // for later extension
    
            // post query
            $args = array( 
                \'post_type\' => $post_type,
                \'category_name\' => $category,
            );
            $query = new WP_Query( $args );
            $posts = $query->posts;
    
            $post_options = $this->return_options( \'post\' );
            foreach ($posts as $key => $post) {
                $post_options .= \'<option value="\' . $post->ID . \'">\' . $post->post_title . \'</option>\';
            }
    
            // action here after checking
            wp_send_json_success( array(
                \'message\' => __( \'Post list preparation completed\', \'q363147\' ),
                \'post_type\' => $post_type,
                \'tax_query_var\' => $tax_query_var,
                \'posts\' => $post_options,
    
                // for debug
                \'query_result\' => $query,
                \'post_data\' => $_POST, 
            ) );
        }
    
        // render form to frontend
        public function render_form_list() {
            // output your form here
    
            $post_types = get_post_types();
    
            // if you want to limit the following post type to be appeared
            $allowed_to_search_arr = array(
                \'post\' => \'Post\',
                \'page\' => \'Page\', // if you turned it on for search, default is off
                \'custom1\' => \'Custom post type1\',
                \'custom2\' => \'Custom post type2\',
            );
    
            // post type list
            $post_type_options = \'<option value="default">-- Post types --</option>\';
            foreach ($post_types as $key => $post_type) {
                if( array_key_exists( $post_type, $allowed_to_search_arr ) )
                $post_type_options .= \'<option value="\' . $key . \'">\' . $post_type . \'</option>\';
            }
    
            // category list
            $category_options = $this->return_options( \'category\' );
    
            // post list
            $post_options = $this->return_options( \'post\' );
    
            $form = <<<HTML
            <form method="post" class="form">
                <ul class="list">
                    <li class="post-types">
                        <select name="post_type" class="post-type-selector">
                            <!-- send action to ajax -->
                            $post_type_options
                        </select>
                    </li>
    
                    <li class="categories">
                        <select name="selected_category" class="category-selector">
                            <!-- respond to ajax result -->
                            $category_options
                        </select>
                    </li>
    
                    <li class="posts">
                        <select name="selected_post" class="post-selector">
                            <!-- respond to ajax result -->
                            $post_options
                        </select>
                    </li>
                </ul>
                <input type="hidden" name="taxonomy">
                <input type="hidden" name="tax_query_var">
            </form>
    HTML;
    
            echo $form;
        }
    
        private function return_options( $name = \'\' ) {
            return \'<option value="default">-- Please select \' . $name . \' --</option>\';
        }
    }
    
    // create new object
    new q363151_category_list();
    
    ajax处理程序

    (function ($) {
      // post type selector
      $(\'.form\').on(\'change\', \'.post-type-selector\', function (e) {
        var $initiator = $(this); // Error Handling
        $initiator.prop(\'disabled\', true); // set ajax data, Object for the AJAX action
    
        var data = {
          \'action\': \'update_cat_list\',
          \'post_type\': $(\'select[name="post_type"]\').val(),
        }; // send ajax
    
        $.ajax({
            type: \'post\',
            url: q363147.ajaxurl,
            dataType: \'json\',
            data: data
        }).done( function( response ) {
            console.log(response);
            $initiator.prop(\'disabled\', false);
    
            // update category list
            $( \'.category-selector\' ).html( response.data.categories );
    
            // update taxonomy
            $( \'[name="taxonomy"]\').val(response.data.taxonomy);
            $( \'[name="tax_query_var"]\').val(response.data.tax_query_var);
    
        }).fail( function( jqXHR ) {
            // failure handling
        });
      });
    
      // category selector
      $(\'.form\').on(\'change\', \'.category-selector\', function (e) {
        var $initiator = $(this); // Error Handling
        $initiator.prop(\'disabled\', true); // set ajax data, Object for the AJAX action
    
        var data = {
          \'action\': \'update_post_list\',
          \'post_type\': $(\'select[name="post_type"]\').val(),
          \'selected_category\': $(\'select[name="selected_category"]\').val(),
          \'tax_query_var\': $(\'[name="tax_query_var"]\').val(),
        }; // send ajax
    
        $.ajax({
            type: \'post\',
            url: q363147.ajaxurl,
            dataType: \'json\',
            data: data
        }).done( function( response ) {
            console.log(response);
            $initiator.prop(\'disabled\', false);
    
            // update post list
            $( \'.post-selector\' ).html( response.data.posts );
        }).fail( function( jqXHR ) {
            // failure handling
        });
      });
    })(jQuery);
    
    向观众展示

    // place anywhere in your template
    do_action( \'somewhere_in_your_theme\' );
    
    下面是本示例的屏幕截图。[Select a post type1[Select a category of the post type]2[Select a post to work with]3

相关推荐

扩展WooCommerce小部件类-WC_Widget_Product_Categories

我正在尝试扩展woocommerce类,该类用于在我自己的插件中创建产品类别小部件,该插件为woo commerce产品添加了一个称为“部门”的新分类法。当我扩展WP\\u小部件时,一切正常,我看到一个新的小部件,可以添加到外观->小部件中。然而,当我试图扩展WC\\u Widget或WC\\u Widget\\u Product\\u类别时,我根本看不到新的Widget,即使我没有收到任何php错误。以下是我所拥有的不起作用的东西://get the base classes if(!cl