1

I use widget plugin Getting the random post & URL via ajax. Thanks fischi for help to rewrite functions. Problem is that function returns all posts from CPT, so category select doesn't work.

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['taxonomy=portfolio-category'] = $_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");
});

});

Template for output random posts

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


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

Why get_posts() not returning only selected category posts from Custom Post Type? Any help,please!

UPDATE So i have made print_r($args); of my ajax call and it shows

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]"‌​}

So portfolio is Theme-built-in 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' ),
        ));
    }
}
0

First, your custom post type is portfolio-item, not portfolio_item. Note that you register the post type with $this->base name and previously you did $this->base = 'portfolio-item';. Also, numberposts is obsolete, use post_per_page instead:

$args = array(
    // 'post_type'  => 'portfolio_item',
    'post_type'     => 'portfolio-item',
    'orderby'       => 'rand',
    'post_per_page' => 1
);

Then, the taxomy argument of your query is wrong. You must use tax_query argument as follow:

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

}

$posts = get_posts( $args );

By default, the arguments exepct terms IDs. If $_POST['usecategory'] is not the term ID but term slug:

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

}

You can all possible combinations in the Codex: WP_Query: taxomomy parameters.

Also, your jQuery has syntax error, you missed });:

jQuery(document).ready(function($) {
  $('.grp_getnew').on('click', function(e){
    e.preventDefault();
    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");
  });
});
  • Adding your code changes nothing. It displays posts from all categories... – Александр Feb 18 '16 at 8:21
  • Check that the name of the taxonomy portfolio-category and that you get a correct value in $_POST['usecategory']. Other than tat, the syntax of the code is correct, 100% sure. – cybmeta Feb 18 '16 at 8:23
  • in admin-panel i check url of portfolio category - taxonomy=portfolio-category. So i don't understand, where is a problem. As i see, it's probably strange, that in php function is ` $args = array('post_type' => 'portfolio-item', 'orderby' => 'rand'... ` and than goes $args['tax_query'] = array(... and than ` $posts = get_posts( $args );` – Александр Feb 18 '16 at 8:29
  • Excuse me, I forget to add the inner array in the tax_query argument. Check it now. – cybmeta Feb 18 '16 at 8:31
  • second array you add brake the function - nothing displays. – Александр Feb 18 '16 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.