我不喜欢WordPress处理库短代码的方式。
这是我用来在图库中获取图像的一些稍加修改的代码。在本例中,附件(以及它们的ID)只有在处理完gallery短代码后才可用。
如果您希望显示不同于默认库的HTML,我会使用post_gallery
过滤以短路内置WordPress快捷码并显示您自己的快捷码。
namespace StackExchange\\WordPress;
class Q291678 {
protected $attachements = [];
public function getAttachments() : array {
return $this->attachments;
}
public function wp_loaded() {
\\add_filter( \'shortcode_atts_gallery\', [ $this, \'shortcode_atts_gallery\' ], 10, 4 );
}
public function shortcode_atts_gallery( array $out, array $pairs, array $atts, string $shortcode ) : array {
$this->attachements = $this->getPostAttachments( $out );
return $out;
}
protected function getPostAttachments( array $atts ) : array {
//* Code copied from WP Core to get post attachements
$id = intval( $atts[ \'id\' ] );
if ( ! empty( $atts[ \'include\' ] ) ) {
$_attachments = \\get_posts( [
\'include\' => $atts[ \'include\' ],
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => $atts[ \'order\' ],
\'orderby\' => $atts[ \'orderby\' ]
] );
$attachments = [];
foreach ( $_attachments as $key => $val ) {
$attachments[ $val->ID ] = $_attachments[ $key ];
}
} elseif ( ! empty( $atts[\'exclude\'] ) ) {
$attachments = \\get_children( [
\'post_parent\' => $id,
\'exclude\' => $atts[ \'exclude\' ],
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => $atts[ \'order\' ],
\'orderby\' => $atts[ \'orderby\' ]
] );
} else {
$attachments = \\get_children( array(
\'post_parent\' => $id,
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => $atts[ \'order\' ],
\'orderby\' => $atts[ \'orderby\' ] ) );
}
//* End code from core
return $attachments;
}
}
\\add_action( \'wp_loaded\', [ new Q291678, \'wp_loaded\' ] );