注意:未定义变量:post in C:\wamp\www\moderna\wp-content\themes\moderna\inc\shortcodes.php on line 48

Notice: Undefined variable: post in C:\wamp\www\moderna\wp-content\themes\moderna\inc\shortcodes.php on line 48

function portfolio_shortcode($atts, $content = null){
    extract( shortcode_atts( array(
        'type' => 'post',
    ), $atts ) );

     $q = new WP_Query(
        array('posts_per_page' => 5, 'post_type' => 'portfolio')
        );              

    $list = '<div class="row">
                <section id="projects">
                    <ul id="thumbs" class="portfolio">';
    while($q->have_posts()) : $q->the_post();
        $idd = get_the_ID();

        $portfolio_large = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'portfolio-large' );
        $portfolio_thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'portfolio-image' );

        $list .= '

                    <!-- Item Project and Filter Name -->
                <li class="col-lg-3 design" data-id="id-0" data-type="web">
                <div class="item-thumbs">
                <!-- Fancybox - Gallery Enabled - Title - Full Image -->
                <a class="hover-wrap fancybox" data-fancybox-group="gallery" title="'.get_the_title().'" href="'.$portfolio_large[0].'">
                <span class="overlay-img"></span>
                <span class="overlay-img-thumb font-icon-plus"></span>
                </a>
                <img src="'.$portfolio_thumb[0].'" alt="'.get_the_title().'" />

                </div>
                </li>

        ';  

    endwhile;
    $list.= '</ul></section></div>';
    wp_reset_query();
    return $list;
}
add_shortcode('portfolio', 'portfolio_shortcode'); 

您在尝试使用 post 全局变量之前没有包含它。导致问题的行是:

$portfolio_large = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'portfolio-large' );
$portfolio_thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'portfolio-image' );

这个特定错误有两种解决方案。

1)

global $post; 添加到函数的顶部。例如

function portfolio_shortcode( $atts, $content = null ) {
    global $post;
    ...

2)

您已经获得了 $idd = get_the_ID(); 的 ID。使用它而不是 $post->ID。例如

$portfolio_large = wp_get_attachment_image_src( get_post_thumbnail_id( $idd ), 'portfolio-large' );
$portfolio_thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $idd ), 'portfolio-image' );

我在最后提到了第三种选择,因为如果您将来 运行 遇到类似的问题,它对您没有帮助。 get_post_thumbnail_id() 将作用于循环中的当前 post。因此,您无需传入任何 ID。