Support

Account

Home Forums General Issues the_field not working in a template

Solved

the_field not working in a template

  • I have a template file with the following code.

    <?php {
    $recentposts=get_posts('showposts=3&category=<?php the_field(artist_news); ?>');
    if ($recentposts) {
    foreach($recentposts as $post) {
    setup_postdata($post);
    ?>

    The custom field named ‘artist_news” should return an id in a numerical form (for example ’22’). This is not working though. Any ideas why I can’t place the php field call in my code like this? The end result should be like this…

    <?php {
    $recentposts=get_posts('showposts=3&category=22');
    if ($recentposts) {
    foreach($recentposts as $post) {
    setup_postdata($post);
    ?>

    How would I get my custom field value to render in my code?

    • Will

    • January 9, 2014 at 7:47 am

    Try this:

    <?php
    $cat = get_the_field('artist_news');
    $recentposts=get_posts('showposts=3&category=$cat');
    ?>

    Not exactly sure how WordPress functions handle variables inside of strings like that so you might need to do this:

    <?php
    $cat = get_the_field('artist_news');
    $recentposts=get_posts('showposts=3&category=' . $cat);
    ?>
  • So does this repalce ALL of my above code or do I integrate it somehow with mine?

    When I replace it with your code I get an error…

    fatal error: Call to undefined function get_the_field()

    • Will

    • January 9, 2014 at 10:17 am

    Sorry about that. I’m drunk. It’s get_field, not get_the_field.

    <?php
    $cat = get_field('artist_news');
    $recentposts=get_posts('showposts=3&category=$cat');
    
    if ($recentposts) {
    ... rest of your code
    ?>
  • We have a winner! thanks very much for the help. Final working code here for those in the future…

    <?php
    $cat = get_field(‘artist_news’);
    $recentposts=get_posts(‘showposts=3&category=’ . $cat);
    if ($recentposts) {
    foreach($recentposts as $post) {
    setup_postdata($post);
    ?>

Viewing 5 posts - 1 through 5 (of 5 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.