InsideDarkWeb.com

How to break meta values into different items and avoid duplicates?

I’m trying to build a filter for a custom post type page. The custom post type has a metabox that allows inputting of different authors.

I am displaying the post names in a dropdown like this, using the get_post_meta:

/*Get the Authors*/
$list_authors = array(
'post_type'         => array('publications'),
);
$authors = array();
$query_authors = new WP_Query( $list_authors );

if ( $query_authors->have_posts() ) :
while ( $query_authors->have_posts() ) : $query_authors->the_post();
$author = get_post_meta(get_the_id(), 'cl_pub_authors', true);
if(!in_array($author, $authors)){
$authors[] = $author;
}
endwhile;
wp_reset_postdata();
endif;
foreach( $authors as $author ):
?>
<option value="<?php echo $author;?>"><?php echo $author;?></option>
<?php endforeach; ?>

The problem is that some values are grouped together, typed separated by commas. I need to take every value in the field as individual, and avoid duplicates.

One Answer

This is just a basic php array question - not a WP question.

function unique_authors ( $authors ) {
    $newArray = array();

    foreach( $authors as $item ) {
        $itemArray = explode( ", ", $item );
        $newArray = array_merge($newArray, $itemArray);
    }

    $newArray = array_unique($newArray);
    return $newArray;
}

$authors = unique_authors( $authors );

foreach( $authors as $author ):  //etc

Answered by shanebp on November 11, 2021

Add your own answers!

Related Questions

How to add post_distinct filter to WP_Comment_Query?

2  Asked on August 17, 2020 by jonathan-gruber

   

How can I combine one field using wpdb and group by?

1  Asked on August 10, 2020 by user81828

   

Custom posts password protect

1  Asked on August 6, 2020 by jason

   

REST API: Display Category names in JSON?

1  Asked on August 3, 2020 by steve

       

Gutenberg withInstanceId. When to use it?

2  Asked on July 25, 2020 by at-least-three-characters

 

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.