Extracting objects from database for specific posts

SLE :

I have the below code:

$test = get_post_meta($post->ID, 'author', true);
var_dump($test);

Which returns me these two IDs:
enter image description here

These are two IDs inside my wp_posts database table, how would I be able to extract both post_title and the guid? Here is what's shown in the database:
enter image description here

Xhynk :

Since you're already using WordPress' helper functions, the easiest way would probably be to use the relevant helper functions get_the_title() and get_the_guid().

Something like this:

if( $_author = get_post_meta( $post->ID, 'author', true ) ){
    foreach( $_author as $id_string ){
        $guid       = get_the_guid( $id_string );
        $post_title = get_the_title( $id_string );
    }
}

You could also use the $wpdb class (specifically the $wpdb::get_results() method), but that involves writing your own SQL query, safely turning it into a prepared statement to prevent SQL injection vulnerabilities with the $wpdb::prepare() method, and just overall seems more complicated than necessary for something as simple as getting two fields from the posts table.

global $wpdb;
$_author = get_post_meta( $post->ID, 'author', true );
$format  = array_fill( 0, count($_author), '%d' );
$format  = implode(',', $format);

$sql = "
    SELECT post_title, guid
    FROM   {$wpdb->posts}
    WHERE  ID
    IN ({$format})
    GROUP BY ID
";

$results = $wpdb->get_results( $wpdb->prepare( $sql, array($_author) ) );

The above function is untested, but should be pretty close to working, just showing that it's a bit more complicated than using the built in functions WordPress already has that do this kind of work for you.

WordPress has plenty of handy helper functions like that, generally they follow the naming convention get_the_[object]_[part_of_object](), and generally the ones that start with the_ (omitting the get_) will echo the value instead of just returning it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9721&siteId=1