代码之家  ›  专栏  ›  技术社区  ›  Geoff_S

从wordpress页面编辑器调用简码函数

  •  0
  • Geoff_S  · 技术社区  · 4 年前

    从wordpress页面编辑器调用短代码时遇到问题,即使我可以从php主题文件调用短代码也没有问题

    我在functions.php文件中有这个:

    function new_loop() {
    
        $args = array(
            'post_type' => 'discounts',
            'post_status' => 'publish',
        );
    
        $my_query = null;
        $my_query = new WP_query($args);
        $string = "<div class='container'>";
        $string .= "<div class='row'>";
        if($my_query->have_posts()):
            while($my_query->have_posts()) : $my_query->the_post();
                $custom = get_post_custom( get_the_ID() );
                $thumbnail = get_the_post_thumbnail_url($post->ID(), 'full');
    
                $string .= "<div class='col-md-4 my-2'>" . " <div class='discount-container shadow' style='background: url(". $thumbnail . "); background-size:cover; background-position:center;'>  ". "<div class='discount-content'>" . "<p class='discount-title font-weight-bold'>" .get_the_title(). "</p>" . "<div class='discount-desc' id='discount-description'>" . get_the_content() ."</div>" . "<a class='discount-link' href=". get_the_permalink() .">" . "Open in new tab" . "</a>" ."</div>" ."</div>" . "</div>" ;
            endwhile;
    
        $string .= "</div>";
          $string .= "</div>";
          return $string;
            wp_reset_postdata();
        else :
        _e( 'Sorry, no posts matched your criteria.' );
        endif;
    }
    add_shortcode( 'calling_loop', 'new_loop' );
    

    如果我这样做,那么效果很好。但是在一个wordpress编辑器页面中,我只有[calling_loop],它不起作用,我收到一个通知,我的回调是错误的,因为它找不到变量$post

    我如何通过在页面编辑器中调用短代码片段来正确地完成这项工作?

    0 回复  |  直到 4 年前
        1
  •  0
  •   ZealousWeb    4 年前

    在你的代码中,你使用了$post,而$post没有定义。

    因此,这个解决方案有两种选择。

    1. 您可以使用 $my_query->ID 而不是 $post->ID
    2. 您可以使用 get_the_ID() 而不是 $post->身份证件

    根据我的建议,我想 建议第一种选择 .

    在这里,我还分享了WordPress的一些提示,你需要在你的功能中注意这些提示。

    =>根据WordPress标准,如果你想在编辑器中使用短代码,请使用 the_content() 功能而不是 get_the_content() .

    推荐文章