【问题标题】:Wordpress if post has an image I want to display that image if doesn't (do nothing)Wordpress 如果帖子有图像我想显示该图像如果没有(什么都不做)
【发布时间】:2015-10-14 03:10:42
【问题描述】:

在我的 wordpress 主题中,我使用函数在我的 index.php 中显示帖子的第一张图片

对我来说,我不想在我的主题中添加支持缩略图。它太烦人了!

我观看了一个教程,该教程教如何通过为摘录添加一个 padding-left 并将图像浮动到左侧以使图像在左侧和摘录中,从而在帖子摘录的左侧显示图像在图像旁边。此外,本教程还教您如何在帖子没有图片时不执行任何操作(不执行任何操作=不推送摘录并且不向图像添加浮动,以便帖子的格式看起来正常)。

他通过使用函数 if has_post_thumbnail = 做某事(在摘录中添加一个 padding-left 并在右侧浮动图像)并且如果帖子没有 thumbnail = 什么也不做。就是这样。

代码如下:

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

    <article class="post <?php if ( has_post_thumbnail() ) { ?>has-thumbnail <?php } ?>">

        <!-- post-thumbnail -->
        <div class="post-thumbnail">
            <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('small-thumbnail'); ?></a>
        </div><!-- /post-thumbnail -->



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

        <p class="post-info"><?php the_time('F j, Y g:i a'); ?> | by <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>">

现在我想做同样的事情,但我不想在我的主题中添加对缩略图的支持,而且我不打算支持缩略图。

我尝试将 has_post_thumbnail() 替换为我使用的 get post first image 函数,但没有成功。

我真的需要在我的网站上这样做。那请问各位大侠有什么解决办法吗?

【问题讨论】:

  • 为了避免使用帖子缩略图而进行黑客攻击将比首先启用它们(这涉及在 functions.php 中添加一行)更多的工作

标签: php html css wordpress image


【解决方案1】:

the_post_thumbnail 调用特色图片...这是您应该不想做的事情。

相反,您需要检查图片的帖子内容。这里有答案:https://wordpress.stackexchange.com/questions/60245/get-first-image-in-a-post

【讨论】:

  • 我已经尝试用函数catch_that_image()替换has_post_thumbnail,但没有成功!
  • 感谢您的回复。我已经使用 catch that image 函数自己解决了
【解决方案2】:

使用has_post_thumbnail() 条件函数。见docs

但如果你真的不想使用帖子缩略图(你应该,但你是老板),see this question

【讨论】:

  • 我的主题不支持缩略图。请再次阅读我的问题。
  • 您要求解决方案 - 正确的解决方案是添加帖子缩略图支持。他们正是针对这种情况的。无论如何,如果您仍然不想使用帖子缩略图,请稍后查看我的更新答案。
  • 感谢您的回复。我已经使用 catch that image 函数自己解决了
  • 您知道catch_that_image() 不是标准的WP 功能吗? :)
  • 是的,我知道这一点,有人做了这个很棒的功能。很有帮助
【解决方案3】:

您应该真的考虑使用精选图片。只需在 functions.php 中添加一行即可启用它们...

但是,如果您仍然不想这样做,您可以使用以下方法检查帖子的图片附件:

// Get images attached to the current post
$images = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );

// If there are images
if ( $images ) {
    // Show stuff 
} else {
    // Do nothing
}

【讨论】:

  • 感谢您的回复。我已经使用 catch that image 函数自己解决了
猜你喜欢
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多