WordPress.org

Ready to get started?Download WordPress

Forums

PHP code widget plugin - need code - please help (5 posts)

  1. ehteshamuddin.syed
    Member
    Posted 1 year ago #

    Hello folks,

    I need to add custom widget to display tech specs related to post so the widget will display different spec for different post, i was suggested to use php code plugin and create custom fields, I have added the plugin but i need peice of code get it working, can any body please post the php code that would fix the problem.

    Thank you

  2. aritzalvarez
    Member
    Posted 1 year ago #

    To get a custom field, the code is

    $custom_field_value = get_post_meta($post->ID, 'custom_field_name', true);

    It will save the value stored in your custom field on to $custom_field_value, then you can display, like this:

    echo $custom_field_value;

    There is a very simple method, but are a lot of ways more, take a look on codex: custom fields it can really help you.

  3. ehteshamuddin.syed
    Member
    Posted 1 year ago #

    Thank you for reply aritzalvarez

    I pasted the following code in the PHP code widget on the side bar and set the custom field title same as post ID, but nothing shows up on sidebar on post apart from just the title. could you please assist if there is some thing missing in code or i'm doing some thing wrong.

    <?php
    $custom_field_value = get_post_meta($post->ID, 'custom_field_name',true);
    echo $custom_field_value;
    ?>

  4. aritzalvarez
    Member
    Posted 1 year ago #

    same post ID?

    So... I guess you meant same custom field name; the $post-ID isn't to edit, it's to know what post is being read....

    Ok, to it works you need have it inside the loop. If your theme hace it outside the loop it will not work...

    <?php
    	if ( have_posts() ) { while ( have_posts() ) { the_post(); 
    
                  // HERE YOU CAN USE IT
    
    		} // end while
    	} // end if
    ?>

    A way to fix it is use

    <?php
    $custom_field_value = get_post_meta($post->ID, 'custom_field_name',true);
    ?>

    Inside of the loop and, then, use storage value and

    echo $custom_field_value;

    In the sidebar... But only will work if your sidebar is after the loop....

    Ypu can try add a secondary loop in the sidebar, but it's a pretty messy way to do it

    I will try to use it in the loop, where the content is shown, to see if everything is ok

  5. ehteshamuddin.syed
    Member
    Posted 1 year ago #

    Thank you for the update aritzalvarez, really appreciate your effort

    I'm fairly new to WordPress and PHP, i'm having difficulty in understanding where to place the above code. should i add the first part of code to funtions.php or put the code in the php code widget side bar ?

Topic Closed

This topic has been closed to new replies.

About this Topic