Support

Account

Home Forums Front-end Issues Insert field at hook-position using function.php

Solving

Insert field at hook-position using function.php

  • Hi acf community,

    I´m struggling with adding a custom field to the position of a hook. I was looking for a solution in the faq and the forum but I couldn´t find a hint how to solve this.

    I created the following code and put it into the functions.php:

    
    add_filter('vpc_container_end', 'add_table', 10, 1);
    
    function add_table( $value ) {
        $value = get_field('testfield');
        return $value;
    };
    

    The hook is part of a product generator plugin, which inserts the content of the products into an existing page.
    Therefore, I can not insert the field directly into the page, but instead use the functions.php/hook.
    I successfully created the field in the backend and attached it to the products of the generator plugin, but the content of the field doesn´t appear at the frontend.

    By changing my code to

    
    function add_table( $value ) {
        $value = 'test';
        echo $value;
    };
    

    the word “test” appears at the frontend in the right position. Using the hook seems to work but I can´t get the content of the custom field.

    Does anybody know what I´m doing wrong? A little help would be very appreciated.

    • James

    • July 14, 2019 at 2:06 am

    Hi There,

    Thanks for the mail.

    Is it possible that your issue is related to the global post ID parameter?

    Kindly try passing the global post ID param as the second parameter to the get_field function and let me know you are able to load the value.

    Hope to hear from you soon.

  • Hi James,

    thanks for your advice. I tried to get the post ID but somehow it didn´t work.
    Now my code looks like this:

    
    // Add acf field to product generator page
    add_filter('vpc_container_end', 'add_table', 10, 1);
    function add_table($value){
        global $post;
        $value .= get_field('testfield', $post->ID);
        return $value;     
    }
    

    For testing I also tried to enter the ID of a specific post:

    
       $value .= get_field('testfield', 17890);
    

    But this doesn´t work either. :-/

    • James

    • July 16, 2019 at 10:12 pm

    Hi there,

    Thanks for sharing these findings.

    It is likely that you are calling the get_field() function before ACF is loaded. You can workaround this by making use of get_post_meta() native function to achieve the same result.
    https://developer.wordpress.org/reference/functions/get_post_meta/

    I hope this info helps.

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

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.