【问题标题】:Calling shortcode function from wordpress page editor从 wordpress 页面编辑器调用简码函数
【发布时间】:2021-04-29 20:23:01
【问题描述】:

从 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' );

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

如何通过在页面编辑器中调用简码 sn-p 来正确完成这项工作?

【问题讨论】:

  • 在函数的顶部,尝试将$post = get_post();
  • 不幸的是,我没有得到它,但我能够使用 get_the_ID() 并从那里弄清楚。谢谢@

标签: php wordpress


【解决方案1】:

在您的代码中,您使用了 $post 并且未定义 $post。

所以,这个解决方案有两种选择。

  1. 您可以使用$my_query-&gt;ID 而不是$post-&gt;ID
  2. 您可以使用get_the_ID() 而不是$post-&gt;ID

根据我的建议,我想建议第一个选项。

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

=>根据 WordPress 标准,如果您想在编辑器中使用短代码,请使用 the_content() 函数而不是 get_the_content()。

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2011-02-02
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多