开发者

How do I get a list of items in the Wordpress media library on a plugin options page?

开发者 https://www.devze.com 2023-01-05 12:07 出处:网络
I\'m writing a Wordpress plugin which injects a grid of images just above the footer on all frontend pages. The application is to display sponsor\'s logos. I\'d like to harness the WP Media Library si

I'm writing a Wordpress plugin which injects a grid of images just above the footer on all frontend pages. The application is to display sponsor's logos. I'd like to harness the WP Media Library since the logos are already uploaded for use on the 'sponsorship' page and in posts.

Essentially I'm stuck at accessing the media library interface on the plugin's options page. All of the legwor开发者_运维问答k is done in terms of creating the options page, using the action hook to place content on frontend pages from the plugin, etc. What I need now is to be able to display all the files in the media library in a list on the options page, and provide a checkbox or something to allow the user to select certain files for insertion above the footer.

The Media Library API seems to be aimed at people writing themes or media plugins. Help understanding what to make use of would be great!


I think you'd be much better off adding your own column into the existing media library, rather than try re-coding it yourself;

function my_media_col($cols)
{
    $cols['my_col'] = 'Footer';
    return $cols;
}
add_filter('manage_media_columns', 'my_media_col');

function handle_my_media_col($name, $id)
{
    if ($name !== 'my_col')
        return false;
    $in_footer = get_option('in_footer', array());
?>
<input type="checkbox" name="in_footer[]" value="<?php echo $id; ?>" <?php checked(in_array($id, $in_footer)); ?> />
<?php
}
add_action('manage_media_custom_column', 'handle_my_media_col', 10, 2);

Then just hook onto the load-upload.php (the library page) and save changes when POST'ed;

function save_my_col()
{
    if (!isset($_POST['in_footer']))
        return false;

    $in_footer = $_POST['in_footer'];
    if (is_array($in_footer))
        $in_footer = array_map('absint', $in_footer); // sanitize
    else
        $in_footer = array();

    $in_footer = array_merge(get_option('in_footer', array()), $in_footer);
    $in_footer = array_unique(array_filter($in_footer));
    update_option('in_footer', $in_footer);
}
add_action('load-upload.php', 'save_my_col');

Note this is just an example, and I may have one or two typos.

UPDATED:

My code example should store an array of IDs in the options table, under the key 'in_footer'.

Put in practice, you can get all media items marked 'in footer' like so;

$query = new WP_Query(array('post__in' => get_option('in_footer', array()) ));

if ($query->have_posts()): while ($query->have_posts()): $query->the_post();
?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

<?php endwhile; endif; ?>
0

精彩评论

暂无评论...
验证码 换一张
取 消