sql - Get post from meta_key and meta_value

admin2025-06-02  1

I have this sql statement:

SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2

I am facing one problem:

I don't know how to do that sql code with wordpress functionalities. I have read the manual to get_posts() etc. (though I might have missed something), but I haven't found a way to implement this yet.

Can you help me and show me a way or a hint.

Thanks in advance

I have this sql statement:

SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2

I am facing one problem:

I don't know how to do that sql code with wordpress functionalities. I have read the manual to get_posts() etc. (though I might have missed something), but I haven't found a way to implement this yet.

Can you help me and show me a way or a hint.

Thanks in advance

Share Improve this question edited Mar 15, 2019 at 14:27 A new 1 asked Mar 15, 2019 at 13:12 A new 1A new 1 231 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

You can get using this using SQL

global $wpdb;

// For single record
$wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2");

// For multiple records
$wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2" );

Use this for query

 $args = array(
        'posts_per_page' => 10, // -1 for all posts
       'meta_query' => array(
           array(
               'key' => 'your_meta_key',
               'value' => 'your_meta_value',
               'compare' => '=',
           )
       )
    );
    $the_query = new WP_Query($args);

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

Try Like:

global $wpdb;

$post = $wpdb->get_results('SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2');

Using Wordpress default method:

$args = array(
    'posts_per_page'   => -1,
    'meta_query' => array(
        array(
            'key'     => 'YOUR KEY',
            'value'   => 'YOUR VALUE',
            'compare' => '=',
        ),
    ),
);

$posts = get_posts( $args );

Then print result of $post like print_r($post) and check have you get your post_id or not. Please let me know if any query.

Hope it will help!

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748803031a313848.html

最新回复(0)