首页 文章

Wordpress - 每个帖子多个图像

提问于
浏览
1

正在寻找任何指针 .

The functionality I'm after

基本上我希望能够为一个帖子分配最多6个不同的图像 . 所有6张图像将在single.php中正常显示 . 例如,在主页上,我希望其中一个图像随机显示在该帖子的页面加载上 .

A couple of questions

  • 这甚至可能吗?

  • 是否有可以管理此类事情的插件?

  • 如果我自己这样做,我应该如何创建这种功能呢?

2 回答

  • 4

    是的,这是可能的,而不是那么困难 . 您在创建帖子时上传图像 .

    然后在single.php中使用get_children从帖子中获取所有图像 .

    在循环中假设:

    $images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=$post->ID' );
    

    并输出它们如下:

    if ($images)
    {
    foreach ( $images as $attachment_id => $attachment ) {
            echo wp_get_attachment_image( $attachment_id, 'full' );
        }
    }
    

    对于随机图像,您可以使用与上面相同的get_children,但将 &numberposts=1 添加到args字符串 .

    或类似的东西:

    function fetch_random_img($postid='') {
        global $wpdb;
        if (empty($postid))
        {
           //we are going for random post and random image
         $postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY RAND() LIMIT 1");
        }
        $imageid = $wpdb->get_var($wpdb->prepare("SELECT ID FROM wp_posts WHERE post_type='attachment' AND post_mime_type LIKE 'image/%' AND post_parent=$postid ORDER BY RAND() LIMIT 1"));
        if ($imageid) {
             echo wp_get_attachment_image( $imageid, 'full' );
        }
        else {
        return false;
        }
    
        }
    

    这将只给你一个随机图像,它将是随机的,而get_children每次都会拉出相同的图像,除非你添加order和orderby参数,这将允许你更改哪个图像出来 .

    要在div中回显图像,只需调用函数:

    <div>
    <?php fetch_random_img(); ?>
    </div>
    
  • 0

    对于每个帖子,添加一个带有名称和值的自定义字段 . 您可以将名称设置为ImageURL1,值可以是图像的URL . 根据需要为帖子添加任意数量的自定义字段 . 例:

    enter image description here

    使用以下代码将其打印在single.php或循环内的任何其他文件中:

    <?php $values = get_post_custom_values("ImageURL"); echo $values[0]; ?>
    

    要在主页上加载它,您将查询帖子,然后获取index.php中特定名称的自定义字段值:

    <?php query_posts('cat=10')  //your cat id here ?>
    <?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
    <a href="<?php $values = get_post_custom_values("LinkURL"); echo $values[0]; ?>" target="_blank"><img src="<?php $values = get_post_custom_values("ImageURL"); echo $values[0]; ?>" alt="<?php the_title(); ?>" /></a>
    <?php endwhile; ?><?php endif; ?>
    <?php wp_reset_query(); ?>
    

    您可以随机化它或循环浏览自定义字段(如果需要) .

相关问题