Support » Fixing WordPress » More Fields Plugin – get_post_meta function not working in Functions.php

  • Resolved cadencehart

    (@cadencehart)


    Hello! I’m using the genesis theme so most of the time, I am using hooks to add and remove elements from posts and pages via functions.php.

    I have installed More Fields to take care of my posts’ custom fields. My problem is that, I can’t get the get_post_meta($post->ID, $key, true); function to work.

    My code is:

    add_action( 'genesis_before_post_content', 'addImage' );
    function addImage() { ?>
    <?php $image = get_post_meta($post->ID, 'image-url', true);
    //Checking if anything exists for the key image
    if ($image) {
    echo '<img src="'. $image .'" style="float:left;" />';
    } //if there is nothing for image then display
    else {
    // none
    } ?>
    <?php }

    I have used the above code in page templates multiple times before with the More Fields plugin, and it works. This time, when using it in functions.php, the code is not working.

    I hope someone can point me to the right direction. Thanks!

Viewing 1 replies (of 1 total)
  • Ok now I know what;s wrong. Below is the correct code:

    add_action( 'genesis_before_post_content', 'addImage' );
    function addImage() { ?>
    <?php $image = get_post_meta(get_the_id(), 'image-url', true);
    //Checking if anything exists for the key image
    if ($image) {
    echo '<img src="'. $image .'" style="float:left;" />';
    } //if there is nothing for image then display
    else {
    // none
    } ?>
    <?php }

    Both codes are correct but since I am calling the function within the loop, $post->ID should be replaced with get_the_id().

Viewing 1 replies (of 1 total)
  • The topic ‘More Fields Plugin – get_post_meta function not working in Functions.php’ is closed to new replies.