Reputation: 1519
I am working on a wordpress webpage in which I want to show zero post for a specific category. Following is the code for that:
<?PHP
$temp_args = [
'post_status' => 'publish',
'orderby' => array(
'feat_yes' => 'ASC',
'post_type' => 'ASC',
'date' => 'DESC'),
'posts_per_page' => $data->{"no_articles_".ICL_LANGUAGE_CODE}, // Line A
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $cat_today,
],
],
];
echo '<pre>'; print_r($temp_args); echo '</pre>';
$q = new WP_Query($temp_args);
echo "Have posts: ";
echo '<pre>'; print_r($q->have_posts()); echo '</pre>';
if ($q->have_posts()) {
while ($q->have_posts()) {
$q->the_post();
$post_type = strtolower(get_post_type());
switch ($post_type) {
}
}
wp_reset_postdata();
}
?>
I have added Line#A in order to control to number of posts for a specific category. When the value of 'posts_per_page' => 0
then it shows all list of posts for that particular specific category which I am not sure why.
Problem Statement:
I am wondering what changes I should make in the php code above when 'posts_per_page' => 0
then it should show zero post.
Upvotes: 1
Views: 1462
Reputation: 2483
This is a longstanding bug in WordPress Core. See Trac ticket #24142.
You can just make sure it's greater than 0 before running the code by wrapping everything in an if statement:
<?PHP
if( $data->{"no_articles_".ICL_LANGUAGE_CODE} >= 1 ) {
$temp_args = [
'post_type' => array('current-channel', 'post', 'current-episodes'),
'post_status' => 'publish',
'orderby' => array(
'feat_yes' => 'ASC',
'post_type' => 'ASC',
'date' => 'DESC'),
'posts_per_page' => $data->{"no_articles_".ICL_LANGUAGE_CODE}, // Line A
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $cat_today,
],
],
];
echo '<pre>'; print_r($temp_args); echo '</pre>';
$q = new WP_Query($temp_args);
echo "Have posts: ";
echo '<pre>'; print_r($q->have_posts()); echo '</pre>';
if ($q->have_posts()) {
while ($q->have_posts()) {
$q->the_post();
$post_type = strtolower(get_post_type());
switch ($post_type) {
case 'current-episodes':
get_template_part('template-parts/content-search', 'video');
break;
case 'current-channel':
if (get_post_meta($post->ID, "current_portal_end_date_timestamp", true) > time()) {
echo "Hello World";
get_template_part('template-parts/content-search', 'channel');
}
break;
case 'post':
get_template_part('template-parts/content', 'search');
break;
}
}
wp_reset_postdata();
}
}
?>
Upvotes: 2