• Resolved JM

    (@viscodesign)


    I’m trying to get the featured image and page title, for a specific array of IDs, from outside the loop. After tinkering a bit I’ve got as far as displaying the thumbnail, but I can’t figure out how to grab the title too. At the moment the <h2> is just empty.

    Here’s my code:

    <?php
    	$page_id = array('17', '15', '19', '13'); //stores multiple page ID in an array
    	//render image for each page using foreach conditional loop
    	foreach($page_id as $id){
    		if (has_post_thumbnail($id) ):
    		$image = wp_get_attachment_image_src( get_post_thumbnail_id($id, 'thumbnail') );
    		endif; ?>
    		<div class="teaser-box">
    			<h2><a href="<?php echo the_title( $id ); ?>"></a></h2>
    			<?php echo "<img src='".$image[0]."'>"; ?>
    		</div>
    <?php } ?>

    I tried searching, but I’m not that great with PHP so not even sure of what I’m searching for. Any help much appreciated! Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • I think you want to use get_the_title() when echoing.

    http://codex.ww.wp.xz.cn/Function_Reference/get_the_title

    Thread Starter JM

    (@viscodesign)

    Thanks acrane, that’s what I needed alright.

    But I’m an idiot … I had the code in the wrong place all along. The echo statement was in the href, that’s why the <h2> was empty all this time. Embarrassing 🙂

    Anyway, for anyone else looking for the same thing, here’s the final code that displays an array of page thumbnails and titles outside of the loop:

    <?php
    	$page_id = array('17', '15', '19', '13'); //stores multiple page ID in an array
    	//render image for each page using foreach conditional loop
    	foreach($page_id as $id){
    		if (has_post_thumbnail($id) ):
    		$image = wp_get_attachment_image_src( get_post_thumbnail_id($id, 'thumbnail') );
    		endif; ?>
    		<div class="teaser-box">
    			<h2><a href="<?php echo get_permalink($id); ?>" rel="bookmark"><?php echo get_the_title($id); ?></a></h2>
    			<?php echo "<img src='".$image[0]."'>"; ?>
    		</div>
    <?php } ?>
Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Page title and thumbnail outside loop’ is closed to new replies.