Query the wp_postmeta table using wpdb from wodpress

Asked

Viewed 316 times

0

How do I print a table query on the page wp_postmeta filtering through meta_key using wpdb of wordpress? Already with the right structure. Someone can help me?

1 answer

2

The class wpdb provides a direct interface with the bank. Using an example of the Codex:

<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'miles';
$allmiles = $wpdb->get_var( $wpdb->prepare( 
    "
        SELECT sum(meta_value) 
        FROM $wpdb->postmeta 
        WHERE meta_key = %s
    ", 
    $meta_key
) );
echo "<p>Total miles is {$allmiles}</p>";
?> 

Of course here you can change the meta_key and what you want to select (in this case, the sum(meta_value)) for whatever best suits you.

I’m not particularly adept at messing with wp’s global ones. The class’s own documentation is full of warnings for use with caution. Anyway, there are many ways to interact with the wordpress Metadata, one of them, is the methodget_post_meta(), but of course it varies from case to case.

  • 1

    Surely the best option is get_post_meta...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.