Joao Alves Marrucho Joao Alves Marrucho - 1 year ago 72
CSS Question

How to get my thumbnails to display in random positions (in archive page wordpress)

I have registered a custom post type in my theme (no plugins) in my functions.php wordpress file like this:

add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'Works',
'labels' => array(
'name' => __( 'Works' ),
'singular_name' => __( 'Work' )
'public' => true,
'description' => ('Work'),
'has_archive' => true,
'taxonomies' => array('category'),
'supports' => array( 'title', 'editor', 'thumbnail')

I have then created an "archive-works.php" where I am only showing this custom post-type. And there I am merely showing the thumbnails and the title when you hover. Those thumbnails are links (there is a "a" tag around the "img"). And they are being styled like this:

#content img {
width: 70%;
height: auto;

Meanwhile I have wrapped a ".js-container" class around all links.

<div class="js-container">
<a href="" title="Work 3">
<img width="960" height="630" src=""
class="attachment-post-thumbnail size-post-thumbnail wp-post-image"
srcset=" 960w, 300w, 768w"
sizes="(max-width: 960px) 100vw, 960px">

I want the images to deviate ever so slightly from their natural positions. I mean, I need to place them randomly position-wise (more on the left or on the right, and if possible slightly above or below of where they should be.
I was doing a bit of research and I have found this example: Positioning images in random places

I know it is a combination of javascript and css as in the example above. This is my current stage:
I have tried typing this on the header.php file but with no results:

<script type="text/javascript">
$('.js-container a img').each(function() {
var top = Math.floor(Math.random() * 400), left = Math.floor(Math.random() * 400);
"top": top,
"left": left,

Can someone help me out here?
Many thanks.

Answer Source

This should be a correct JavaScript for your case. You don't need that .js-container anymore, it is bound directly to the post divs:

    jQuery(window).load(function() {
        $('').each(function () {
            // get the size and position
            var width = $(this).find('img').width(),
                height = $(this).find('img').height(),
                top = Math.floor(Math.max((Math.random() * $(window).height() - height), 0)),
                left = Math.floor(Math.max((Math.random() * $(window).width() - width), 0));

            // place the element
                "display": "block",
                "position": "absolute",
                "top": top,
                "left": left,
                "width": width,
                "height": height
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download