Support

Account

Home Forums General Issues How to pass variable to the_field?

Solving

How to pass variable to the_field?

  • Hi,

    Basically, I want to do this:

    the_field(the_field('field_name');

    In reality, I’m trying it like this:

    $variable = the_field('field_name'); 
    the_field($variable);

    The reason:

    I’ve created a CPT with about 20 custom fields. I want to pull the value of a single field across every post onto a new CPT post. Easy practical example:

    What I have (by way of example):

    iPhone 5 (‘mobile’ custom post type)

    • CPU (custom field)
    • Resolution (custom field)

      iPhone 6 (‘mobile’ custom post type)

    • CPU (custom field)
    • Resolution (custom field)

    What I want to do:

    CPU (‘mobile’ custom post type and page template)

    • iPhone 5
    • iPhone 6

    And using the same custom field values.

    I created a custom field (‘argument’) for the latter post, in which I specify the name of the field as an argument I want to push to the_field in the page template.

  • First the_field() is only used to display fields. To use the value of the field somewhere else you need to use get_field()

    You also need the post ID of the post where that other field appears. Basically, what you need is a post object field that returns the ID and the field name you want to put from that page.

    Then, in long form

    
    // get the field and post ID from this post
    $field_name = get_field('field name of field containing field name');
    $post_id = get_field('field name of post object field that has the above field');
    
    // show the value from that other post
    the_field($field_name, $post_id);
    
  • Thanks for this, John.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.