我在WordPress上遇到一些问题,无法在另一个页面上显示属于某个帖子的图像。我正在寻找的是一个主页,它列出了某个类别中的所有帖子,并显示标题、摘录和"查看示例"链接。查看示例链接将在灯箱中显示属于帖子的所有图像,但在主页上。
到目前为止,我有这个,但现在我有点卡住了。
<?php query_posts('cat=15&order=DSC'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-md-6">
<div class="pakket-block">
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<span class="read_more"><a href="<?php the_permalink(); ?>" rel="shadowbox">View examples</a></span>
</div> <!-- /.pakket-block -->
</div> <!-- /.col-md-6 -->
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); // reset the query ?>
这是一个非常粗略的例子(无法在我当前的环境中对此进行测试)
这应该会让您朝着正确的方向获取附加到页面的所有图像。
将此函数放入函数中.php:
function get_match( $regex, $content ) {
preg_match($regex, $content, $matches);
return $matches[1];
}
在模板文件中:
query_posts('cat=15&order=DSC');
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Extract the shortcode arguments from the $page or $post
$shortcode_args = shortcode_parse_atts(get_match('/'[gallery's(.*)']/isU', $post->post_content));
$ids = $shortcode_args["ids"];
// get the attachments specified in the "ids" shortcode argument
$attachments = get_posts(
array(
'post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'menu_order ID',
'orderby' => 'post__in',
)
);
print_r($attachments);
endwhile; endif;
wp_reset_postdata();
不要将query_posts
用于其他帖子查询。请参阅:何时应使用 WP_Query vs query_posts() vs get_posts()?
您需要的可以通过 2 get_posts
,一个用于抓取该类别中的帖子。第二个,在第一个内部,使用post_parent
(如理查德丹顿的答案)和第一个循环的 ID 来获取附件。
您可以在functions.php
中创建自己的函数来完成这项工作。因此,在您的模板文件中,您只需(通用代码大纲):
<?php print_category_15(); ?>
和功能:
function print_category_15() {
$posts = get_posts( $your_arguments );
if( $posts ) {
foreach ( $posts as $post ) {
// Print titles and excerpts
print_childrens_of_15( $post->ID );
}
}
}
function print_childrens_of_15( $parent ) {
$children = get_posts( $your_arguments_for_attachments );
if( $children ) {
foreach ( $children as $child ) {
// Print your hidden divs to be used in the ShadowBox
}
}
}