【问题标题】:Wordpress get_posts() returns all posts from Custom Post Type instead returning only selected category postsWordpress get_posts() 从自定义帖子类型返回所有​​帖子,而不是只返回选定类别的帖子
【发布时间】:2016-02-18 08:55:13
【问题描述】:

我使用小部件插件通过 ajax 获取随机帖子和 URL。 感谢fischi 帮助重写函数。 问题是该函数返回 CPT 的所有帖子,所以类别选择不起作用。

php

function get_random_post_tu() {

    // Simple as that, get a random post
    // I put it in an array to make it easier to read
    $args = array(
        'post_type'   => 'portfolio-item','orderby'     => 'rand',
        'numberposts' => 1
    );

    // Add the Category parameter, if set
    if ( isset( $_POST['usecategory'] ) && intval( $_POST['usecategory'] ) != 0 ) {
         $args['tax_query'] = array(
      'taxonomy' => 'portfolio-category',
      'field'    => 'slug',
      'terms'    => $_POST['usecategory']
  );
    }
    $posts = get_posts( $args );

    /**
     * This actually gives us an array of post objects, so we should double check 
     * if there is indeed a post in there.
     */
    $data = array();
    if (is_array($posts) && isset($posts[0])) {

        // add this to use on frontend
        $data['status']  = 'success';
        $data['link']    = get_permalink($posts[0]->ID);
        $data['title']   = get_the_title($posts[0]->ID);
        $data['thumb']   = get_the_post_thumbnail($posts[0]->ID);
        $data['content'] = get_post_field('post_content', $posts[0]->ID);

    } else {

        // add a error status
        $data['status'] = 'error';

    }    

    // use the WordPress built in function
    wp_send_json( $data ); // this is required to return a proper result

}

jQuery

jQuery(document).ready(function($) {
$('.grp_getnew').on('click', function(){
    var data = {
        action: 'get_random_post_tu',
        usecategory: $('#categoryselect').val()
    };

    $.post( ajax_object.ajax_url, data, function(response) {
        if ( response.status != 'error' ) {
            var $link = $("<a href='" + response.link + "'>" + response.title + "</a><span >" + response.content +"</span>");
            $('.grp_content').html($link);
        }
    }, "json");
});

});

输出随机帖子的模板

<?php
$args = array(
    'taxonomy' => 'portfolio-category','id' => 'categoryselect'
);
wp_dropdown_categories( $args );?>


<button class="grp_getnew">Let's go!</button>

为什么 get_posts() 不只返回自定义帖子类型中选定的类别帖子?任何帮助,请!

更新所以我做了print_r($args);我的ajax调用,它显示了

Array ( [post_type] => portfolio-item [orderby] => rand [posts_per_page] => 1 [tax_query] => Array ( [taxonomy] => portfolio-category [field] => term_id [terms] => 40 ) ) {"status":"success","link":"http:\/\/marinaa9.bget.ru\/portfolio-item\/rough-ske‌​tches-2\/","title":"Rough Sketches","thumb":"\"ss\"","content":"[\/vc_column_text][\/vc_column][\/vc_row]"‌​}

所以投资组合是主题内置的 CPT

class PortfolioRegister implements PostTypeInterface {
    /**
     * @var string
     */
    private $base;

    public function __construct() {
        $this->base = 'portfolio-item';
        $this->taxBase = 'portfolio-category';

        add_filter('single_template', array($this, 'registerSingleTemplate'));
    }

    /**
     * @return string
     */
    public function getBase() {
        return $this->base;
    }

    /**
     * Registers custom post type with WordPress
     */
    public function register() {
        $this->registerPostType();
        $this->registerTax();
        $this->registerTagTax();
    }

    /**
     * Registers portfolio single template if one does'nt exists in theme.
     * Hooked to single_template filter
     * @param $single string current template
     * @return string string changed template
     */
    public function registerSingleTemplate($single) {
        global $post;

        if($post->post_type == $this->base) {
            if(!file_exists(get_template_directory().'/single-portfolio-item.php')) {
                return ELATED_CORE_CPT_PATH.'/portfolio/templates/single-'.$this->base.'.php';
            }
        }

        return $single;
    }

    /**
     * Registers custom post type with WordPress
     */
    private function registerPostType() {
        global $chandelier_elated_Framework, $chandelier_elated_options;

        $menuPosition = 5;
        $menuIcon = 'dashicons-admin-post';
        $slug = $this->base;

        if(eltd_cpt_theme_installed()) {
            $menuPosition = $chandelier_elated_Framework->getSkin()->getMenuItemPosition('portfolio');
            $menuIcon = $chandelier_elated_Framework->getSkin()->getMenuIcon('portfolio');

            if(isset($chandelier_elated_options['portfolio_single_slug'])) {
                if($chandelier_elated_options['portfolio_single_slug'] != ""){
                    $slug = $chandelier_elated_options['portfolio_single_slug'];
                }
            }
        }

        register_post_type( $this->base,
            array(
                'labels' => array(
                    'name' => __( 'Portfolio','eltd_cpt' ),
                    'singular_name' => __( 'Portfolio Item','eltd_cpt' ),
                    'add_item' => __('New Portfolio Item','eltd_cpt'),
                    'add_new_item' => __('Add New Portfolio Item','eltd_cpt'),
                    'edit_item' => __('Edit Portfolio Item','eltd_cpt')
                ),
                'public' => true,
                'has_archive' => true,
                'rewrite' => array('slug' => $slug),
                'menu_position' => $menuPosition,
                'show_ui' => true,
                'supports' => array('author', 'title', 'editor', 'thumbnail', 'excerpt', 'page-attributes', 'comments'),
                'menu_icon'  =>  $menuIcon
            )
        );
    }

    /**
     * Registers custom taxonomy with WordPress
     */
    private function registerTax() {
        $labels = array(
            'name' => __( 'Portfolio Categories', 'taxonomy general name' ),
            'singular_name' => __( 'Portfolio Category', 'taxonomy singular name' ),
            'search_items' =>  __( 'Search Portfolio Categories','eltd_cpt' ),
            'all_items' => __( 'All Portfolio Categories','eltd_cpt' ),
            'parent_item' => __( 'Parent Portfolio Category','eltd_cpt' ),
            'parent_item_colon' => __( 'Parent Portfolio Category:','eltd_cpt' ),
            'edit_item' => __( 'Edit Portfolio Category','eltd_cpt' ),
            'update_item' => __( 'Update Portfolio Category','eltd_cpt' ),
            'add_new_item' => __( 'Add New Portfolio Category','eltd_cpt' ),
            'new_item_name' => __( 'New Portfolio Category Name','eltd_cpt' ),
            'menu_name' => __( 'Portfolio Categories','eltd_cpt' ),
        );

        register_taxonomy($this->taxBase, array($this->base), array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => array( 'slug' => 'portfolio-category' ),
        ));
    }

    /**
     * Registers custom tag taxonomy with WordPress
     */
    private function registerTagTax() {
        $labels = array(
            'name' => __( 'Portfolio Tags', 'taxonomy general name' ),
            'singular_name' => __( 'Portfolio Tag', 'taxonomy singular name' ),
            'search_items' =>  __( 'Search Portfolio Tags','eltd_cpt' ),
            'all_items' => __( 'All Portfolio Tags','eltd_cpt' ),
            'parent_item' => __( 'Parent Portfolio Tag','eltd_cpt' ),
            'parent_item_colon' => __( 'Parent Portfolio Tags:','eltd_cpt' ),
            'edit_item' => __( 'Edit Portfolio Tag','eltd_cpt' ),
            'update_item' => __( 'Update Portfolio Tag','eltd_cpt' ),
            'add_new_item' => __( 'Add New Portfolio Tag','eltd_cpt' ),
            'new_item_name' => __( 'New Portfolio Tag Name','eltd_cpt' ),
            'menu_name' => __( 'Portfolio Tags','eltd_cpt' ),
        );

        register_taxonomy('portfolio-tag',array($this->base), array(
            'hierarchical' => false,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => array( 'slug' => 'portfolio-tag' ),
        ));
    }
}

【问题讨论】:

    标签: jquery ajax plugins wordpress


    【解决方案1】:

    slug 更改为 term_id,因为您的帖子请求发送的是类别 ID,而不是其 slug。
    另外,它是posts_per_page 而不是numberposts

    【讨论】:

    • $args['tax_query'] 可能未设置。打印出$args,看看get_posts调用之前的样子
    • @Александр print_r($args); 然后查看开发者控制台、网络选项卡、您的 ajax 调用、响应选项卡
    • Array ( [post_type] =&gt; portfolio-item [orderby] =&gt; rand [posts_per_page] =&gt; 1 [tax_query] =&gt; Array ( [taxonomy] =&gt; portfolio-category [field] =&gt; term_id [terms] =&gt; 40 ) ) {"status":"success","link":"http:\/\/marinaa9.bget.ru\/portfolio-item\/rough-sketches-2\/","title":"Rough Sketches","thumb":"\"ss\"","content":"[\/vc_column_text][\/vc_column][\/vc_row]"}
    【解决方案2】:

    所以我添加了这个

    if ( isset( $_POST['usecategory'] ) && intval( $_POST['usecategory'] ) != 0 ) {
      $args['tax_query'] = array(
        array(
          'taxonomy' => 'portfolio-category',
          'terms'    => intval( $_POST['usecategory'] )
        )
      );
    
    }
    

    它对我有用。另外,我是posts_per_page 谢谢 Flyer 和 Bolverin 的帮助

    【讨论】:

    • 这很奇怪,因为即使你省略了field,默认也是term_id,所以它和我给你的几乎一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    相关资源
    最近更新 更多