user3318882
user3318882

Reputation:

how to show posts with different background for every post in WordPress?

I want to show different posts on my page but the problem is that every post has a unique background image which is, at the moment, added via background image property.
I need to replace this with WordPress, but I don't now how to achieve that. The idea I have is to use post thumbnail image as a background image, but in the post there is also a thumbnail showing up in the content.

It's the scenario of the post, background image, then comes the title, description and then comes the thumbnail. Sorry I could not upload any screen shot of my work, but I am trying my best to describe the whole scenario. Any suggestions will be appreciated.

Upvotes: 0

Views: 605

Answers (2)

Jonathan
Jonathan

Reputation: 6537

I believe my first answer will still be helpful to some, but since you cannot use Advanced Custom Fields or another plugin, you could add the following code in your functions.php file instead.

Note that I have taken and slightly modified the code from this Stack Overflow post to limit it to one image instead of a group of images, and I have made use of the more modern media uploader.

Also, this will only add the custom field to your post type, and not your pages, custom post types, etc. Look through the code, and I'm sure your can figure out how to change that if so desired.

add_action( 'admin_init', 'add_post_image_so_30337102' );
add_action( 'admin_head-post.php', 'print_scripts_so_30337102' );
add_action( 'admin_head-post-new.php', 'print_scripts_so_30337102' );
add_action( 'save_post', 'update_post_image_so_30337102', 10, 2 );

/**
 * Add custom Meta Box to Posts post type
 */
function add_post_image_so_30337102() 
{
    wp_enqueue_media();
    add_meta_box(
        'post_image',
        'Custom Uploader',
        'post_image_options_so_30337102',
        'post',
        'normal',
        'core'
    );
}

/**
 * Print the Meta Box content
 */
function post_image_options_so_30337102()
{
    global $post;
    $image_data = get_post_meta( $post->ID, 'image_data', true );

    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_so_30337102' );
?>

<div id="dynamic_form">

    <div id="field_wrap">
        <div class="field_row">

          <div class="field_left">
            <div class="form_field">
              <label>Image URL</label>
              <input type="text"
                     class="meta_image_url"
                     name="image[image_url]"
                     value="<?php esc_html_e( isset($image_data['image_url']) ? $image_data['image_url'] : '' ); ?>"
              />
            </div>
            <div class="form_field">
              <label>Description</label>
              <input type="text"
                     class="meta_image_desc"
                     name="image[image_desc]"
                     value="<?php esc_html_e( isset($image_data['image_desc']) ? $image_data['image_desc'] : '' ); ?>"
              />
            </div>
          </div>

          <div class="field_right image_wrap">
            <img src="<?php esc_html_e( $image_data['image_url'] ); ?>" height="48" width="48" />
          </div>

          <div class="field_right">
            <input class="button" type="button" value="Choose File" onclick="add_image(this)" /><br />
          </div>

          <div class="clear" /></div> 
        </div>
    </div>

</div>

  <?php
}

/**
 * Print styles and scripts
 */
function print_scripts_so_30337102()
{
    // Check for correct post_type
    global $post;
    if( 'post' != $post->post_type )
        return;
    ?>
    <style type="text/css">
      .field_left {
        float:left;
      }

      .field_right {
        float:left;
        margin-left:10px;
      }

      .clear {
        clear:both;
      }

      #dynamic_form {
        width:580px;
      }

      #dynamic_form input[type=text] {
        width:300px;
      }

      #dynamic_form .field_row {
        border:1px solid #999;
        margin-bottom:10px;
        padding:10px;
      }

      #dynamic_form label {
        padding:0 6px;
      }
    </style>

    <!-- New script taken from here: http://brinidesigner.com/use-wordpress-3-5-new-media-uploader-for-your-plugin-and-theme-options-panel-development/ -->
    <script type="text/javascript">
        function add_image(obj) {
            var parent=jQuery(obj).parent().parent('div.field_row');
            var inputField = jQuery(parent).find("input.meta_image_url");

            var image = wp.media({ 
                title: 'Upload Image',
                // mutiple: true if you want to upload multiple files at once
                multiple: false
            }).open()
            .on('select', function(e){
                // This will return the selected image from the Media Uploader, the result is an object
                var uploaded_image = image.state().get('selection').first();
                // We convert uploaded_image to a JSON object to make accessing it easier
                // Output to the console uploaded_image
                //console.log(uploaded_image);
                var image_url = uploaded_image.toJSON().url;
                // Let's assign the url value to the input field
                inputField.val(image_url);
                jQuery(parent)
                .find("div.image_wrap")
                .html('<img src="'+image_url+'" height="48" width="48" />');
            });

            return false;  
        }

    </script>
    <?php
}

/**
 * Save post action, process fields
 */
function update_post_image_so_30337102( $post_id, $post_object )
{
    // Doing revision, exit earlier **can be removed**
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    // Doing revision, exit earlier
    if ( 'revision' == $post_object->post_type )
        return;

    // Verify authenticity
    if ( !wp_verify_nonce( $_POST['noncename_so_30337102'], plugin_basename( __FILE__ ) ) )
        return;

    // Correct post type
    if ( 'post' != $_POST['post_type'] )
        return;

    if ( $_POST['image'] )
    {
        // Build array for saving post meta
        $image_data = array();
        if ( '' != $_POST['image']['image_url'] )
        {
            $image_data['image_url']  = $_POST['image']['image_url'];
            $image_data['image_desc'] = $_POST['image']['image_desc'];
        }

        if ( $image_data )
            update_post_meta( $post_id, 'image_data', $image_data );
        else
            delete_post_meta( $post_id, 'image_data' );
    }
    // Nothing received, all fields are empty, delete option
    else
    {
        delete_post_meta( $post_id, 'image_data' );
    }
}

Now you can get the image URL (and description) inside of your the_post() loop of your template like this:

$image_data = get_post_meta( $post->ID, 'image_data', true );

And then echo the image like this. You can re-use the CSS from my first answer.

<div class="hentry" style="background-image:url(<?php echo $image_data['image_url']; ?>)"></div>

Upvotes: 0

Jonathan
Jonathan

Reputation: 6537

This sounds like an excellent time to use a plugin like Advanced Custom Fields. Once you have it installed, you can follow these steps:

  1. Create a new field group.
  2. Add a new field of type "image".
  3. Make the rules for post-type is equal to post.

Now in your template file, you can fetch the image like this:

<?php
  // Where 'image' is the name of the field you added
  $image = get_field('image');
?>

Then you can include the image wherever you like later in the same template file, for example:

<div class="hentry" style="background-image:url(<?php echo $image['url']; ?>)"></div>

And in your CSS, assuming you want the background image to take up the whole background of the post:

<style type="text/css">
  .hentry  {
    background-size:cover;
    background-position:center;
  }
</style>

Let me know if that helps.

Upvotes: 0

Related Questions