首页 文章

Wordpress从附件中获取发布信息

提问于
浏览
0

我试图制作一个模板来显示wordpress博客中所有使用过的图像,并链接到附有图像的帖子,如图库或投资组合页面,但我无法获得帖子单页的链接或 Headers . 我做到了这一点:

<?php
$post_parent = get_post($post->ID, ARRAY_A);
$parent = $post_parent['post_parent'];
$paged = ( get_query_var( 'paged' ) ) ? get_query_var('paged') : 1;
$attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC', 'paged' => $paged, 'posts_per_page' =>9,) ); 
?>

和foreach:

<?php foreach($attachments as $id => $attachment) :
$img_title = $attachment->post_title;
$img_caption = $attachment->post_excerpt;
$img_description = $attachment->post_content;
?>

所以我查了一下codex,发现如何得到这样的img url:

<?php if ( have_posts() ) : ?>
<li>
<?php $image_attributes = wp_get_attachment_image_src( $id, full ); // returns an array
if( $image_attributes ) {?> 
<a  href="<?php echo $image_attributes[0]; ?>"><img src="<?php echo $image_attributes[0]; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_title; ?>" /></a>
<?php
echo $post->post_parent;
?>
<p><a href="<?php
echo get_post($id)->post_parent; ?>">link</a></p>
<?php } ?>
</li>
<?php endif; ?>

<?php endforeach; ?>

上面的代码效果很好,它显示了附在ul l列表中的所有图像 .

然后我想在循环中添加一个指向父POST的链接,使用foreach中的内容,如:

<p><a href="<?php echo get_post($id)->post_parent; ?>">Post link</a></p>

但它返回一个没有的链接或返回“0”,如果我“回显$ id”,它返回附件ID但不返回帖子ID(帖子ID是我想要的) .

请问如何获取父帖子ID或只是在上面的循环中获取帖子链接和 Headers ?救命!

谢谢!

1 回答

  • 0

    现在找到答案 . 我使用普通查询来获取所有帖子,并且查询在内容(或其特色图像)中搜索img标签然后在循环中显示该图像,可选地在该图像下方显示摘录,然后完成此模板 .

    我正在考虑在媒体库中获取附件,但这不是正确的方式,有些媒体甚至没有附加到任何帖子,所以这是一个死胡同 .

    但是要查询帖子并进行查询,选择带有“ <img ”的帖子在某种程度上比查询附件更好,而且也很容易理解 .

相关问题