J'utilise un plugin pour le widget Obtention de la publication aléatoire et de l'URL via ajax. Merci fischi pour l’aide à la réécriture des fonctions. Le problème est que la fonction renvoie toutes les publications de CPT, donc la sélection de catégorie ne fonctionne pas.
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(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>
Pourquoi get_posts () ne renvoie pas uniquement les publications de catégorie sélectionnées dans Type de publication personnalisée? Toute aide, s'il vous plaît!
UPDATE Donc, j'ai fait print_r($args);
de mon appel ajax et il montre
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-sketches-2\/","title":"Rough Sketches","thumb":"\"ss\"","content":"[\/vc_column_text][\/vc_column][\/vc_row]"}
Le portefeuille est donc un CPT intégré au thème
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' ),
));
}
}
Premièrement, votre type de message personnalisé est portfolio-item
, pas portfolio_item
. Notez que vous enregistrez le type de publication avec $this->base
nom et que vous avez précédemment enregistré $this->base = 'portfolio-item';
. De plus, numberposts
est obsolète, utilisez post_per_page
à la place:
$args = array(
// 'post_type' => 'portfolio_item',
'post_type' => 'portfolio-item',
'orderby' => 'Rand',
'post_per_page' => 1
);
Ensuite, l'argument taxomie de votre requête est faux. Vous devez utiliser l'argument tax_query
comme suit:
if ( isset( $_POST['usecategory'] ) && intval( $_POST['usecategory'] ) != 0 ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'portfolio-category',
'terms' => intval( $_POST['usecategory'] )
)
);
}
$posts = get_posts( $args );
Par défaut, les arguments excluent les identifiants de termes. Si $_POST['usecategory']
n'est pas l'identifiant du terme mais le slug du terme:
if ( isset( $_POST['usecategory'] ) && intval( $_POST['usecategory'] ) != 0 ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'portfolio-category',
'field' => 'slug',
'terms' => $_POST['usecategory']
)
);
}
Vous pouvez toutes les combinaisons possibles dans les paramètres Codex: WP_Query: taxomomy .
De plus, votre jQuery a une erreur de syntaxe, vous avez manqué });
:
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");
});
});