I have a question related with Wordpress Ajax posts request. And I can't figure out for hours... Maybe someone will give me advice what I'm doing wrong!
Problem:
So I have infinite scroll on my archive pages. Everything is working as it should but for some reason it loads all the time the same 20 posts... What I need to change to have infinite scroll as long as created posts exists.
Here is my JS code:
function loadArticle() {
var loading = false;
$(window).bind('scroll', function() {
var page = $(this).data('page');
var newPage = page + 1;
var maxPages = $("#content").data('max-pages');
var postType = false;
var search = getQueryVariable("s");
if ( $('body').hasClass('post-type-archive-news') ) {
postType = 'news';
} else if ( $('body').hasClass('post-type-archive-ebooks') ) {
postType = 'ebooks';
} else if ( $('body').hasClass('post-type-archive-lookbooks') ) {
postType = 'lookbooks';
} else if ( $('body').hasClass('post-type-archive-case-studies') ) {
postType = 'case-studies';
} else if ( $('body').hasClass('post-type-archive-events') ) {
postType = 'events';
} else if ( $('body').hasClass('search-results') ) {
postType = false;
} else {
postType = 'post';
}
var query = 'action=infinite_scroll';
if ( newPage ) {
query = query + '&page_no=' + newPage;
}
if ( typeof postType == "string" ) {
query = query + "&post_type=" + postType;
}
if ( typeof search == "string" ) {
query = query + "&search=" + search;
}
// Show Loader
//$('a#inifiniteLoader').show('fast');
// Load Next Page
if(!loading && $(window).scrollTop() >= ($('#content').offset().top + $('#content').outerHeight() - window.innerHeight)) {
loading = true;
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:'POST',
data: query,
success: function(html){
$("#content").append(html); // This will be the div where our content will be loaded
loading = false;
}
});
}
return false;
});
}
And this is my PHP
function yieldify_infinite_scroll(){
//init ajax
$ajax = false;
//check ajax call or not
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$ajax = true;
}
$paged = $_POST['page_no'] + 1;
$post_type = $_POST['post_type'];
$search = $_POST['s'];
$args = array(
'posts_per_page' => get_option('posts_per_page'),
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
if ( $post_type ) {
$args['post_type'] = $post_type;
}
if ( $search ) {
$args['s'] = $post_type;
}
// Load the posts
//query_posts( $args );
$ajax_query = new WP_query( $args );
//echo "<pre>";
//$print_query = json_encode( $ajax_query, JSON_PRETTY_PRINT );
//$print_query = htmlentities( $print_query, ENT_QUOTES, 'utf-8' );
//print_r( $print_query );
//echo "</pre>";
if( $ajax_query->have_posts() ) {
while( $ajax_query->have_posts() ) { $ajax_query->the_post();
if ( $post_type ) { ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php } else {
echo "<div class='col-12'>";
get_template_part('loops/search-results');
echo "</div>";
}
}
}
wp_reset_postdata();
//check ajax call
if($ajax) die();
exit;
}
add_action('wp_ajax_infinite_scroll', 'yieldify_infinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'yieldify_infinite_scroll');
My archive layout looks like that:
<?php if( have_posts() ) : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
<section id="blog-listing" class="resources-section">
<div class='container'>
<div class='row' id="content">
<?php while( have_posts() ) : the_post(); ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php endwhile; ?>
</div><!-- .row -->
<div class='row'>
<div class='col-12 text-center'>
Show More
</div><!-- .col -->
</div><!-- .row -->
</div><!-- .container -->
</section><!-- #blog-listing -->
<?php endif; ?>
I would be appreciated for any help!
It seems to me that you need to update the value in $(this).data('page')
You get it, do an increment on the variable, but you do not store it back. Try to modify as follow.
var page = $(this).data('page');
var newPage = page + 1;
$(this).data('page', newPage);
Related
I'm using "Users Following System" plugin. So far I added a list of the following/followers into the author.php profile, now I'm trying to use Ajax with this but the problem I'm facing that I need to get the same user meta for each user by ID, So that everyone can see the following users of each other.
In author.php I used this line to get the users information.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
And this line to get the user meta of _pwuf_following
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
But when I added the same lines within the Ajax function handler not working.
i tried get_queried_object(); wp_get_current_user(); get_userdata();
but I always failing.
Here's the snippet from author.php to get the list of following users.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => 1
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
?>
This is the js to get Ajax url and action
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var canBeLoaded = true,
bottomOffset = 2000;
jQuery(function($) {
$(window).scroll(function() {
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ) {
canBeLoaded = false;
var data = {
'action': 'user_following_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("user_more_following"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('#following').append(response);
canBeLoaded = true;
page++;
});
}
});
});
</script>
And this is from the function.php of Ajax handler.
add_action('wp_ajax_user_following_by_ajax', 'user_following_by_ajax_callback');
add_action('wp_ajax_nopriv_user_following_by_ajax', 'user_following_by_ajax_callback');
function user_following_by_ajax_callback() {
check_ajax_referer('user_more_following', 'security');
$paged = $_POST['page'];
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => $paged
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
wp_die();
}
I can see you don't pass the author_name field which is used in your code. Please check below code where I have added the missing field.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var canBeLoaded = true,
bottomOffset = 2000;
jQuery(function($) {
$(window).scroll(function() {
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ) {
canBeLoaded = false;
var data = {
'action': 'user_following_by_ajax',
'data': { page : 'page', author_name: '<?php echo get_the_author(); ?>' }, // Here set author name which you are getting.
'security': '<?php echo wp_create_nonce("user_more_following"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('#following').append(response);
canBeLoaded = true;
page++;
});
}
});
});
</script>
I'm very new to the Wordpress. I'm currently using the FoundationPress theme and I'm trying to add a button that the user can click to load more post.
What I want is that initially the user will see four blog posts and when the user click on the read more button it will load the next four until there are no more posts and the button disappear.
I got up to the point where I can load the first four posts, but I'm having a hard time setting up a button to display the next four posts.
This is what I have so far:
<section class="row blogArticleWrapper">
<?php while ( have_posts() ) : the_post(); ?>
<?php
the_post();
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'orderby' => 'date',
'order' => 'DESC'
) );
if ( $blog_posts ):
?>
<?php
foreach ( $blog_posts as $post ):
setup_postdata($post);
?>
<article class="blog-profile small-12 columns">
<span class="name"><?php the_field("news_title"); ?></span>
<p class="writtenBy">Written by: <?php the_field("news_written_by"); ?> <span class="date">Date: <?php the_field("news_date"); ?></span></p>
</article><!-- /.profile -->
<?php endforeach;
?>
<?php endif; ?>
<?php endwhile; // end of the loop. ?>
</section><!-- /.row -->
I tried following this guide, but I don't know how to use it on my page.
Any help is appreciated,
Thanks.
Remove:
while ( have_posts() ) : the_post(); ?>
the_post();
and
<?php endwhile; // end of the loop. ?>
Change request to
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
) );
Add to functions.php
function wp_corenavi() {
global $wp_query;
$pages = '';
$max = $wp_query->max_num_pages;
if (!$current = get_query_var('paged')) $current = 1;
$a['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
$a['total'] = $max;
$a['current'] = $current;
$total = 1;
$a['mid_size'] = 3;
$a['end_size'] = 1;
$a['prev_text'] = '«';
$a['next_text'] = '»';
if ($max > 1) echo '<div id="pagination" class="navigation column medium-12">';
if ($total == 1 && $max > 1) $pages = '<span class="pages">' . __('Page', 'Site') . $current . ' ' . __('of', 'Site') . ' ' . $max . '</span>'."\r\n";
echo $pages . paginate_links($a);
if ($max > 1) echo '</div>';
}
Add after endforeach; - wp_corenavi();wp_reset_postdata();;
Then jQuery ajax:
//Trigger ajax at the end of page
$(window).scroll(function(){
var top = $('body,html').scrollTop();
var height = $(window).height();
var docheight = $(document).height();
var screen = Number(docheight) - Number(height);
if( top >= screen ){
$('#pagination .next').click();
}
});
//do ajax on pagination
$('#pagination .next').on('click',function(e){
e.preventDefault();
$('#pagination').remove();
$.ajax({
type: "GET",
url: $(this).attr('href'),
dataType: "html",
success: function(out){
//We get blocks from next page , change selector to yours
result = $(out).find('.short-articles-wrapper-main .short-article');
//find next page pagination,change selector to yours
pagination = $(out).find('.short-articles-wrapper-main #pagination');
//append blocks from next page to current ,change selector to yours
$('.short-articles-wrapper-main').append(result);
//append pagination from next page to current, change selector to yours
$('.short-articles-wrapper-main').append(pagination.fadeIn(200));
}
});
});
Hope it will help you.
I'm using the starter theme Sage to create a custom Wordpress Theme. I made a very simple infinite scroll system to display every posts. On that point, everything seems to work fine.
Now, I have to display an advertisement block each N posts in the loop. At first sight, it seemed pretty easy, but unfortunately, it was not.
My system works this way :
When the blog page is displayed, the firsts N posts are shown. In that template (Template 1), in the loop, I call a method to check if I have to display an advertisement.
When the user starts to scroll, the next N posts are loaded with AJAX. So, JS calls a Wordpress action which loads the next posts and call the appropriate template (Template 2). In that template, I check again how many posts have passed and if I have to display an advertisement.
Counting informations are stocked in session variables.
The problem is this one :
When the page is loaded, everything is fine. When the infinite scroll operates for the first time, it still fine. But, when the system is called once again, the counting informations stocked in variables session are not good. They take the previous values like if the session variables were not incremented.
At first time, I used some static attributes and a static method but it didn't work. So, I thought it was because the script was not call at once and I used global variables. But it didn't work either.
It seems that the counting works fine but every time the template called by AJAX is loaded, the session variables are reset to their previous values, like if they were late.
Here are the files that I use :
Template 1, it's the index.php of the theme
Template 2, the file called by AJAX
Ajax functions, which contains all the AJAX actions I need in Wordpress
Advertisement Controller, which contains every method relative to the advertisements blocks
A JS file with the different AJAX queries.
Can somebody tell what I am doing wrong? It will be much appreciated.
Please, find my code below:
Template 1
/****************************************/
/********** TEMPLATE 1 - INDEX **********/
/****************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
$_SESSION['globalCountAds'] = 0;
$_SESSION['globalArrayAds'] = '';
$_SESSION['globalCountPosts'] = 1;
get_template_part('templates/page', 'header');
while (have_posts()) {
the_post();
get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format());
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Template 2
/**************************************************/
/********** TEMPLATE 2 - CALLDED BY AJAX **********/
/**************************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
while (have_posts()) {
the_post();
get_template_part( 'templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format() );
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Advertisement Controller
/**********************************************/
/********** ADVERTISEMENT CONTROLLER **********/
/**********************************************/
namespace Roots\Sage\ThemeAdvertisementController;
use Roots\Sage\ThemeViewController;
use Roots\Sage\ThemePostController;
class AdvertisementController {
public function __construct() {
}
private function getTheAds() {
$PostController = new ThemePostController\PostController();
$postType = 'advertisement';
$nbPosts = -1;
$status = 'publish';
$orderBy = 'title';
$order = 'ASC';
$meta = '';
$taxQuery = '';
$metaQuery = array(
array(
'key' => 'advertisement_in_news',
'value' => true,
'compare' => '='
)
);
return $PostController->getThePosts( $postType, $nbPosts, $status, $orderBy, $order, $meta, $taxQuery, $metaQuery );
}
private function displayTheAd() {
$ViewController = new ThemeViewController\ViewController();
$theAdsArray = $_SESSION['globalArrayAds'];
$theGlobalCountAds = $_SESSION['globalCountAds'];
$thePostID = $theAdsArray->posts[ $theGlobalCountAds ]->ID;
if ( !empty( $thePostID ) ) {
$_SESSION['globalCountAds']++;
$ViewController->postID = $thePostID;
$ViewController->postType = 'advertisement';
$ViewController->nbPosts = 1;
$ViewController->status = 'publish';
$ViewController->orderBy = 'ID';
$ViewController->order = 'ASC';
$ViewController->meta = '';
$ViewController->taxQuery = '';
return $ViewController->displayAdvertisementBlock();
} else {
return false;
}
}
public function getTheLoopAds() {
$arrayAds = $_SESSION['globalArrayAds'];
$adsCount = $_SESSION['globalCountAds'];
$postCount = $_SESSION['globalCountPosts'];
$_SESSION['globalCountPosts']++;
if ( empty( $arrayAds ) ) {
$theAds = $this->getTheAds();
$_SESSION['globalArrayAds'] = $theAds;
}
if ( $postCount%2 == 0 && $postCount != 0 ) {
$displayedAd = $this->displayTheAd();
if ( $displayedAd ) {
return $displayedAd;
} else {
return false;
}
} else {
return false;
}
}
}
Ajax functions
/************************************/
/********** AJAX FUNCTIONS **********/
/************************************/
function infinitePaginateAjax() {
$paged = $_POST['paged'];
$postsPerPage = get_option('posts_per_page');
$args = array( 'paged' => $paged,
'post_status' => 'publish',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
query_posts( $args );
get_template_part('templates/loop-news');
exit;
}
add_action( 'wp_ajax_infinitePaginateAjax','infinitePaginateAjax' );
add_action( 'wp_ajax_nopriv_infinitePaginateAjax','infinitePaginateAjax' );
function getNbPostsPerPageAjax() {
$value = array();
$nbPostsPerPage = get_option('posts_per_page');
if ( !empty( $nbPostsPerPage ) ) {
$value['answer'] = 1;
$value['value'] = $nbPostsPerPage;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
add_action( 'wp_ajax_nopriv_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
function getTotalPostsAjax() {
global $wp_query;
$value = array();
$nbPosts = wp_count_posts( 'post' );
$nbPublishedPosts = $nbPosts->publish;
if ( !empty( $nbPublishedPosts ) ) {
$value['answer'] = 1;
$value['value'] = $nbPublishedPosts;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getTotalPostsAjax','getTotalPostsAjax' );
add_action( 'wp_ajax_nopriv_getTotalPostsAjax','getTotalPostsAjax' );
JS
jQuery(document).ready(function() {
var pageInfinite = '.infinite-page';
var loaderInfinite = '.infinite-loader';
var contentInfinite = '.main-content';
var getTotalPosts = function() {
var totalPosts = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getTotalPostsAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
totalPosts = data.value;
} else {
totalPosts = 0;
}
},
error: function () {
console.log( 'error: cannot get nb posts' );
totalPosts = 0;
}
});
return totalPosts;
};
var getNbPostsPerPage = function() {
var postsPerPage = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getNbPostsPerPageAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
postsPerPage = data.value;
} else {
postsPerPage = 0;
}
},
error: function () {
console.log( 'error: cannot get max posts page' );
postsPerPage = 0;
}
});
return postsPerPage;
};
var infiniteLoadArticle = function( pageNumber ) {
jQuery( loaderInfinite ).show( 'fast' );
setTimeout(function(){
jQuery.ajax({
type:'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url: data_sage_js.ajaxurl,
data: {
action: 'infinitePaginateAjax',
paged: pageNumber
},
success: function( html ) {
jQuery( loaderInfinite ).hide( 'fast' );
jQuery( contentInfinite ).append( html);
}
});
}, 1000);
return false;
};
if ( jQuery( pageInfinite ).length > 0 ) {
var postsTotal = parseInt( getTotalPosts() );
var incPost = parseInt( getNbPostsPerPage() );
var postsCount = parseInt( incPost );
var nbPage = parseInt( 1 );
var nbTotalPage = parseInt( Math.ceil( postsTotal / incPost ) );
jQuery(window).scroll(function() {
if ( jQuery(window).scrollTop() === jQuery(document).height() - jQuery(window).height() ) {
if ( nbTotalPage > nbPage ) {
nbPage++;
infiniteLoadArticle( nbPage );
postsCount = postsCount + incPost;
} else if ( nbTotalPage <= nbPage ) {
return false;
}
}
});
}
});
EDIT/SOLVE
So, after hours of searching, I decided to do it another way : I decided to use the "posts_per_page" attribute to count posts and to know when I have to display an advertisement. I just had to refactor a few functions and methods.
Do session variables work outside of the Ajax Calls? on page refresh etc.
If they do not then it may be to do with the fact that wordpress can treat session variables very weirdly.
I think its for security but if in your php.ini if 'register_globals' is on it unregisters all of the php globals.
Reference: WP_unregister_GLOBALS
In which case I believe things like https://wordpress.org/plugins/wp-session-manager/ fill in the blanks for this, or you could turn off register_globals in your php.ini (although I dont understand the repercussions of doing that sorry
Sorry, I think I read every post about this but cant get it to work.
I have a Wordpress custom post typ called "external" and I would like to show both the post from "external" aswell as my normal standard posts at the same time on my homepage.
This is my loop:
<?php
get_header();
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata(); endif; ?>
How can I include the "external" posts in this code?
The theme then uses blocks to display content on the startpage, here is block8.php with a post query.
function block_eight_ajax_query($atts='') {
$args = array (
$is_ajax = 0;
if($atts==''){
$is_ajax=1;
$atts=$_GET;
if($atts['global_query']){
unset($atts['no_found_rows']);
unset($atts['suppress_filters']);
unset($atts['cache_results']);
unset($atts['update_post_term_cache']);
unset($atts['update_post_meta_cache']);
unset($atts['nopaging']);
}
}
$atts['is_ajax'] = $is_ajax;
$query = null;
$query = new WP_Query( $atts );
$html = '';
if ( $query->have_posts() ) {
ob_start();
$i = 1;
while ( $query->have_posts() ):
$query->the_post();
$atts['video'] = rd_field( 'abomb_post_video' );
$atts['extern'] = rd_field( 'extern' );
$atts['audio'] = rd_field( 'abomb_post_audio' );
$atts['gallery'] = rd_field( 'abomb_post_gallery' );
$atts['counter'] = $i;
block_grid_content($atts);
if ($atts['column'] == 'grid-12') { $divide = 1; }
else if ($atts['column'] == 'grid-3') { $divide = 4; }
else if ($atts['column'] == 'grid-4') { $divide = 3; }
else { $divide = 2; }
if ($i%$divide==0 && $divide!=1) {
echo '<div class="clear"></div>';
}
$i++;
endwhile;
if ($atts['nav'] == 'numbered') {
echo '<div class="grid-12">';
rd_pagination($query->max_num_pages);
echo '</div>';
}
wp_reset_postdata();
$html = ob_get_clean();
if($is_ajax==1){
echo $html;
exit();
}
return $html;
}
else{
if($is_ajax==1){
echo '-11';
exit();
}
return '';
}
}
Update: I added this code to functions:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'extern' ) );
return $query;
}
Now I can see the posts in for exampel the search result but I need the Query in Block8.php to fetch them aswell.
I Thanks!
To include a custom post type in the regular loop (ie. posts page) just add the following code to index.php before if ( have_posts() ) :
$args = array(
'post_type' => array('post', 'custom_post_type'),
'post_status' => 'publish',
);
$new_post_loop = new WP_Query( $args );
then modify the following two lines:
if ( have_posts() ) : change it to if ( $new_post_loop -> have_posts() ) :
and
while ( have_posts() ) : the_post(); to while ( $new_post_loop -> have_posts() ) : $new_post_loop -> the_post();
This solution avoids the problem of having the custom post type listed in the all posts screen on the backend, which #David.J's answer produces ;)
Add this to your functions.php file.
/**
* #param WP_Query $query
* #return WP_Query
*/
function add_my_custom_post_type( $query ) {
if ($query->is_main_query())
$query->set( 'post_type', array( 'post', 'external' ) );
return $query;
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );
Ref & duplicate: https://wordpress.stackexchange.com/questions/27104/how-to-display-regular-posts-custom-post-types-that-fall-under-a-category-usin
function add_my_custom_post_type( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
if ($query->is_main_query()) {
$query->set( 'post_type', array( 'post', 'some_custom_post_type_name' ) );
}
return $query;
}
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );
This is the correct way to write the code so as not to break the dashboard queries.
I have tried to implement the approved answer from here: Adding jQuery TouchSwipe to prettyPhoto to accomplish using touchwipe with prettyphoto.
The site is in wordpress and I have called the touchwipe javascript properly and added the code from the link above in my page.php with in script tags.
For some reason though I cannot get it to work.
Here is my code from page.php
<?php
get_header();
$no_feat_class = '';
if( !options::logic( 'blog_post' , 'enb_featured' ) || !
has_post_thumbnail( $post -> ID ) ){
$no_feat_class = ' no_feat ';
}
$post_id = $post -> ID;
/*---------------------*/
$post_format = get_post_format( $post -> ID );
if(!strlen($post_format)){ $post_format = 'standard';}
?>
<script>
$(document).ready(function(){
function setupBox() {
$("a[rel^='prettyPhoto']").prettyPhoto({
social_tools: false,
theme:'dark_rounded',
changepicturecallback: function() {
setupSwipe();
}
});
}
function setupSwipe() {
$(".pp_hoverContainer").touchwipe({
wipeLeft: function() {
$.prettyPhoto.changePage('next');
},
wipeRight: function() {
$.prettyPhoto.changePage('previous');
},
min_move_x: 20,
min_move_y: 20,
preventDefaultEvents: true
});
}
setupBox();
});
</script>
<section id="main">
<div class="main-container">
<?php
while( have_posts () ){
the_post();
$meta = meta::get_meta( $post -> ID, 'settings' );
$meta_enb = options::logic( 'blog_post' , 'meta' );
} /*EOF while( have_posts () ) */
?>
<?php
$resizer = new LBPageResizer('page');
$resizer -> render_frontend();
?>
</div>
</section>
<?php get_footer(); ?>
Have I done something wrong?