【问题标题】:Notice: Undefined variable: post in C:\wamp\www\moderna\wp-content\themes\moderna\inc\shortcodes.php on line 48注意:未定义的变量:发布在 C:\wamp\www\moderna\wp-content\themes\moderna\inc\shortcodes.php 的第 48 行
【发布时间】:2015-01-17 16:58:20
【问题描述】:
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-&gt;ID -> $idd-&gt;ID ?
  • 最后一行真的是第 48 行吗?到目前为止,您尝试过什么?
  • 题目中包含一个问题,而问题正文中没有其他解释性信息,往往会被关闭。
  • 您的帖子中只有 41 行代码,但问题出在第 48 行...您需要向我们展示第 48 行附近的代码...

标签: php wordpress shortcode


【解决方案1】:

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

$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-&gt;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() 将在循环中处理当前帖子。因此,您不需要传递任何 ID。

【讨论】:

  • 你怎么知道 OP 甚至在任何地方定义了$post?!
  • 该代码特定于 WordPress。 $post 已经在全局范围内定义,用户不需要自己做。
  • 嗨,内森·道森,非常感谢。
猜你喜欢
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-04-03
  • 2016-10-09
  • 2016-07-07
  • 2012-06-26
  • 2014-05-29
  • 2015-07-12
相关资源
最近更新 更多