wordpress搜索结果带图代码
时间 : 2024-03-21 14:08:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

要将WordPress搜索结果中的文章标题和摘要添加图像,可以使用以下代码示例:

```php

<?php

// 获取搜索结果

$search_results = get_search_results();

if ($search_results) {

foreach ($search_results as $result) {

// 获取文章的标题、摘要和特色图像

$post_title = $result->post_title;

$post_excerpt = $result->post_excerpt;

$post_image = get_the_post_thumbnail_url($result->ID, 'large');

// 显示文章标题和摘要

echo '<h2>' . $post_title . '</h2>';

echo '<p>' . $post_excerpt . '

';

// 显示特色图像

if ($post_image) {

echo '<img src="' . $post_image . '" alt="' . $post_title . '">';

}

}

}

?>

在这个代码示例中,首先获取搜索结果并循环遍历每个结果。然后获取文章的标题、摘要和特色图像,并显示在页面中。如果文章有特色图像,也将对应的图像显示出来。你可以将这段代码添加到WordPress主题的搜索结果模板文件中,以显示带图像的搜索结果。

其他答案

以下是一个简单的 WordPress 搜索结果页面模板,带有图片展示的代码示例:

```php

<?php

// 获取搜索关键词

$search_query = get_search_query();

// 查询符合搜索条件的文章

$posts = new WP_Query(array(

's' => $search_query,

'post_type' => 'post',

));

// 循环显示搜索结果

if ($posts->have_posts()) :

while ($posts->have_posts()) : $posts->the_post();

?>

<div class="search-result">

<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php

if (has_post_thumbnail()) {

the_post_thumbnail('medium'); // 显示文章特色图片

}

?>

<p><?php the_excerpt(); ?>

</div>

<?php

endwhile;

else :

?>

<div class="search-result">

<p>抱歉,没有找到符合搜索条件的结果。

</div>

<?php

endif;

// 重置查询

wp_reset_postdata();

?>

将以上代码放入你的 WordPress 主题的搜索页面模板文件(通常是 `search.php`)中即可。这段代码将搜索结果显示为带有标题、特色图片和摘要的形式。你也可以根据需要自行调整样式和布局。