WordPress:functions.php 中的 WP_Query 返回空查询(对于自定义短代码)

发布于 2024-12-19 07:34:26 字数 1117 浏览 3 评论 0原文

我正在为子主题编写一个自定义短代码,我已将其放入子主题functions.php中。这是代码:

function get_featured_video(){
$video_query = new WP_Query('category_name=videos&order=ASC');
$videoPath = "/";
$videoText =  "";
while ($video_query->have_posts()){
    $video_query->the_post();
    $featured = get_post_meta($post->ID, "vid_feature", $single = true);
    if(strtolower($featured)=='yes'){
        $videoPath = get_permalink($post->ID);
        $content = strip_tags($post->post_content);
        $contentArr = str_word_count($content,1);
        if(count($contentArr>50)){
            $videoText = join(" ",array_slice($contentArr,0,50));
            $videoText .= " <a href='$link'>&lt;read more&gt;</a>";
        } else {
            $videoText = $content;
        }
        break;
    }
}
$returnStr = "<h1><a href='$videoPath'>You've Got to See This!</a></h1>\n";
$returnStr .= $videoText;
return $returnStr;
}

add_shortcode('getfeaturedvideo','get_featured_video');

我遇到的问题是它返回一个空白查询。我知道视频类别中有一个帖子。我从未在functions.php中使用过WP_Query。我需要使用其他方法吗?

I'm writing a custom shortcode for a childtheme that I've dropped into my child themes functions.php. Here's the code:

function get_featured_video(){
$video_query = new WP_Query('category_name=videos&order=ASC');
$videoPath = "/";
$videoText =  "";
while ($video_query->have_posts()){
    $video_query->the_post();
    $featured = get_post_meta($post->ID, "vid_feature", $single = true);
    if(strtolower($featured)=='yes'){
        $videoPath = get_permalink($post->ID);
        $content = strip_tags($post->post_content);
        $contentArr = str_word_count($content,1);
        if(count($contentArr>50)){
            $videoText = join(" ",array_slice($contentArr,0,50));
            $videoText .= " <a href='$link'><read more></a>";
        } else {
            $videoText = $content;
        }
        break;
    }
}
$returnStr = "<h1><a href='$videoPath'>You've Got to See This!</a></h1>\n";
$returnStr .= $videoText;
return $returnStr;
}

add_shortcode('getfeaturedvideo','get_featured_video');

The problem I'm having is that it's returning a blank query. I know there's a post in the videos category. I've never used the WP_Query inside functions.php. Is there a different method I need to use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开半夏魅人心 2024-12-26 07:34:26

在函数的顶部尝试声明:

global $post;

At the top of the function try declaring:

global $post;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文