在Wordpress中获取帖子的图像
我想在wordpress中制作一个幻灯片放映,我为它制作了一个类别,现在我想为我的幻灯片放映获取该类别的图像。以下是我的部分代码:在Wordpress中获取帖子的图像,wordpress,wordpress-theming,Wordpress,Wordpress Theming,我想在wordpress中制作一个幻灯片放映,我为它制作了一个类别,现在我想为我的幻灯片放映获取该类别的图像。以下是我的部分代码: <div id="slide-show"> <ul> <?php query_posts('cat=1'); while(have_posts()): the_post();?> <li> <a href="<?php the_permalink
<div id="slide-show">
<ul>
<?php query_posts('cat=1'); while(have_posts()): the_post();?>
<li>
<a href="<?php the_permalink();?>">
<img src="<?php
$image=wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail');
echo $image[0];?>" alt="<?php the_title();?>" /></a>
</li>
<?php endwhile; wp_reset_query();?>
</ul>
</div>
但它不起作用。有人能帮我吗?首先,我会:
首先,不要使用查询帖子。
请核对:
在这种情况下,我建议构建一个函数来创建所需的输出。您可以将其放在theme functions.php文件中。把它放在文件的末尾。
如果有?>作为PHP文件的最后一件事,请将其删除,这是不必要的,如果文件后面有任何空白,则可能会破坏您的网站
也就是说,我们的函数将精确地打印您想要的Html,在任何主题模板文件index.php、single.php、page.php等中都会这样调用它
数字4是类别ID
这就是函数,检查代码中的注释:
function get_gallery( $id )
{
// Simple query
$posts = get_posts( array(
'category' => $id,
'post_status' => 'publish',
'post_type' => 'post',
) );
// Start building the Html code
$slide_show = '
<div id="slide-show">
<ul>';
// Iterate through the results
foreach ( $posts as $post )
{
// Assign value and test if it exists at the *same time*
if( $thumb = get_post_thumbnail_id( $post->ID ) )
{
$permalink = get_permalink( $post->ID );
$image = wp_get_attachment_image_src( $thumb );
// Build the Html elements
$slide_show .= '
<li>
<a href="' . $permalink . '">
<img src="'. $image[0] . '" alt="' . $post->post_title .'" />
</a>
</li>';
}
}
// Finish the Html
$slide_show .= '
</ul>
</div>
';
// Print the Html
echo $slide_show;
}
结果:
什么不起作用?正在分析列表,但src属性为空吗?
function get_gallery( $id )
{
// Simple query
$posts = get_posts( array(
'category' => $id,
'post_status' => 'publish',
'post_type' => 'post',
) );
// Start building the Html code
$slide_show = '
<div id="slide-show">
<ul>';
// Iterate through the results
foreach ( $posts as $post )
{
// Assign value and test if it exists at the *same time*
if( $thumb = get_post_thumbnail_id( $post->ID ) )
{
$permalink = get_permalink( $post->ID );
$image = wp_get_attachment_image_src( $thumb );
// Build the Html elements
$slide_show .= '
<li>
<a href="' . $permalink . '">
<img src="'. $image[0] . '" alt="' . $post->post_title .'" />
</a>
</li>';
}
}
// Finish the Html
$slide_show .= '
</ul>
</div>
';
// Print the Html
echo $slide_show;
}