Php 编写WordPress函数时出错

Php 编写WordPress函数时出错,php,wordpress,function,responsive-design,Php,Wordpress,Function,Responsive Design,因此,我试图在WordPress中编写一个自定义函数,用picturefill和srcset显示特色图像,以显示不同大小的专长img。我没有太多的主题,但没有太多的写作功能 add_theme_support( 'post-thumbnails' ); 在myfunctions.php中启用。我还需要一个包含我的代码的文件: function responsive_featured_img() { if ( function_exists('has_post_thumbnail') &

因此,我试图在WordPress中编写一个自定义函数,用picturefill和srcset显示特色图像,以显示不同大小的
专长img
。我没有太多的主题,但没有太多的写作功能

add_theme_support( 'post-thumbnails' );
在my
functions.php
中启用。我还需要一个包含我的代码的文件:

function responsive_featured_img() {

if ( function_exists('has_post_thumbnail') && has_post_thumbnail($post->ID) ) {
    $feat_small = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' );
    $feat_med = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' );
    $feat_large = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large' ); ?>


<img src="<?php echo $feat_small[0]; ?>"
    srcset="<?php echo $feat_large[0]; ?> 1024w, <?php echo $feat_med[0]; ?> 400w, <?php echo $feat_small[0]; ?> 320w"
    sizes="100vw"
    alt="<?php the_title(); ?>" 
/> 

<?php } } ?>
任何想法都会很棒

更新: 从Howlin输入后,此代码无错误运行。我相信它可能会被重新考虑:

function responsive_featured_img() {
global $post;
if ( function_exists('has_post_thumbnail') && has_post_thumbnail($post->ID) ) {
    $feat_small = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' );
    $feat_med = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' );
    $feat_large = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large' ); ?>


<img src="<?php echo $feat_small[0]; ?>"
    srcset="<?php echo $feat_large[0]; ?> 1024w, <?php echo $feat_med[0]; ?> 400w, <?php echo $feat_small[0]; ?> 320w"
    sizes="100vw"
    alt="<?php echo get_the_title($post->ID); ?>" 
/> 
功能响应\u特色\u img(){
全球$员额;
if(函数存在('has_post_缩略图')&has_post_缩略图($post->ID)){
$feat_small=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'small');
$feat_med=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'medium');
$feat_large=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'large');?>
"
srcset=“1024w、400w、320w”
尺寸=“100vw”
alt=“”
/> 
尝试更改:

alt="<?php the_title(); ?>" 
alt=“”

alt=“”
当您尝试在外部使用类似
the_title()


编辑:在if语句之前添加
global$post;
将修复错误。您正在调用
$post->ID
,但由于该函数在循环之外,因此引发了错误。

Hmmm,这可能更合适,但没有消除任何错误。该函数仍在工作!干杯第13/1行到底是什么4和15?13:$feat_small=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'small');14:$feat_med=wp_get_attachment_image_src(get_post_缩略图_id($post->id),'middle');15:$feat_large=wp_get_attachment_image_图像_src(get_post_缩略图_id($post->id),'large')?>我不明白为什么会出现这些错误?我以为我在这个例子中定义了这些变量?如果您尝试在If语句之前添加
global$post;
,这会有什么不同吗?
alt="<?php the_title(); ?>" 
alt="<?php echo get_the_title($post->ID); ?>"