我正在使用 has_post_thumbnail()
检查博客文章中是否有缩略图,如果没有缩略图,则调用 JavaScript 脚本函数来更改 .blog- 的布局post
到 display
,从 flex
到 block
。
为此:我正在使用带有条件语句的 JavaScript 函数。如下所示:
content.php
<div class="blog-post">
<?php /* POST FEATURED THUMBNAIL*/
if(has_post_thumbnail()) { ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('feature-image'); ?></a>
</div>
<?php } else { ?>
<script type="text/javascript"> alert("asdsas"); xfullWidthPostWithThumbnail(); </script>
<?php } ?>
<article class="post-article para-text">
<p id="blog-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<p id="blog-info-text"><?php the_time('F jS, Y'); ?> | By <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>"><?php the_author();?></a> | Posted In
<?php
$categories = get_the_category();
$seperator = ", ";
$output = '';
if($categories) {
foreach ($categories as $category) {
$output .= '<a href="'. get_category_link($category->term_id) .'">' . $category->cat_name . '</a>' . $seperator;
}
echo trim($output, $seperator);
}
?></p>
<p><?php echo get_the_excerpt(); ?> <a href="<?php the_permalink(); ?>"> Read more »</a></p>
<p></p>
</article>
</div>
JavaScript函数
/* INDEX PAGE -- ADD DISPLAY BLOCK FOR FULL WIDTH OF POST EXCERPT IF NOT POST THUMBNAIL */
function xfullWidthPostWithThumbnail() {
alert("hhhhhhhhhhhhhhhh");
jQuery(".blog-post").css("display","block !important");
jQuery(".blog-post").css("color","red !important");
}
问题:目前我遇到的错误:
Uncaught ReferenceError: xfullWidthPostWithThumbnail is not defined at (index):155
为什么函数没有定义?有什么想法吗??
最佳答案
无需使用 Javascript 来执行此操作 - 它会在客户端添加不必要的处理。
您要做的就是更改 .blog-post
的 CSS,因此创建一个单独的 CSS 类,如果没有缩略图则应用它。
- 为您要应用的规则创建一个新的 CSS 类
- 检查缩略图是否存在。
- 如果没有,请将新类添加到 div
- 如果是,则正常显示
CSS:
创建一个名为 no_thumbnail
的类来添加您的样式。仅供引用,您应该避免使用 !important
。
.blog-post.no_thumbnail{
display: block !important;
color: red !important;
}
PHP:
/* declare a variable for your extra class */
$blogpostclass = "";
/* If thumbnail doesn't exist, add your 'no_thumbnail' class */
if(!has_post_thumbnail()) $blogpostclass = "no_thumbnail"; ?>
/* add the class variable to your blog-post div */
<div class="blog-post <?php echo $blogpostclass; ?>">
/* If there is a thumbnail, add it as usual */
<?php
if(has_post_thumbnail()) { ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('feature-image'); ?></a>
</div>
<?php } ?>
[...]
</div>
关于javascript - 尝试在 PHP 中调用 jQuery - 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379135/