WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] More Fields Plugin - get_post_meta function not working in Functions.php (2 posts)

  1. cadencehart
    Member
    Posted 2 years ago #

    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!

  2. cadencehart
    Member
    Posted 2 years ago #

    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().

Topic Closed

This topic has been closed to new replies.

About this Topic