Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Echo or Print custom field into PHP function WordPress

  • SOLVED

<strong>I need to Print or Echo this:</strong>

<img src="<?php echo get_post_meta($post->ID, 'cf_image', true);?>" width="100" height="100" />

<strong>Into this function.php function</strong>

function content1($pageid) {
$my_query = new WP_Query("showposts=1&post_type=page&page_id=".$pageid);
while ($my_query->have_posts()) :
$my_query->the_post();
$do_not_duplicate = $post->ID;
the_content('');
<img src="HERE">
endwhile;
}


<em>Any suggestions would be much appreciated!</em>

Answers (3)

2011-09-02

Kailey Lampert answers:

How about this?

function content1($pageid) {

$my_query = new WP_Query("showposts=1&post_type=page&page_id=".$pageid);

while ($my_query->have_posts()) :

$my_query->the_post();

$do_not_duplicate = $post->ID;

the_content('');

echo '<img src="'. get_post_meta( get_the_ID(), 'cf_image', true) .'" width="100" height="100" />';

endwhile;

}


West Coast Design Co. comments:

Thanks Kailey, <strong>you rock</strong> as always.

<em>Have a wicked weekend!</em>

2011-09-02

Zack Tollman answers:

Another option would be to gather all of the output and return it in the function. You can then simply call the function and echo out the output of the function wherever you want to:

function content1($pageid) {
// Make the query
$my_query = new WP_Query("showposts=1&post_type=page&page_id=".$pageid);

// Begin the loop
while ($my_query->have_posts()){
$my_query->the_post();
global $post;
$do_not_duplicate = $post->ID;

// Get the content
$content = $post->post_content;

// Get the image
$content .= '<img src="' . get_post_meta($post->ID, 'cf_image', true) . '" width="100" height="100" />';
}

return $content;
}

// Echo the content of the function
echo content1($pageid);

2011-09-02

Jeff Rose answers:

No empty image tags. You might want to consider doing esc_attr on $the_img too if you're not sure where it came from.


function content1($pageid) {
$my_query = new WP_Query("showposts=1&post_type=page&page_id=".$pageid);
while ($my_query->have_posts()) :
$my_query->the_post();
$do_not_duplicate = $post->ID;
the_content('');

$the_img = get_post_meta( get_the_ID(), 'cf_image', true);

if ( !empty( $the_img ) ){
echo '<img src="'. $the_img .'" width="100" height="100" />';
}
endwhile;
}