mysql custom wp query

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;?>
</select>

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

Read More

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>
</select>

How to make the second example correctly ?

thanks

Related posts

Leave a Reply

2 comments

  1. 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:

    <?php
    $values = get_tags();
    if(sizeof($values) > 0) : ?>
        <select name="tags">
            <option value="">default</option>
        <?php
            // 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; ?>
        </select>
    <?php endif; ?>
    

    Good luck!