0

I have saved the meta key with the name writer_meta_key and want to retrieve it on my custom-functions page. I can get it on front page and single page but it doesn't work on my custom-function page. Here is my code. It gives only title but not the writer's name.

$term       = get_queried_object();
$tax_object = get_taxonomy( $term->taxonomy );
$post_type_array = $tax_object->object_type;
$post_type  = $post_type_array[0];

$posts      = get_posts( array(
    'post_type' => $post_type,
    'taxonomy'  => $term->taxonomy,
    'term'      => $term->slug
) );

foreach ($posts as $post) {
    $id = get_the_ID();
    $custom_meta_writer = get_post_meta( $id, 'writer_meta_key', true );       
    $writer = $custom_meta_writer['writer'];
    echo $post->post_title; 
    echo $writer; 
}

When I echo $id it shows error as

Array
Array
Array
Array

Where have I mistaken??

  • Welcome to WPSE. Where is your custom-function page used? Is it an include file called by a page template? – jdm2112 Jan 30 at 19:04
  • It's included in a folder inc and is called in functions.php – Jklyn Jan 30 at 19:09
  • It is important to remember that WordPress is an application that runs when a user requests content and does nothing otherwise (over-simplified) so my question is related to that. What triggers the code above to actually run? Typically custom functions (or plugins) are fired when the action they are hooked to is called. – jdm2112 Jan 30 at 19:13
  • First of all I'ven't used any plugins in this project. This is just a page where I've done all the codings. The above code displays the category posts and what I need is to retrive the meta key of the title. – Jklyn Jan 30 at 19:20
  • To simplify the question - how does this code get called? It isn't in a function hooked to an action. It is not part of a page template. How would WordPress know this code exists? – jdm2112 Jan 30 at 19:30
0

WordPress uses a global $post to keep track of the current post the user is viewing. Whenever you call functions like the_title() or get_the_ID() it uses that global $post to pull that data. In your code snippet you're using get_posts() which generally does not overwrite the global $post object unless you specify with setup_postdata( $post ).

The easiest thing to do is to simply modify your metadata line and use:

$custom_meta_writer = get_post_meta( $post->ID, 'writer_meta_key', true );
  • 1
    I used setup_postdata( $post ); after foreach loop and it worked. Thanks. I'll accept your answer. – Jklyn Jan 31 at 5:15
  • @Jklyn By using setup_postdata( $post ) you're overwriting the global $post object. Make sure you reset it by calling wp_reset_postdata() after your loop. – Howdy_McGee Jan 31 at 15:22

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.