下面的代码将提供一个非常基本的接口。想法如下。在编辑页面上,您会看到另一个元框“Slider”,您可以在其中选择滑块应使用的连接媒体。当然,这里可以做更多的用户体验工作。现在,它只显示已连接的介质。因此,编辑器需要添加媒体,保存帖子,然后选择。可以做一些改进。
一旦编辑器为滑块定义了一些附加介质,您就不会使用get_attached_media( \'image\' )
还有,但是get_attached_slider()
. 基本上,该功能还输出Post对象,但仅输出所附媒体的Post对象,该对象应显示在滑块中。
希望,这给你一个开始,你需要什么。
<?php
add_action( \'add_meta_boxes\', \'slider_metabox\' );
function slider_metabox(){
add_meta_box(
\'slider-metabox\',
__( \'Slider Pictures\', \'sl\' ),
\'slider_metabox_render\',
\'post\' //Use \'post\' to display on Posts, \'page\' to display on Pages
);
}
/**
* This function renders the Metabox
**/
function slider_metabox_render( $post ){
$slider_attachments = get_post_meta( $post->ID, \'slider_attachments\', true );
$all_attachments = get_attached_media( \'image\', $post->ID );
if( empty( $slider_attachments ) )
$slider_attachments = array();
/*
* We get our attached media and the media, which is already supposed
* to be in the slider. We loop through all the attached media
* output a checkbox and if the single media is
* already for the slider, we check the checkbox
**/
?>
<ul>
<?php foreach( $all_attachments as $s ): ?>
<li data-attachment="<?php echo $s->ID; ?>">
<label for="attachment-<?php echo $s->ID; ?>">
<?php echo wp_get_attachment_image( $s->ID, \'post-thumbnail\' ); ?>
</label>
<input id="attachment-<?php echo $s->ID; ?>" type="checkbox" <?php
if( in_array( $s->ID, $slider_attachments ) ):
echo \'checked="checked" \';
endif;
?>name="slider_attachments[]" value="<?php echo $s->ID; ?>" />
</li>
<?php endforeach; ?>
</ul>
<?php
}
/**
* Lets save our slider media
**/
add_action( \'save_post\', \'slider_attachment_save\' );
function slider_attachment_save( $post_id ){
if ( wp_is_post_revision( $post_id ) )
return;
if( isset( $_POST[\'slider_attachments\'] ) )
update_post_meta(
$post_id,
\'slider_attachments\',
$_POST[\'slider_attachments\']
);
}
/**
* get_attached_slider
* Use this instead of get_attached_media() to retrieve only the slider images
**/
function get_attached_slider( $post_id = null ){
if( $post_id == null )
$post_id = get_the_ID();
if( !is_numeric( $post_id ) ){
$error = new WP_Error();
$error->add( \'post-id\', \'No valid post ID\' );
return $error;
}
$attachment_ids = get_post_meta( $post_id, \'slider_attachments\', true );
if( empty( $attachment_ids ) || ! is_array( $attachment_ids ) )
return false;
$args = array(
\'post_type\' => \'attachment\',
\'post__in\' => $attachment_ids,
\'post_status\' => \'any\',
\'posts_per_page\' => count( $attachment_ids )
);
$query = new WP_Query( $args );
$attachments = $query->posts;
return $attachments;
}
?>
有关如何实现这一点的更多信息: