我在函数中使用以下代码。php,以获取贴在帖子上的所有图像,以便我可以通过AJAX检索它们。
<?php
function get_all_images($post_id=0, $size=\'bigger\', $attributes=\'\') {
$post_id = $_POST[\'post_id\'];
if ($post_id<1) $postid = get_the_ID();
if ($images = get_children(array(
\'post_parent\' => $post_id,
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'orderby\' => \'menu_order\',
\'post_mime_type\' => \'image\',)))
$response = \'\';
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, $size);
$tranparent=get_template_directory_uri();
$response .= \'<img src="\'.$tranparent.\'/images/transparent.gif" data-original="\'.$attachment[0].\'" alt="" class="imarge" />\';
}
die( json_encode( $response ) );
}?>
我想做的是添加
<h2 class="titles">Title of the post</h2>
在所有图像之前的响应中。
所以我尝试了这个:
<?php
function get_all_images($post_id=0, $size=\'bigger\', $attributes=\'\') {
$post_id = $_POST[\'post_id\'];
if ($post_id<1) $postid = get_the_ID();
if ($images = get_children(array(
\'post_parent\' => $post_id,
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'orderby\' => \'menu_order\',
\'post_mime_type\' => \'image\',)))
$img = \'\';
$title = get_the_title($post_id);
$response = \'<h2 class="titles">\'.$title.\'</h2>\'.$img.\'\';
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, $size);
$tranparent=get_template_directory_uri();
$img .= \'<img src="\'.$tranparent.\'/images/transparent.gif" data-original="\'.$attachment[0].\'" alt="" class="imarge" />\';
}
die( json_encode( $response ) );
}?>
我现在得到了帖子的标题,但不再是图片了。有什么想法吗?
最合适的回答,由SO网友:marfarma 整理而成
您希望将标题添加到响应中,而不是将响应替换为标题。像这样:
<?php
function get_all_images($post_id=0, $size=\'bigger\', $attributes=\'\') {
$post_id = $_POST[\'post_id\'];
if ($post_id<1) $postid = get_the_ID();
if ($images = get_children(array(
\'post_parent\' => $post_id,
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'orderby\' => \'menu_order\',
\'post_mime_type\' => \'image\',)))
$title = get_the_title($post_id);
$response = \'<h2 class="titles">\'.$title.\'</h2>\';
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, $size);
$tranparent=get_template_directory_uri();
$response .= \'<img src="\'.$tranparent.\'/images/transparent.gif" data-original="\'.$attachment[0].\'" alt="" class="imarge" />\';
}
die( json_encode( $response ) );
}?>
Update
更正为将其添加到循环之前。