this code is designed to select posts with selected meta value in wordpress query

<?php $values = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key  = 'wpcf-scr'",ARRAY_A);?>
<select name="wpcf-scr">
<option value="">default</option>
<?php foreach ($values as $value):?>
<?php if($value['meta_value']):?>
    <option value="<?php echo $value['meta_value']?>"><?php echo $value['meta_value']?></option>
<?php endif;?>
<?php endforeach;?>

I need to re use the code but with selecting posts with tags(manual assigned) not meta values...

something like this below just for explanation (it's wrong)

<?php $values = $wpdb->get_results("SELECT DISTINCT post_tags FROM $wpdb->tags ",ARRAY_A);?>
<select name="tags">
<option value="">default</option>
<option value="tag1">tag1</option>
<option value="tag1">tag2</option>
<option value="tag1">tag3</option>
<option value="tag1">tag4</option>

How to make the second example correctly ?


  • Note that what you're looking for is post_tag not post_tags.
    – RRikesh
    May 10 '13 at 5:17

You could use the wp_dropdown_categories() function and pass post_tag as taxonomy parameter.

<?php wp_dropdown_categories( array( 'taxonomy' => 'post_tag' ) ); ?>

It'll never work, as there is no tags table in a default WP database (nor a post_tags column for that matter). For that query to work, you'd have to look within and join term_relationships, term_taxonomy and terms tables. Complicated stuff.

If you're not familiar with MySQL queries or WP's database structure, just use the get_tags function instead. You don't even have to provide any arguments: it will return all the existing post tags as an array of objects. Here's an example, based on your question's code:

$values = get_tags();
if(sizeof($values) > 0) : ?>
    <select name="tags">
        <option value="">default</option>
        // I've used value=id instead of name / slug, which is always better, but just change the index if desired
        foreach ($values as $value) : ?>
        <option value="<?php echo($value->term_id); ?>"><?php echo($value->name); ?></option>
    <?php endforeach; ?>
<?php endif; ?>

Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.