2013-08-31 69 views
0

使用以下代碼我可以打印標題,帖子日期。現在我想從我的帖子內容中獲得第一張照片,我怎樣才能解決這個問題。我也嘗試過the_date(),the_title()來顯示日期和時間,但是徒勞無功。先謝謝了。從wordpress帖子獲得第一張圖片

$args = array('posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'date'); 
$postslist = get_posts($args); 


$postcound=0; 
foreach ($postslist as $post) { 
echo "date".$postslist[$postcound]->post_date; 
echo "<br />title:".$postslist[$postcound]->post_title; 
    echo "<br />content:".$postslist[$postcound]->post_content; 



echo "<br />id:". $postslist[$postcound]->ID; 
$postcound++; 
} 
?> 
+0

你的意思是,在post_content中獲得第一個「 NoBugs

回答

0

你可以試試這個代碼

<?php if (have_posts()) : ?> 
<?php while (have_posts()) : the_post(); ?> 

<?php 
$szPostContent = $post->post_content; 
$szSearchPattern = '~<img [^\>]*\ />~'; 

// Run preg_match_all to grab all the images and save the results in $aPics 
preg_match_all($szSearchPattern, $szPostContent, $aPics); 

// Check to see if we have at least 1 image 
$iNumberOfPics = count($aPics[0]); 

if ($iNumberOfPics > 0) { 
    // Now here you would do whatever you need to do with the images 
    // For this example the images are just displayed 
    for ($i=0; $i < $iNumberOfPics ; $i++) { 
     echo $aPics[0][$i]; 
    }; 
}; 

endwhile; 
endif; 
?> 
0

這裏是演示代碼,來WordPres後的第一個圖像:

// Get first image 
function get_first_image() { 
global $post, $posts; 
$first_image = ''; 
ob_start(); 
ob_end_clean(); 
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
$first_image = $matches [1] [0]; 
if(empty($first_image)){ //Defines a default image 
// Set the default image if there are no image available inside post content 
$first_image = "/img/default.jpg"; 
} 
return $first_image; 
} 
// End Get First Image 

要顯示使用後的第一個圖像循環內的以下代碼:

<?php echo get_first_image(); ?> 

來源:Get first image of WordPress post and set it as featured image

相關問題