How to remove duplicated results from a foreach loop - wordpress

I'm trying to add some sidebar content to my WordPress search results page where the top categories and tags, related to the current search query, are displayed. I have been able to generate the content, but there are a massive amount of duplicates also displaying. Click for my example page.
I've tried two ways of doing this, both with no success. Both were pulled from previous threads with similar questions. I would prefer avoiding 3rd party plugins if possible. Any ideas would be appreciated. Thanks
Method #1:
function list_search_cats() {
// Start the Loop
$uniqueCats = array();
while ( have_posts() ) : the_post();
$cats = get_the_category();
if (! in_array($cats, $uniqueCats)) :
$uniqueCats[] = $cats;
foreach($cats as $cat) :
echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>';
endforeach;
endif;
endwhile;
}
Method #2:
function list_search_cats() {
// Start the Loop
$uniqueCats = array();
while ( have_posts() ) : the_post();
$cats = get_the_category();
$cats = array_unique($cats, SORT_REGULAR);
foreach($cats as $cat) :
echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>';
endforeach;
endwhile;
}

It looks to me like you're just missing the actual check of each category. You may need an extra foreach loop to check for dupes, then use that unique array in another foreach to display the categories. Try this:
function list_search_cats() {
// Array to put unique cats in
$uniqueCats = array();
while ( have_posts() ) : the_post();
$cats[] = get_the_category();
// first foreach to check each cat and put in to new array
foreach($cats as $cat) {
if(!in_array($cat, $uniqueCats)) {
$uniqueCats[] = $cat;
}
}
// second foreach to display the list
foreach($uniqueCats as $cat_li) {
$term = get_term_by('name', $cat_li, 'category');
echo '<li><a class="tag" href="'.get_category_link($term->term_id)).'">' . $cat_li . '</a></li>';
}
endwhile;
}

Related

Get a Value in the Author Page from a Custom Taxonomy

I have created a Custom Taxonomy called nationality, then I added it to let the user chose his/her nationality through a Custom Account Edit Form using ACF.
I am trying to get the Tax value into the Author.php page but it returns as Array ,
This is my code which I am using:
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$terms = wp_get_post_terms($post->ID, 'nationality' , $curauth);
if ($terms){
$out = array(
'name'=>'<span>Nationality: </span>'
);
foreach ($terms as $term)
{
$out[] = '<a " ' . ' href="' . esc_url(get_term_link( $term->slug, 'nationality')) .'">' .$term->name .'</a>' ;}
echo join( ' ', $out );
}
?>
I have also tried the following code:
<?php
$nationality = get_field('nationality', $curauth);
$nationality = get_field_object('nationality', $curauth);
echo $nationality['value'];
?>
still giving me an Array.
The Field type is select and Return Value is set to Term Object either Term ID
the error then is
Object of class WP_Term could not be converted to string
any Ideas how to make this Correct.
Thank you!
Ahmad
are you trying to get the custom taxonomy from the current user? try like this:
get_the_terms( get_the_ID(), 'nationality' )
and if you are sure it will always get only one (take into account some people have more than one nationality) just access the first element:
get_the_terms( get_the_ID(), 'nationality' )[0]
I have the right Code here :
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$terms = get_field('nationality', $curauth);
if( $terms ): ?>
<?php foreach( $terms as $term ): ?>
<?php echo $term->name ; ?>
<?php endforeach; ?>
<?php endif; ?>

Reversing sort order of ingested RSS feed in PHP

I have a site where I am 'pulling' local events from a secondary website RSS feed. I have this working however the feed is displaying in reverse order with the local events dated later (i.e. at the end of October versus events dated for today) showing up at the top instead of the bottom.
Here is the code I am using for the feed ingest:
<?php if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed
$limit = $feed->get_item_quantity(25); // specify number of items
$semti = array_flip($limit);
$items = $feed->get_items(0, $limit); // create an array of items
}
if ($limit == 0) echo '<div>The feed is unavailable.</div>';
else foreach ($items as $item) : ?>
<p><b><a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank">
<?php echo esc_html( $item->get_title() ); ?></a></b>
<?php echo esc_html( $item->get_date('| j F | g:i a') ); ?><br>
<?php echo sanitize_text_field( $item->get_content() ); ?>
</p>
<?php endforeach; ?>
This works perfectly to get my remote RSS feed and display the title, date of the event and the excerpt, however the order is reverse sorted.
I tried adding filters like "sort and ksort" in the "foreach ($items $items) :" area but this did not work for me. I've racked my brains on this one and am hoping someone can help me out. I appreciate any guidance/help in advance.
Try the appropriately named array_reverse function!
<?php if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed
$limit = $feed->get_item_quantity(25); // specify number of items
$items = $feed->get_items(0, $limit); // create an array of items
$semti = array_reverse($items); // & flip it
}
if ($limit == 0) echo '<div>The feed is unavailable.</div>';
else foreach ($semti as $item) : ?>
<p><b><a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank">
<?php echo esc_html( $item->get_title() ); ?></a></b>
<?php echo esc_html( $item->get_date('| j F | g:i a') ); ?><br>
<?php echo sanitize_text_field( $item->get_content() ); ?>
</p>
<?php endforeach; ?>
From PHP.net:
array_reverse
Return an array with elements in reverse order
array array_reverse ( array $array [, bool $preserve_keys = false ] )
Takes an input array and returns a new array with the order of the elements reversed.

wrap each custom post taxonomy term within an li - using a foreach loop

I'm trying to display a number of custom post taxonomy terms - but each within their own specific list item.
I have a site which is about garages. (developing on localhost so don't have a link yet).
I have a custom post type called Cars. Within this I have a custom post taxonomy with the make of the Car 'Ford' in this case.
Within 'Ford' is a list of custom post taxonomy terms of all the ford cars at that garage. 'GT', 'Sierra', 'Orion'.
Instead of listing the terms: 'GT', 'Sierra', 'Orion'. I want to show a picture of the car within a ul list.
I've created a sprite with all the images and want to loop through these setting the background position for each li item.
The first lot of code below displays a list of of the terms which is all good, but not what I want. Right at the bottom is the code which I've tried to add the list items to but just getting a blank screen...
Any help, much appreciated. Thanks
<?php if ( get_post_type() == cars ) { ?>
<div class="entry-meta-custom">
<?php
$terms = get_the_terms( $post->ID, 'ford' );
if ( $terms && ! is_wp_error( $terms ) ) :
$draught_links = array();
foreach ( $terms as $term ) {
$draught_links[] = $term->name;
}
$on_draught = join( ", ", $draught_links );
?>
<?php echo $on_draught; ?>
<?php endif; ?>
</div><!-- .entry-meta-custom -->
<?php } ?>
And here's where I've tried to add the list items.
<?php if ( get_post_type() == cars ) { ?>
<div class="entry-meta-custom">
<?php
$terms = get_the_terms( $post->ID, 'ford' );
if ( $terms && ! is_wp_error( $terms ) ) :
$draught_links = array();
foreach ( $terms as $term ) {
if ($term->name == 'gt') {
$term->name = '<li class="gt">' . $term->name . '</li>';
}
if ($term->name == 'sierra') {
$term->name = '<li class="sierra">' . $term->name . '</li>';
}
if ($term->name == 'orion') {
$term->name = '<li class="orion">' . $term->name . '</li>';
}
$draught_links[] = $term->name;
}
$on_draught = join( ", ", $draught_links );
?>
<?php echo '<ul>' . $on_draught . '</ul>; ?>
<?php endif; ?>
</div><!-- .entry-meta-custom -->
<?php } ?>
I worked it out. Below is the code for anyone that is looking to replace custom post taxonomy list terms with individual images which are link to the term archive.
Source http://codex.wordpress.org/Function_Reference/get_term_link
<?php if ( get_post_type() == cars ) { ?>
<div class="entry-meta-custom">
<?php
$terms = get_terms('ford');
echo '<ul>';
foreach ($terms as $term) {
echo '<li class="'.$term->name.'"></li>';
}
echo '</ul>'; ?>
</div><!-- .entry-meta-custom -->
<?php } ?>

WordPress - How to do "current-page-item" classes in a list of custom taxonomy terms?

I have the following code that generates a list of terms in a taxonomy term, and then POSTS that are under each term.
I want to have a current-page-item class added to the current item, so that when you are on a page under the taxonomy term, its related item in the nav is styled. Here is my code:
<?php $terms = get_terms('benefit-cats');
echo "<ul>";
foreach ($terms as $term) {
$wpq = array ('taxonomy'=>'benefit-cats','term'=>$term->slug,'order'=>'asc','orderby'=>'title');
$query = new WP_Query ($wpq);
echo "<li class=".$term->slug."><span class=\"list-item\"><span class=\"text-arrow\">►</span> ".$term->name."</span>"; ////
echo "<ul class=\"children\">";
?>
<?php
if ($query->have_posts() ) : while ($query->have_posts() ) : $query->the_post(); ?>
<li><span class="text-arrow">►</span> <?php the_title();?></li>
<?php endwhile; endif; wp_reset_query(); ?>
<?php
echo "</ul></li>";
}
echo "</ul>";
?>
You can try something like this...
Specify the current post_id before your loop, then condition to see if post loop contains your post_id.
// before loop
$page_id = $wp_query->get_queried_object_id();
// replace <li><span class="text-arrow">►</span>
if($page_id ==$query->post->ID ) $class = " current-page-item";
<li><span class="text-arrow<?php echo $class; ?>">►</span>

How can i reset a query in a custom wordpress metabox

I'm working on this plugin for wordpress and i am stuck on a query that won't be reset.
In the following function:
function WPSM_artists_autocomplete(){
$response = array();
query_posts('post_type=artist&posts_per_page=-1');
if (have_posts()) : while (have_posts()) : the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'artist-icon');
$image_url = $image_url[0];
$response[] = array( get_the_ID() , get_the_title() , null, '<img src="'.$image_url.'" />'. get_the_title());
endwhile; endif;
wp_reset_query();
// Write JSON file
$output = json_encode($response);
$data = WPSM_CACHE_DIR."/data.json";
$fh = fopen($data, 'w') or die("can't open file");
fwrite($fh, $output);
fclose($fh);
// Return JSON url
echo WPSM_CACHE_URL."/data.json";
}
I use a query_posts to populate a metabox. But the wp_reset_query(); doesn't seem to work properly. This affects all other metaboxes and post related option. The global $post variable is set to the latest value of this query, and not the default value of the posts edit page.
I'd love to hear how to solve this plugin. Could use everything to get me in the right direction. Thanks in advance!
Cheers,
Ronny
I came across this today and found a fix.
You will need to store the original $post before starting a new loop and then at the end of your function you will need to set it back.
Before you function assign $post to a temporary variable.
$original_query = $wp_query;
Then at the end of your function set it back.
$wp_query = $original_query;
wp_reset_postdata();
Not sure if the above works in your case as I was using a custom query.
I have posted my code below so you can have a look.
global $wpdb;
global $post;
$originalpost = $post;
$querydetails = "
SELECT *
FROM $wpdb->posts
WHERE $wpdb->posts.post_type = 'projects'
AND $wpdb->posts.post_status = 'publish'
ORDER BY $wpdb->posts.post_date DESC
";
$pageposts = $wpdb->get_results($querydetails, OBJECT);
if ($pageposts) {
foreach ($pageposts as $post) {
setup_postdata($post);
$postID = get_the_ID();
echo '<option value="';
echo $postID . '"';
foreach ($meta as $m) {
if ($postID == $m) echo ' selected="selected" ';
}
echo '>';
echo the_title();
echo '</option>';
}
}
echo "</select>";
$this->show_field_end($field, $meta);
$post = $originalpost;

Resources