2013-08-31 4 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

Вы имеете в виду регулярное выражение для получения первого ' 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