gpt4 book ai didi

php - WordPress 自定义简码和循环抛出奇怪的结果

转载 作者:搜寻专家 更新时间:2023-10-31 21:04:38 25 4
gpt4 key购买 nike

问题

当我运行此代码时,它会输出特定类别中的所有帖子,每个帖子都在 <li> 中标签。出于某种原因,最后一项也有我不想要的帖子缩略图。

函数.php

我创建了一个自定义短代码来显示特定类别中的所有帖子:

function getPostbyCategory($atts) {

extract(shortcode_atts(array(
"slug" => 'tutorials'
), $atts));

global $post;

$args = array(
'category_name' => $slug,
'posts_per_page' => 2000,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$buildOuput = "<ul>";
$posts_array = get_posts( $args );
foreach ( $posts_array as $post ) {
$buildOuput .= "<li><a href=".get_the_permalink($post->ID).">".get_the_title()."</a></li>";

}
$buildOuput .= "</ul>";

return $buildOuput;

wp_reset_postdata();

}
add_shortcode("specificcategoryposts","getPostbyCategory");

邮报

这是帖子中的所有内容:

<div class="row">
<div class="two-thirds column">
<h2>Category</h2>
<p>Lorem Ipsum Dolor Sit Amet</p>
[specificcategoryposts slug="tutorials"]
</div>

<div class="one-third column ">
<img src="example.com/title-img.png" alt="Title Image" />
</div>
</div>

输出

<div class="row">
<div class="two-thirds column">
<h2>Category</h2>
<p>Lorem Ipsum Dolor Sit Amet</p>
<ul>
<li><a href="#link1">postTitle1</a></li>
<li><a href="#link2">postTitle2</a></li>
</ul>
</div>

<div class="one-third column">
<img src="example.com/title-img.png" alt="Title Image" />
</div>
</div>

// Then it outputs this, outside of everything:
<div class="one-third column">
<img width="738" height="492" src="http://example.com/featured-image.png" class="hide-mobile wp-post-image" alt="iOS Development Swift Tutorial">
</div>

关于这里到底发生了什么的任何想法。

最佳答案

不确定它会如何影响结果,但返回语句在 wp_reset_postdata 之前。请参阅下面的更正。

函数引用,https://codex.wordpress.org/Function_Reference/wp_reset_postdata

function getPostbyCategory($atts) {

extract(shortcode_atts(array(
"slug" => 'tutorials'
), $atts));

global $post;

$args = array(
'category_name' => $slug,
'posts_per_page' => 2000,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$buildOuput = "<ul>";
$posts_array = get_posts( $args );
foreach ( $posts_array as $post ) {
$buildOuput .= "<li><a href=".get_the_permalink($post->ID).">".get_the_title()."</a></li>";
}
$buildOuput .= "</ul>";

wp_reset_postdata(); // this line was previously beneath the return statement
return $buildOuput;
}
add_shortcode("specificcategoryposts","getPostbyCategory");

关于php - WordPress 自定义简码和循环抛出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com