Forums

Help Me Get A Custom Field Value while Inside a Plugin (4 posts)

  1. phpwannabe
    Member
    Posted 2 years ago #

    Greetings,

    I can't get the value of a custom field assigned to a string variable inside a plugin for the life of me.

    Here is what I've done so far..

    I added this function to functions.php in my theme..

    function get_custom_field_value($szKey, $bPrint = false) {
    	global $post;
    	$szValue = get_post_meta($post->ID, $szKey, true);
    	if ( $bPrint == false ) return $szValue; else echo $szValue;
    }

    Inside the plugin, I added this code..

    if ( function_exists('get_custom_field_value') ){
       $custom_field = get_custom_field_value('custom_field_name', false);
    }

    Where custom_field_name is the name of my custom field.

    So, I add a new post, select the custom field and give it a value, add it. Publish the post.

    The value never gets assigned to $custom_field.

    I've searched the web and all posts seem to lead back to using this method. I just can't get it to work

    Where am I going wrong here?

    Thanks!!

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    Works just fine for me using the WordPress Default theme's index.php if the code is placed before the endwhile statement (meaning inside The Loop).

  3. phpwannabe
    Member
    Posted 2 years ago #

    Thanks for your response.

    Isn't this code supposed to work outside the loop? I'm trying to assign the value of a custom field to a variable inside a plugin.

    $custom_field = get_custom_field_value('custom_field_name', false);

    If I manually assign a constant to $custom_field everything works fine with the constant but the above code always returns a null string.

    Does my does my code and logic seem sound?

  4. MichaelH
    Volunteer
    Posted 2 years ago #

    Isn't this code supposed to work outside the loop?

    No--because you are using $szValue = get_post_meta($post->ID, $szKey, true); and $post->ID would be set in the loop.

    Otherwise you'll need to pass the post ID in your arguments.

Topic Closed

This topic has been closed to new replies.

About this Topic