简体   繁体   中英

Can I use a variable as an argument in get_the_ID()?

Note: I am still a beginner in both PHP and WordPress so apologies if I'm way off.

I am trying to echo the custom field value from the latest post from the 'video' post format, but for some reason, $video_url is outputting an empty string. I'm thinking it has to do with this line below:

$video_url = htmlspecialchars(get_post_meta(get_the_ID($latest_video_id), 'dt_video', true));

I'm not sure if I'm allowed to use a variable as an argument in get_the_ID() .

Here is the full code:

<?php   
    $args = array( 
        'numberposts' => '1', 
        'tax_query' => array(
            array(
                'taxonomy' => 'post_format',
                'field' => 'slug',
                'terms' => 'post-format-video'
            )
        ),
        'meta_query' => array(
            array(
                'key' => 'dt_video',
                'value' => '',
                'compare' => '!='
            )
        )
    );
    $latest_video = wp_get_recent_posts($args); // Get latest video in 'video' post format
    $latest_video_id = $latest_video['0']['ID']; // Get latest video ID
    $video_url = htmlspecialchars(get_post_meta(get_the_ID($latest_video_id), 'dt_video', true));
    echo '<iframe width="180" height="101" src="'.$video_url.'?rel=0" frameborder="0" allowfullscreen></iframe>';
?>

Hi get_the_ID() returns the id of the current post when you are inside the loop. does not accept any parameter.

You allready have the id of the video post in the var $latest_video_id, so you can simply do

$video_url = htmlspecialchars(get_post_meta($latest_video_id, 'dt_video', true));

good luck.

You are always able to use an argument as long as it returns something. You should be receiving some type of error if it's not working.

Example:

function getId()
{
  return 1;
}
function showId($id)
{
  return $id;
}
echo showId(getId());

Result: 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM