• Resolved pacificshack

    (@pacificshack)


    OK i’ve been doing all the rounds on this one and still can’t find a solution!

    I have a site which the client wants to use infinite scroll across custom post types. I can get this to work for for some reason after the first 10 posts are loaded in, the next 10 posts are the first 10, and then the page continues to load in as it should.

    Am running Masonry with this too.

    Anyone have any ideas which it’s doing this? Thought it be to do with having first 10 posts display on the posts page, but not sure now.

    Have got this in my function file:
    // Jetpack Infinite scroll
    function enqueue_masonry_script() {
    wp_enqueue_script(‘masonry-script’, get_template_directory_uri() . ‘/js/masonry.pkgd.min.js’, array(‘jquery’));
    }
    add_action(‘wp_enqueue_scripts’, ‘enqueue_masonry_script’);

    function my_load_infinite_scroll( $load_infinite_scroll ) {
    if( is_post_type_archive(‘gallery’) )
    return true;
    return $load_infinite_scroll;
    }
    add_filter(‘infinite_scroll_load_override’, ‘my_load_infinite_scroll’);

    add_theme_support( ‘infinite-scroll’, array(
    ‘container’ => ‘pageRowMasonry’,
    ‘wrapper’ => false,
    ‘render’ => false,
    ‘footer’ => false,
    ‘posts_per_page’ => ‘7’
    ) );

    This is the jQuery which loads in the footer:
    <script>
    // 1 Masonry first state
    jQuery(‘.js-masonry’).imagesLoaded( function(){
    jQuery(‘.js-masonry’).masonry({
    isAnimated: true,
    isFitWidth: true,
    “gutter”: 20,
    transitionDuration: 0
    });
    });

    // 2 Masonry second state
    jQuery( document ).ready( function( $ ) {
    infinite_count = 0;
    // Triggers re-layout on infinite scroll
    $(document.body).on(‘post-load’, function() {
    infinite_count = infinite_count + 1;
    var $container = $(‘#pageRowMasonry’);
    var $selector = $(‘#infinite-view-‘ + infinite_count);
    var $elements = $selector.find(‘.pagePhotoshootsContainer’);
    $elements.hide();
    $container.masonry(‘reloadItems’);
    $elements.fadeIn();

    jQuery(‘.js-masonry’).masonry({
    isAnimated: true,
    isFitWidth: true,
    “gutter”: 20,
    transitionDuration: 0
    });

    });
    });
    </script>

    Then calling in the posts:
    $args = array(‘posts_per_page’ => 10, ‘post_type’ => ‘post’, ‘post_status’ => ‘publish’);
    query_posts($args);
    if ( have_posts() ) :…..

    I have also tried using an array in a session to match post>id, but to no avail.

    https://wordpress.org/plugins/jetpack/

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author Brandon Kraft

    (@kraftbj)

    Code Wrangler

    Do you have a site with that running and failing? I’m curious in seeing the output of the IS. Could you get it working without Masonry?

    I haven’t used them together before myself, so a bit of exploration on my part πŸ™‚

    Cheers!

    Thread Starter pacificshack

    (@pacificshack)

    I am building a beta site for a client at the mo and it’s private so I can’t send a link yet.

    I managed to get JetPack working on Posts which are used on a blog, and I was able to target the second ‘set’ of 10 posts loaded which were duplicates using CSS, and I then turned them off so they don’t appear:

    .pagePhotoshootsContainer:nth-child(10) { display: none; }

    I’ve since abandoned JetPack. For just using Infinite Scroll it’s not worth it. The other issue was using it across custom post types, which I thought I had nailed, but not. I need infinite scroll used on a long list of images.

    So instead I’ve gone for this solution:
    http://www.w3bees.com/2013/09/jquery-infinite-scroll-with-php-mysql.html

    Quite a lightweight infinite scroll and works well. The only drawback is I am having to use direct mysql queries, which isn’t too bad as I find it easier anyway as oppose to using WordPress specific functions.

    I am now able to get it working across custom post types, and using masonry. Only issue is now getting the second set of posts moving which I’m sure i’ll nail today.

    This is the Masonry resource: http://masonry.desandro.com/

    Thread Starter pacificshack

    (@pacificshack)

    OK, some good news! Infinite scroll on WordPress with custom post types inside Masonry – works! Yippee!

    I set up an includes file called page-gallery.inc – and I point to it if the user is on the Gallery page, then use the following code:

    <?php
    # db configuration
    define('DB_HOST', '<DB_HOST>');
    define('DB_USER', '<DB_USER>');
    define('DB_PASS', '<DB_PASS>');
    define('DB_NAME', '<DB_NAME>');
    $limit = 10; #item per page
    # db connect
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error();
    $db = mysql_select_db(DB_NAME, $link);
    $page = (!isset($_GET['page'])) ? 1 : $_GET['page'];
    # sql query
    $sql = "SELECT * FROM wp_posts WHERE post_type = 'gallery' AND post_status = 'publish' ORDER BY post_title ASC";
    # find out query stat point
    $start = ($page * $limit) - $limit;
    # query for page navigation
    if( mysql_num_rows(mysql_query($sql)) > ($page * $limit) ){
    	$next = ++$page;
    }
    $query = mysql_query( $sql . " LIMIT {$start}, {$limit}");
    if (mysql_num_rows($query) < 1) {
    	header('HTTP/1.0 404 Not Found');
    	echo 'Page not found!';
    	exit();
    }
    ?>
    
    <div id="pageRowMasonry" class="pageRow js-masonry" id="contentScroller" data-masonry-options='{ "columnWidth": 200, "itemSelector": ".pageGalleryContainer" }'>
    
    	<?php
    	// Loop first wp_posts
    	while ($row = mysql_fetch_array($query)):
    		// Look for featured image in WP_postmeta
    		$sqlMETA1 = "SELECT * FROM wp_postmeta WHERE post_id = '".$row['ID']."'";
    		$queryMETA1 = mysql_query($sqlMETA1);
    		$rowMETA1 = mysql_fetch_array($queryMETA1);
    
    		// Look for _thumbnail_id
    		if ($rowMETA1['meta_key'] == '_thumbnail_id') {
    			$sqlMETA2 = "SELECT * FROM wp_postmeta WHERE post_id = '".$rowMETA1['meta_value']."'";
    			$queryMETA2 = mysql_query($sqlMETA2);
    			$rowMETA2 = mysql_fetch_array($queryMETA2);
    
    			// Look for categories through WP
    			$sqlTERMS = "SELECT * FROM wp_terms WHERE name = 'Gallery (Double)'";
    			$queryTERMS = mysql_query($sqlTERMS);
    			$rowTERMS = mysql_fetch_array($queryTERMS);
    
    			$sqlTAX = "SELECT * FROM wp_term_taxonomy WHERE term_id = '".$rowTERMS['term_id']."'";
    			$queryTAX = mysql_query($sqlTAX);
    			$rowTAX = mysql_fetch_array($queryTAX);
    
    			$sqlRELS = "SELECT * FROM wp_term_relationships WHERE object_id = '".$row['ID']."' AND term_taxonomy_id = '".$rowTAX['term_taxonomy_id']."'";
    			$queryRELS = mysql_query($sqlRELS);
    			$rowRELS = mysql_fetch_array($queryRELS);
    
    			if (isset($rowRELS['object_id'])) {
    				$pageGalleryContainerType = 'pageGalleryContainerDouble';
    			} else { $pageGalleryContainerType = 'pageGalleryContainerSingle'; }
    			?>
    			<div class="pageGalleryContainer <?php echo $pageGalleryContainerType; ?> masonry-brick" style="position: absolute;">
    				<a href="http://beta.photographersinc.co.nz/wp-content/uploads/<?php echo $rowMETA2['meta_value']; ?>" class="fancybox">
    					<div class="pageGalleryContainerText"><h3 class="displayNone"><?php echo $row['post_title']; ?></h3></div>
    					<img width="474" height="316" src="http://beta.photographersinc.co.nz/wp-content/uploads/<?php echo $rowMETA2['meta_value']; ?>" class="attachment-large wp-post-image" alt="<?php echo $row['post_title']; ?>">
    				</a>
    			</div>
    	<?php } ?>
    	<?php endwhile; ?>
    
    	<!--page navigation-->
    	<?php if (isset($next)): ?>
    	<div class="page-nav">
    		<a href='http://beta.photographersinc.co.nz/gallery.php?page=<?php echo $next?>'>Next</a>
    	</div>
    	<?php endif?>
    
    	<script src="<?php bloginfo('template_directory'); ?>/js/masonry.pkgd.min.js"></script>
    	<script src="<?php bloginfo('template_directory'); ?>/js/jquery.infinitescroll.min.js"></script>
    	<script>
    	  jQuery(function(){
    
    	    var $container = jQuery('#pageRowMasonry');
    
    	    $container.imagesLoaded(function(){
    	      $container.masonry({
    	        itemSelector: '.pageGalleryContainer',
    	        columnWidth: 100
    	      });
    	    });
    
    	    $container.infinitescroll({
    	      navSelector  : '.page-nav',    // selector for the paged navigation
    	      nextSelector : '.page-nav a',  // selector for the NEXT link (to page 2)
    	      itemSelector : '.pageGalleryContainer',     // selector for all items you'll retrieve
    	      loading: {
    	          finishedMsg: 'No more pages to load.',
    	          img: 'http://i.imgur.com/6RMhx.gif'
    	        }
    	      },
    	      // trigger Masonry as a callback
    	      function( newElements ) {
    	        // hide new items while they are loading
    	        var $newElems = jQuery( newElements ).css({ opacity: 0 });
    	        // ensure that images load before adding to masonry layout
    	        $newElems.imagesLoaded(function(){
    	          // show elems now they're ready
    	          $newElems.animate({ opacity: 1 });
    	          $container.masonry( 'appended', $newElems, true );
    	        });
    	      }
    	    );
    
    	  });
    	</script>
    </div>

    Bingo. As the page scrolls down it loads in more posts of the type ‘gallery’ which have been set up as a custom post type.

    Hope this helps other people, it has taken me a long time to resolve.

    Plugin Author Brandon Kraft

    (@kraftbj)

    Code Wrangler

    Glad you found a solution that works for you. Not meant to be a full code review, but I would consider using the wpdb class instead of directly using SQL ( https://codex.wordpress.org/Class_Reference/wpdb ).

    This would futureproof the queries more (e.g. automatically determine to use mysqli or mysql, accounting for changes to the WP db schema over time, etc)

    Thread Starter pacificshack

    (@pacificshack)

    Cheers Brandon, i’ll look at updating the queries when I get it finished!

    Next issue I am having is getting Fancybox to work on the images. I am using Easy Fancybox which fires the images open, no problems there. I am then trying to pass through the ID of the post through the alt tag in jQuery. Then I need to pass it to php and get the post from the DB. Once I have that I can pull in the tags and other data the post has which I need to display.

    Also, the code above, I have since made a heap of changes and found putting in the jQuery in the footer the better option. So keeping in the php at the top of the page, the rest of the html looks like:

    <div id="pageRowMasonry" class="pageRow js-masonry" id="contentScroller" data-masonry-options='{ "columnWidth": 200, "itemSelector": ".pageGalleryContainer" }'>
    
    <?php
    $count = 0;
    
    // Loop first wp_posts
    while ($row = mysql_fetch_array($query)):
    $count++;
    	// Look for featured image in WP_postmeta
    	$sqlMETA1 = "SELECT * FROM wp_postmeta WHERE post_id = '".$row['ID']."'";
    	$queryMETA1 = mysql_query($sqlMETA1);
    	$rowMETA1 = mysql_fetch_array($queryMETA1);
    
    	// Look for _thumbnail_id
    	if ($rowMETA1['meta_key'] == '_thumbnail_id') {
    		$sqlMETA2 = "SELECT * FROM wp_postmeta WHERE post_id = '".$rowMETA1['meta_value']."'";
    		$queryMETA2 = mysql_query($sqlMETA2);
    		$rowMETA2 = mysql_fetch_array($queryMETA2);
    
    		// Look for categories through WP
    		$sqlTERMS = "SELECT * FROM wp_terms WHERE name = 'Gallery (Double)'";
    		$queryTERMS = mysql_query($sqlTERMS);
    		$rowTERMS = mysql_fetch_array($queryTERMS);
    
    		$sqlTAX = "SELECT * FROM wp_term_taxonomy WHERE term_id = '".$rowTERMS['term_id']."'";
    		$queryTAX = mysql_query($sqlTAX);
    		$rowTAX = mysql_fetch_array($queryTAX);
    
    		$sqlRELS = "SELECT * FROM wp_term_relationships WHERE object_id = '".$row['ID']."' AND term_taxonomy_id = '".$rowTAX['term_taxonomy_id']."'";
    		$queryRELS = mysql_query($sqlRELS);
    		$rowRELS = mysql_fetch_array($queryRELS);
    
    		if (isset($rowRELS['object_id'])) {
    			$pageGalleryContainerType = 'pageGalleryContainerDouble';
    		} else { $pageGalleryContainerType = 'pageGalleryContainerSingle'; }
    		?>
    		<div class="pageGalleryContainer pageGalleryContainer<?php echo $page.$count; ?> <?php echo $pageGalleryContainerType; ?> masonry-brick" style="position: absolute;">
    			<a tabindex="1" class="fancybox" rel="gallery" href="http://beta.photographersinc.co.nz/wp-content/uploads/<?php echo $rowMETA2['meta_value']; ?>" title="<?php echo $row['ID']; ?>">
    				<div class="pageGalleryContainerText"><h3 class="displayNone"><?php echo $row['post_title']; ?></h3></div>
    				<img width="474" height="316" src="http://beta.photographersinc.co.nz/wp-content/uploads/<?php echo $rowMETA2['meta_value']; ?>" class="attachment-large wp-post-image" alt="<?php echo $row['ID']; ?>" title="<?php echo $row['post_title']; ?>">
    			</a>
    		</div>
    <?php } ?>
    <?php endwhile; ?>
    
    <!--page navigation-->
    <?php if (isset($next)): ?>
    <div class="page-nav">
    	<a href='http://beta.photographersinc.co.nz/gallery.php?page=<?php echo $next?>'>Next</a>
    </div>
    <?php endif?>
    
    </div>

    Then in the footer:

    <script>
    	jQuery(function(){
    
    		var $container = jQuery('#pageRowMasonry');
    
    		$container.imagesLoaded(function(){
    			$container.masonry({
    			itemSelector: '.pageGalleryContainer',
    			columnWidth: 100
    			});
    		});
    
    		$container.infinitescroll({
    		navSelector  : '.page-nav',    // selector for the paged navigation
    		nextSelector : '.page-nav a',  // selector for the NEXT link (to page 2)
    		itemSelector : '.pageGalleryContainer',     // selector for all items you'll retrieve
    			loading: {
    			finishedMsg: 'No more pages to load.',
    			img: 'http://i.imgur.com/6RMhx.gif'
    			}
    		},
    		// trigger Masonry as a callback
    		function( newElements ) {
    			// hide new items while they are loading
    			var $newElems = jQuery( newElements ).css({ opacity: 0 });
    			// ensure that images load before adding to masonry layout
    			$newElems.imagesLoaded(function(){
    				// show elems now they're ready
    				$newElems.animate({ opacity: 1 });
    				$container.masonry( 'appended', $newElems, true );
    			});
    
    			jQuery(newElements).each(function() {
    				// Image hovers
    				jQuery(this).on("hover",function(){
    					jQuery(this).find('img').toggleClass('pageGalleryContainerImageRollover');
    					jQuery(this).find('h3').toggleClass('displayNone');
    				});
    
    				jQuery(this).on("click",function(){
    					jQuery.ajax({
    					type: 'POST',
    					url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session.php',
    					data: {
    						galleryValue: jQuery(this).find('img').attr("alt")
    						}
    					});
    				});
    
    				// Fancybox
    				jQuery("a.fancybox").fancybox({
    					// fancybox API options here
    					'padding': 10,
    					'titlePosition'  : 'over',
    					'titleFromAlt' :  true,
    					'onComplete': function(){
    						jQuery('#fancybox-title-over').append(' test ');
    						jQuery('#fancybox-title-over').append(' <?php echo $_SESSION['SESSIONaltValue']; ?> ');
    					}
    				});
    
    			});
    		});
    	});
    	</script>

    Masonry is now working really well with Infinite Scroll. Fancybox is working fine too. Just need to be able to pass the ID as a jQuery variable via AJAX to php so I can look up the ID in the database. Getting there.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Infinite scroll and first page duplicate posts’ is closed to new replies.