How to fix: custom categories navigation shows duplicate items - php

I have a category menu that filters the posts shown in the page. My problem is that instead of having an item per category in the menu, I see duplicates of the same Item. It seems like I have as much duplicates as the number of the posts under that category.
Link to the page where the navigation is: http://www.confesercenti.pistoia.it/connessioni/
You can see it under "Filtra le aziende per settore economico". For example, you will notice "COMUNICAZIONE" is repeated five times.
This is the code:
<div id="filters" class="settore_dropdown_wrapper button-group">
<p>Filtra le aziende per settore economico</p>
<ul id="port-list" class="port-filter">
<li><a class="active" data-filter="*">Tutti</a></li>
<?php
$main_convenzione = new WP_Query(array(
'post_type' => 'azienda',
'meta_key' => 'convenzioni_attive',
'meta_value' => 1
));
if ($main_convenzione->have_posts()) : while($main_convenzione->have_posts()) : $main_convenzione->the_post();
// while($main->have_posts()) : $main->the_post();
global $post;
$post_id = $post->ID;
// $terms_list = get_the_terms( get_the_ID(), 'settore' );
$terms_list = get_the_terms( $post_id, 'settore');
// $args = array(
// 'post_type' => 'azienda', // filter by the post type progetto
// 'taxonomy' => 'settore',
// 'hide_empty' => true
// );
// $terms = get_terms($args); // Get all terms of a taxonomy
foreach ( $terms_list as $term_single ) {
$term_name = $term_single->name;
$term_slug = $term_single->slug; ?>
<li><a data-filter=".<?php echo strtolower(preg_replace('/[^a-zA-Z]+/', '-', $term_name)); ?>">
<?php echo esc_attr($term_name); ?></a></li>
<?php }
endwhile; endif; wp_reset_postdata(); ?>
</ul><!--port-list-->
</div><!--filters-->
As stated above it seems like it shows as much duplicates as the number of the posts under that category. My goal is to have one item per category instead of having a al those duplicates

You need to save the filters you need instead of showing them directly. You can use in_array to check if a value is in your array. Something like would work:
<div id="filters" class="settore_dropdown_wrapper button-group">
<p>Filtra le aziende per settore economico</p>
<ul id="port-list" class="port-filter">
<li><a class="active" data-filter="*">Tutti</a></li>
<?php
$main_convenzione = new WP_Query(array(
'post_type' => 'azienda',
'meta_key' => 'convenzioni_attive',
'meta_value' => 1
));
if ($main_convenzione->have_posts()) : while($main_convenzione->have_posts()) : $main_convenzione->the_post();
global $post;
$terms_list = get_the_terms( $post->ID, 'settore');
$terms = [];
foreach ( $terms_list as $term_single ) {
if(!in_array($term_single->name, $terms)) {
$terms[] = $term_single->name;
};
};
endif;
?>
<?php foreach($terms as $term): ?>
<li><a data-filter=".<?php echo strtolower(preg_replace('/[^a-zA-Z]+/', '-', $term)); ?>"><?php echo esc_attr($term); ?></a></li>
<?php endforeach; wp_reset_postdata(); ?>
</ul><!--port-list-->
</div><!--filters-->

Related

Wordpress loop: custom number of posts and sort by date

I have tried to find a solution to something I need on the website (example here: https://www.baiweb.nl/). I have been looking for a way to show a custom number of posts per category AND sort them by date. I have managed to get a single post per category, but I can't seem to fix the rest. It sorts the posts itself by date now, but not all of them.
So, my questions are:
Is it possible to sort this loop, with all different categories, by date?
Is it possible to control the number of posts shown per category? This one is extra for me, not essential, but it would be nice.
Hope someone can help! Thanks a lot in advance for your time!
Here is my code used in the loop now:
<?php
$categories = get_categories();
$cats = array();
foreach($categories as $category) {
$cats[] = $category->name . ", ";
}
$exclude_posts = array();
foreach( $cats as $cat ) {
// build query argument
$query_args = array(
'category_name' => $cat,
'showposts' => 1,
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
);
// exclude post that already have been fetched
// this would be useful if multiple category is assigned for same post
if( !empty($exclude_posts) )
$query_args['post__not_in'] = $exclude_posts;
// do query
$query = new WP_Query( $query_args );
// check if query have any post
if ( $query->have_posts() ) {
// start loop
while ( $query->have_posts() ) {
// set post global
$query->the_post();
// add current post id to exclusion array
$exclude_posts[] = get_the_ID();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class('loop');?>>
<div class="corner"><span><?php foreach((get_the_category()) as $category){ echo $category->name.'<br> '; } ?></span></div>
<!-- thumbnail -->
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="image">
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'medium', true);
if ( in_category('2') || in_category('32') ) {
echo '<div class="newstitle">' . the_title() . '</div>';
}
else {
if ( has_post_thumbnail()) {
echo "<div class='ctr-image test2' style='background-image: url(" . $thumb_url[0] . ")'></div>";
}
else {
echo '<div class="newstitle">' . the_title() . '</div>';
}
}
?>
</a>
<div class="content">
<span class="date"><?php the_time('j/m/Y'); ?></span>
<h3>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php if ( in_category('2') || in_category('32') ) {}
else { echo the_title();} ?>
</a>
</h3>
<div class="text">
<?php html5wp_excerpt('html5wp_index'); // Build your custom callback length in functions.php ?>
</div>
</div>
</article>
<?php
// do something
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
} ?>
You were close. Your categories foreach loop has to englobe everything. Then we do a simple loop but we specify what arguments to use depending on each categories.
Here is our final result.
<?php
$categories = get_categories(); // ... get all our categories
foreach( $categories as $category ) { // ... start foreach categories
if ( $category->name == 'Mercury' ) { // ... if our category name is 'Mercury'
$posts_per_page = 1; // ... 1 post per page if our category is named 'Mercury'
} else { // ... else, for all other categories
$posts_per_page = 3; // ... 3 posts per page
};
$args = array( // ... all our arguments
'posts_per_page' => $posts_per_page, // ... 1 or 3 posts per page depending on our categories
'post_type' => 'post',
'category_name' => $category->name,
'post_status' => 'publish',
'orderby' => 'date', // ... order by date
'order' => 'ASC', // ... most recent first
);
$query = new WP_Query( $args ); // .. start a new loop
if( $query->have_posts() ):
echo '<section>';
echo '<h1>' . $category->name . '</h1>'; // ... only display our section IF a post exist in the category
while( $query->have_posts() ): $query->the_post();
echo '<article>'; // ... our post template
the_title( '<h4>', '</h4>' );
echo '</article>';
endwhile;
echo '</section>';
endif;
wp_reset_postdata(); // ... After looping through a separate query, this function restores the $post global to the current post in the main query.
}; // ... end foreach categories
?>
Thank you so much for your quick and comprehensive answer! The part of the number of categories is working very well, however, the outcome is slightly different than I want. It may be that my question was not clear, apologies for that.
What you have already made beautiful is all the categories with posts that belong to it. What I want to achieve is that all messages are mixed up, sorted by date and, what was already done here, I can indicate how many posts are in per category. Is that even possible?
Some screenshotsof the outcome of your code:
This is what I am trying, except now I need to sort this by date:
This is the code slightly adjusted:
<?php
$categories = get_categories(); // ... get all our categories
foreach( $categories as $category ) { // ... start foreach categories
if ( $category->name == 'Mercury' ) { // ... if our category name is 'Mercury'
$posts_per_page = 1; // ... 1 post per page if our category is named 'Mercury'
} else { // ... else, for all other categories
$posts_per_page = 2; // ... 3 posts per page
};
$args = array( // ... all our arguments
'posts_per_page' => $posts_per_page, // ... 1 or 3 posts per page depending on our categories
'post_type' => 'post',
'category_name' => $category->name,
'post_status' => 'publish',
'orderby' => 'date', // ... order by date
'order' => 'ASC', // ... most recent first
);
$query = new WP_Query( $args ); // .. start a new loop
if( $query->have_posts() ):
// echo '<section>';
// echo '<h1>' . $category->name . '</h1>'; // ... only display our section IF a post exist in the category
while( $query->have_posts() ): $query->the_post();
echo '<article>'; // ... our post template
echo '<h1>' . $category->name . '</h1>';
the_time('j/m/Y');
the_title( '<h4>', '</h4>' );
echo '</article>';
endwhile;
// echo '</section>';
endif;
wp_reset_postdata(); // ... After looping through a separate query, this function restores the $post global to the current post in the main query.
}; // ... end foreach categories ?>
Hope this is clear, thanks again!

How to display current posts custom taxonomy name inside wordpress loop?

I am currently building a Wordpress site and I am encountering some difficulty with the following..
I am trying to dynamically add a class to a HTML element by displaying the custom taxonomy name of the current post type, to use as the class name. This is all being done within a Foreach loop.
My code is as follows
<?php
$args = array( 'posts_per_page' => -1, 'post_type' => 'staff', 'orderby' => 'menu_order',
'order' => 'DESC');
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<?php $terms = wp_get_post_terms( $post_ID, 'department' ); ?>
<?php global $post; $terms = wp_get_post_terms( $post->ID, 'department'); ?>
<div class="grid-item <?php echo $term->slug; ?> ">
<div class="staff-box">
<?php the_post_thumbnail('staff-member'); ?>
<a href="<?php echo the_permalink(); ?>">
<p class="staff-title"><?php the_title(); ?></p>
<p class="staff-job-title"><?php the_field('staff-job-title'); ?></p>
</a>
</div>
</div>
<?php endforeach;
wp_reset_postdata();?>
This is working using slug; ?> to display the class name however it is only displaying "veterinary-surgeons" on every single class name, when it should be displaying the relevant department on each item...
Hope that makes sense.
Many thanks.
To anyone who is interested I have now solved this using:
<?php $term_list = wp_get_post_terms($post->ID, 'department', array("fields" => "all")); ?>
and by using
<?php echo $term_list[0]->slug ; ?>
as class name.
Thanks
You can solve this problem by this code also,
Put this code inside while loop, 'portfolio_category' is custom taxonomy name
$terms = get_the_terms( $post->ID, 'portfolio_category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term ) {
$links[] = $term->name;
}
$tax_links = join( " ", str_replace(' ', '-', $links));
$tax = strtolower($tax_links);
else :
$tax = '';
endif;

Randomise X most recent wordpress posts

I've got the following code which will display 4 random posts from the defined category. However, that's a little too random, I need it to display the 4 most recent, and then randomise them in particular each time the page is refreshed.
Otherwise I just end up getting articles which could date back over 2 years ago appear on the homepage.
<div class="article-block-v1">
<?php
//get terms (category ids 11,2,33,34), then display one post in each term
$taxonomy = 'category';// e.g. post_tag, category
$param_type = 'category__in'; // e.g. tag__in, category__in
$term_args=array(
'include' => '1459',
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
foreach( $terms as $term ) {
$args=array(
"$param_type" => array($term->term_id),
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 4,
'orderby' => 'rand',
);
$my_query = null;
$my_query = new WP_Query($args);
$i = 1;
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php if ($i == 1): ?>
<div class="article-block-v1">
<div class="category-label-large category-news-analysis">
<p><?php echo $term->name; ?></p>
</div>
<div class="view2 third-effect">
<?php the_post_thumbnail(); ?>
<div class="mask">
</i>
</div>
</div>
<ul class="homepagewhitebg">
<li><h5><?php the_title(); ?></h5></li>
</ul>
</div>
<?php else: ?>
<li><p><?php the_title(); ?></p></li>
<?php endif; ?>
<?php
$i++;
endwhile;
echo '</ul>';
}
}
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
Demo 1 (4 Most Recent) - Regular without random orderby
Article #1001
Article #1002
Article #1003
Article #1004
Demo 2 (4 Most Recent - But with order by random on those 4)
Article #1003
Article #1001
Article #1004
Article #1002
UPDATE
I'm also trying this now, however it's not taking into account the category I've defined, nor is it randomising across the 4 displayed:
<div class="article-block-v1">
<?php
$number = "4";
$posts = "SELECT * from $wpdb->posts WHERE post_type='post' ORDER BY post_date DESC LIMIT $number";
$postX = array();
$postresult = mysql_query($posts) or die(mysql_error());
while ($row = mysql_fetch_array($postresult)) {
$postX[] = $row[0];
}
$ids = shuffle($postX);
$ids = implode(',', $postX);
echo $ids;
?>
<?php
$args = array(
'posts_per_page'=> $number,
'post__in' => explode(',', $ids),
'include' => '1451',
'orderby' => 'rand'
);
query_posts($args);
?>
<?php while (have_posts()) : the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
You can use shuffle(). You're going to want to get the 4 most recent posts (in order) before shuffling them. Quite simply, you could do something like the following:
// Get the 4 most recent posts
$args = array( 'numberposts' => 4 );
$recent_posts = wp_get_recent_posts( $args );
// Shuffle them
shuffle($recent_posts)
foreach( $recent_posts as $recent ){
// Do something with the $recent post
}
You may need to pass additional $args to the function, for your specific constraints.

Custom Post Query WordPress and a better way to display posts

This seems a little noob, but I didn't found a better option. I created a custom loop to display only the title of custom post type I created.
Example:
Custom Post Type: Atuação
Contratos (Cível e Societário)
Direito Penal Empresarial
The problem is: I can't "validate" at the menu if the post is active or only a link. Example: My visitor is visiting the Direito Penal Empresarial page. But the menu don't display any class so I can customize it. It just shows the <a href> link.
See the code of the custom loop below.
<ul class="menu-advogados">
<?php
// WP_Query arguments
$args = array (
'post_type' => 'atuacao_posts',
'pagination' => false,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$exibir_atuacao_posts = new WP_Query( $args );
// The Loop
if ( $exibir_atuacao_posts->have_posts() ) {
while ( $exibir_atuacao_posts->have_posts() ) {
$exibir_atuacao_posts->the_post();
?>
<li><?php the_title(); ?></li>
<?php
}
} else {
echo "Nenhum post encontrado";
}
// Restore original Post Data
wp_reset_postdata();
?>
</ul>
There is any better solution for this? Or if not, how can I add the "active" class to the href?
UPDATE: You can check out the website live.
You need to store current post ID in a variable then you need to compare current Post ID with list item Post ID if both are same then apply active class. So your code will be something like this-
<ul class="menu-advogados">
<?php
global $post;
$post_id = $post->ID; // Store current page ID in a variable.
// WP_Query arguments
$args = array (
'post_type' => 'atuacao_posts',
'pagination' => false,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$exibir_atuacao_posts = new WP_Query( $args );
// The Loop
if ( $exibir_atuacao_posts->have_posts() ) {
while ( $exibir_atuacao_posts->have_posts() ) {
$exibir_atuacao_posts->the_post();
?>
<li><a href="<?php the_permalink(); ?>" <?php echo ($post_id==$post->ID)?'class="active"':''; ?> ><?php the_title(); ?></a></li>
<?php
}
} else {
echo "Nenhum post encontrado";
}
// Restore original Post Data
wp_reset_postdata();
?>
</ul>
use this
// WP_Query arguments
$args = array (
'post_type' => 'atuacao_posts',
'post_status' => 'publish',
'pagination' => false,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
<?php if ( $query ->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $query ->have_posts() ) : $query ->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
for WP_Query consider this link it's great article...

Word "Array" is Appearing on Blog Posts Page

I'm getting the word "Array" coming up on my blog POSTS page when I use the below code. I have a feeling that it relates to this line:
I am using a similar template for my PORTFOLIO and NEWS pages where the wording is slightly different on this line ("showportcat" and "shownewscat" instead of "get_the_category") and it should be displaying the categories but instead, the word 'array' is in it's place.
I've tried "showpostcat" but that didnt' work so I wonder if I need to be re-wording it? Or maybe the problem is on another part of the code which I've included below?
<div class="greyblock">
<h4 class="nomar"><?php echo the_title(); ?></h4>
<div class="sep"></div>
<?php echo get_the_category(get_the_ID()); ?>
<div class="clear"></div>
<ul class="blogpost_list columns2">
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$args = array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => get_option("posts_per_page"),
);
if (isset($_GET['slug'])) {
$args['tax_query']=array(
array(
'taxonomy' => 'postcat',
'field' => 'slug',
'terms' => $_GET['slug']
)
);
}
$wp_query->query($args);
?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post();
#We have:
#get_permalink() - Full url to post;
#get_the_title() - Post title;
#get_the_content() - Post text;
#get_post_time('U', true) - unix timestamp
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
echo "
<li class='pc'>
<img alt='".get_the_title()."' src='".TIMTHUMBURL."?w=400&h=400&src=".$featured_image[0]."'>
<h4>".get_the_title()."</h4>";
$terms = get_the_terms($post->ID, 'postcat');
if ( $terms && ! is_wp_error( $terms ) ) {
$draught_links = array();
foreach ( $terms as $term ) {
$draught_links[] = $term->name;
}
$on_draught = join( ", ", $draught_links );
}
echo "
<p>".get_the_excerpt()."</p>
<a href='".get_permalink()."' class='read'>Read more</a>
<br class='clear' />
</li>
";
endwhile; ?>
</ul>
</div>
<?php get_pagination() ?>
<?php $wp_query = null; $wp_query = $temp; ?>
How about:
$categories = get_the_category(get_the_ID());
foreach ($categories as $category) {
echo $category;
}
The problem is still there. I'm guessing it relates to the way I am wording one of the below two lines as it is 'showportcat' for portfolios and 'shownewscat' for news but 'showpostcat' doesn't work for posts so I just can't figure it out:
<?php echo get_the_category(get_the_ID()); ?>
**OR**
'taxonomy' => 'postcat',

Categories