0

I am using get_post() to call a single Wordpress post using it's post ID. I have successfully managed to pull the content / title of the post but would like to also pull custom fields also.

The code below is how I declare custom fields in a standard wp_query:

$customField = (get_post_meta($post->ID, "_mcf_customField", true));

And my get_post code below:

                $my_id = 401491;
                $post_id = get_post($my_id);
                $customField = get_post_meta($post_id, "_mcf_customField", true); // I do not think this is correct
                $content = $post_id ->post_content;

                echo $content;
                echo $customField; // No output

I believe the customField variable above is declared incorrectly, cannot seem to find anything in the Codex that sheds any light though. Does anyone have experience using Custom fields with get_post?

  • I think, get_post_meta should be called with $my_id instead of $post_id. – M-R Oct 28 '15 at 12:03
2

You already know the ID, so just use it:

$customField = get_post_meta($my_id, "_mcf_customField", true);

But only for reference, if you want to get the ID from the object:

$customField = get_post_meta($post_id->ID, "_mcf_customField", true);
| improve this answer | |
  • Thanks bud, used first suggestion and works perfectly. Didn't need to get_post being called by $post_id. – James Oct 28 '15 at 12:07
  • That's true! Once you have the ID, you can use mostly post functions with it without querying. Cheers! – Bruno Cantuaria Oct 28 '15 at 12:23
-1

With ACF, i am able to do this:

$my_field = get_field('my_field', $post->ID);

Reference: https://www.advancedcustomfields.com/resources/get_field/

| improve this answer | |
  • why the downvote? please explain, i am happy to improve my answer if needed. – luschn Feb 7 at 13:10

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.