Wordpress通过功能php获取附件

时间:2014-04-30 07:51:30

标签: wordpress

我正在尝试通过function.php改变Wordpress中的图库短代码,但无论如何,我得到零结果。这是我最简单的代码:

remove_shortcode( 'gallery' );
add_shortcode( 'gallery', 'altered_gallery' );

function altered_gallery( $attr ) {
    global $post;   

    $attachments = get_children(array(
        'post_parent'=> $post->ID, // confirmed, right ID
        'post_status'=>'inherit', 
        'post_type'=> 'attachment', 
        'post_mime_type'=>'image', 
        'order'=> 'ASC', 
        'orderby'=> 'menu_order ID',
        'exclude'=> ''
    )); 

    $imageCount = count( $attachments ); // just to check

    echo $imageCount; // result 0, without ID, it will throw every attachment I have in every post
}

我看到几个教程提出相同的方法,包括在SO中。但我无法从中产生任何结果。我做错了什么?或者有更好的方法来获得附件吗?

THX

1 个答案:

答案 0 :(得分:0)

您必须具体说明post_type

$attachments = get_children(array(
    'post_type'   => 'attachment',
    'post_parent' => $post->ID, // confirmed, right ID
));

下次,请学习法典:http://codex.wordpress.org/Function_Reference/get_children