2

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

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
}
  • This is good but i think my instructor dont want me to use sql, but instead use wp functions like get_post(). Do you know a function that translates to this sql? – A new 1 Mar 15 at 13:24
  • i updated answer please check – Prince Mar 15 at 13:27
  • if the answer is correct. please tick it correct. Thanks – Prince Mar 15 at 13:32
  • actually both answers are correct ... its a dilemma – A new 1 Mar 15 at 13:33
0

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!

  • This is good but i think my instructor dont want me to use sql, but instead use wp functions like get_post(). Do you know a function that translates to this sql? – A new 1 Mar 15 at 13:24
  • I have update my answer so please try and let me know if any query – Pratik Patel Mar 15 at 13:28
  • @Anew1 Please try get_post method. – Pratik Patel Mar 15 at 13:29

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.