Exclude current post from the output - php

I have written a Wordpress widget that displays a custom amount of posts from a custom tag (feel free to use it). Here is the code:
<?php
$category = get_the_category();
$current_category = $category[0]->term_id;
?>
<?php query_posts("showposts=".$posts_number."&cat=".$current_category."&tag=featured"); // the tag
if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="block-post clearfix">
<?php
$thumb = '';
$width = 287;
$height = 162;
$classtext = 'post-image';
$titletext = get_the_title();
$thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Recent');
$thumb = $thumbnail["thumb"];
?>
<?php if($thumb <> '' && get_option('aggregate_thumbnails_index') == 'on') { ?>
<div class="thumb">
<a href="<?php the_permalink(); ?>">
<?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>
<span class="overlaybig"></span>
</a>
</div> <!-- end .post-thumbnail -->
<?php } ?>
<div class="recenttitle"><h3 class="title"><?php the_title(); ?></h3></div>
</div> <!-- end .block-post -->
<?php endwhile; endif; wp_reset_query(); ?>
My question is, how can I exclude the current post from the output? The problem is that it does not check if the user is currently viewing any of the posts that it outputs. How can I adjust the code so that it skips the current post that the user is on?
I am pretty sure that this is an easy fix, but I am lost at the moment.
UPDATE: Here is the code for the entire widget, including the fix provided by maiorano84:
<?php class ArtificePinned extends WP_Widget
{
function ArtificePinned(){
$widget_ops = array('description' => 'Displays posts filtered by current category and the tag pinned');
$control_ops = array('width' => 400, 'height' => 300);
parent::WP_Widget(false,$name='Artifice Pinned',$widget_ops,$control_ops);
}
/* Displays the Widget in the front-end */
function widget($args, $instance){
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? ' ' : $instance['title']);
$posts_number = empty($instance['posts_number']) ? '' : (int) $instance['posts_number'];
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
?>
<?php
$category = get_the_category();
$current_category = $category[0]->term_id;
$qarr = array(
'posts_per_page' => $posts_number,
'cat' => $current_category,
'tag' => 'featured',
'post__not_in' => get_the_ID()
);
$q = new WP_Query($qarr);
if($q->have_posts()) : while ($q->have_posts()) : $q->the_post();
?>
<div class="block-post clearfix">
<?php
$thumb = '';
$width = 287;
$height = 162;
$classtext = 'post-image';
$titletext = get_the_title();
$thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Recent');
$thumb = $thumbnail["thumb"];
?>
<?php if($thumb <> '' && get_option('aggregate_thumbnails_index') == 'on') { ?>
<div class="thumb">
<a href="<?php the_permalink(); ?>">
<?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>
<span class="overlaybig"></span>
</a>
</div> <!-- end .post-thumbnail -->
<?php } ?>
<div class="recenttitle"><h3 class="title"><?php the_title(); ?></h3></div>
</div> <!-- end .block-post -->
<?php endwhile; endif;?>
<?php
echo $after_widget;
}
/*Saves the settings. */
function update($new_instance, $old_instance){
$instance = $old_instance;
$instance['title'] = stripslashes($new_instance['title']);
$instance['posts_number'] = (int) $new_instance['posts_number'];
return $instance;
}
/*Creates the form for the widget in the back-end. */
function form($instance){
//Defaults
$instance = wp_parse_args( (array) $instance, array('title'=>' ', 'posts_number'=>'7') );
$title = esc_attr($instance['title']);
$posts_number = (int) $instance['posts_number'];
# Title
echo '<p><label for="' . $this->get_field_id('title') . '">' . 'Title:' . '</label><input class="widefat" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" type="text" value="' . $title . '" /></p>';
# Number Of Posts
echo '<p><label for="' . $this->get_field_id('posts_number') . '">' . 'Number of Posts:' . '</label><input class="widefat" id="' . $this->get_field_id('posts_number') . '" name="' . $this->get_field_name('posts_number') . '" type="text" value="' . $posts_number . '" /></p>';
# Category ?>
<?php
}
}// end ArtificePinned class
function ArtificePinnedInit() {
register_widget('ArtificePinned');
}
add_action('widgets_init', 'ArtificePinnedInit');
?>

Don't use query_posts, as its intention is to modify the default Wordpress Loop. Use WP Query instead.
To answer your question, the solution is pretty simple. I've taken the liberty of giving you this example using WP_Query:
<?php
$qarr = array(
'posts_per_page' => $posts_number,
'cat' => $current_category,
'tag' => 'featured',
'post__not_in' => get_the_ID()
);
$q = new WP_Query($qarr);
if($q->have_posts()) : while ($q->have_posts()) : $q->the_post();
?>
Bear in mind, I've also changed 'showposts' to 'posts_per_page', as showposts was deprecated in version 2.1
UPDATE: Your code should now look like this:
<?php
$category = get_the_category();
$current_category = $category[0]->term_id;
$qarr = array(
'posts_per_page' => $posts_number,
'cat' => $current_category,
'tag' => 'featured',
'post__not_in' => get_the_ID()
);
$q = new WP_Query($qarr);
if($q->have_posts()) : while ($q->have_posts()) : $q->the_post();
?>
<div class="block-post clearfix">
<?php
$thumb = '';
$width = 287;
$height = 162;
$classtext = 'post-image';
$titletext = get_the_title();
$thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Recent');
$thumb = $thumbnail["thumb"];
?>
<?php if($thumb <> '' && get_option('aggregate_thumbnails_index') == 'on') { ?>
<div class="thumb">
<a href="<?php the_permalink(); ?>">
<?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>
<span class="overlaybig"></span>
</a>
</div> <!-- end .post-thumbnail -->
<?php } ?>
<div class="recenttitle"><h3 class="title"><?php the_title(); ?></h3></div>
</div> <!-- end .block-post -->
<?php endwhile; endif;?>
FIX:
The problem is stemming from this:
'post__not_in' => get_the_ID()
The problem is 'post__not_in' expects an array. Not an integer. My apologies, that was my mistake. Please change that line of code to:
'post__not_in' => array(get_the_ID())
and you should be good.

Related

the load more ajax button in wordpress loads already displayed posts, instead of new ones

I'm trying to display a list of "hot" products on the main page. by default, 4 products are displayed and 2 new products must be loaded using the "load more" button. when you click on the button, the first line is duplicated with the first two products instead of two new ones.
link to the website
front-page.php
<div class="hot__items" id="ajax-container">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'post_status' => 'publish',
'meta_key' => 'hot',
'meta_value' => true
);
$products = new WP_Query($args);
$max_pages = $products->max_num_pages;
if($products->have_posts()) : ?>
<?php
$pcount = count( $products->posts );
while($products->have_posts()): $products->the_post();
$mainphoto = get_field("main_foto");
$get_image_id = $mainphoto[id];
$image_link = wp_get_attachment_image_url($get_image_id, "full");
$logo = get_field("logo_tovar");
$get_logo_id = $logo[id];
$logo_link = wp_get_attachment_image_url($get_logo_id, "full");
?>
<div class="hot__item">
<a href="<?php the_permalink( $post ); ?>" title="<?php the_title(); ?>">
<?php if( get_field("hot_comment") ): ?>
<div class="hot_comment red-color"> <span></span> <?php the_field( "hot_comment" ); ?> </div>
<?php endif; ?>
<div class="hot__imgs">
<!--<img src="<?php echo $image_link;?>" alt="" class="hot__img">-->
<!--<img src="<?php echo $logo_link;?>" alt="" class="hot__logo">-->
<div class="item-fix-height fix-height_on-front">
<div class="scale_block_animate csomor-image-zoom" style="background-image: url('<?php echo $image_link;?>');"></div>
</div>
</div>
<div class="hot__text">
<div class="hot__text_title">
<p class="hot__name"><?php the_title(); ?></p>
<?php if( get_field("model") ): ?>
</div>
<div class="hot__text_about">
<p class="hot__model"><b>Модель: </b><span class="red-color"><?php the_field( "model" ); ?></span></p>
<?php endif; ?>
<div class="hot__descr">
<?php if( have_rows('harakteristiki_small') ):?>
<div class="subsection__chtitle">Характеристики</div>
<ul class="subsection__chlist">
<?php while( have_rows('harakteristiki_small')): the_row();?>
<li class="subsection__chitem__on_front_page">
<span class="subsection__chvar"><?php the_sub_field('har_title');?> </span>
<span class="subsection__chval"><?php the_sub_field('har_value');?></span>
</li>
<?php endwhile;?>
</ul>
<?php endif; ?>
</div>
<div class="hot__bottom">
<!--Отправить запрос-->
<ul class="hot__infos">
<!-- <?php if( get_field("nalichie") ): ?>
<li class="hot__info">
Наличие:
<span class="red-color"><?php the_field( "nalichie" ); ?></span>
</li>
<?php endif; ?>
<?php if( get_field("garantiya") ): ?>
<li class="hot__info">
Гарантия:
<span class="red-color"><?php the_field( "garantiya" ); ?></span>
</li>
<?php endif; ?> -->
<?php if( get_field("cena") ): ?>
<li class="hot__info hot__price">
Цена:
<span class="red-color hot-price"><?php the_field( "cena" ); ?></span>
</li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
</a>
</div>
<?php
endwhile;?>
<?php
if($max_pages > 1){ ?>
<a id="load-more-products" href="#" class="good__btn" data-page="2">Смотреть еще</a>
<?php }?>
<?php wp_reset_postdata();
endif;?>
</div>
functions.php
function get_hot_products() {
global $post;
$paged = $_POST['paged'] ? $_POST['paged'] : 1;
$return_html = '';
$args = array(
'post_type' => 'product',
'posts_per_page' => 2,
'post_status' => 'publish',
'meta_key' => 'hot',
'meta_value' => true
);
$products = new WP_Query($args);
$max_pages = $products->max_num_pages;
if ($products->have_posts()):
while ($products->have_posts()): $products->the_post();
$mainphoto = get_field("main_foto");
$get_image_id = $mainphoto[id];
$image_link = wp_get_attachment_image_url($get_image_id, "full");
$logo = get_field("logo_tovar");
$get_logo_id = $logo[id];
$logo_link = wp_get_attachment_image_url($get_logo_id, "full");
$title = get_the_title();
$permalink = get_the_permalink();
$cena = get_field("cena");
$return_html .= '<div class="hot__item"><a href="' . $permalink . '" title="' . title . '">';
if( get_field("hot_comment") ):
$hot_comment = get_field( "hot_comment" );
$return_html .= '<div class="hot_comment red-color"> <span></span>' . $hot_comment . '</div> ';
endif;
$return_html .='<div class="hot__imgs"><div class="item-fix-height fix-height_on-front"><div class="scale_block_animate csomor-image-zoom" style="background-image: url(' . $image_link . ');"></div></div></div>';
$return_html .='<div class="hot__text">';
$return_html .='<div class="hot__text_title"><p class="hot__name">' . $title . '</p></div>';
$return_html .='<div class="hot__text_about">';
if( get_field("model") ):
$model = get_field( "model" );
$return_html .= '<p class="hot__model"><b>Модель: </b><span class="red-color">' . $model . '</span></p>';
endif;
$return_html .='<div class="hot__descr">';
if( have_rows('harakteristiki_small') ):
$return_html .='<div class="subsection__chtitle">Характеристики</div><ul class="subsection__chlist">';
while( have_rows('harakteristiki_small')): the_row();
$har_title = get_sub_field( "har_title" );
$har_value = get_sub_field( "har_value" );
$return_html .='<li class="subsection__chitem__on_front_page"><span class="subsection__chvar">' . $har_title . '</span><span class="subsection__chval">' . $har_value . '</span></li>';
endwhile;
$return_html .='</ul>';
endif;
$return_html .='<div class="hot__bottom"><ul class="hot__infos"><li class="hot__info hot__price">Цена:<span class="red-color hot-price">' . $cena . '</span></li></ul></div>';
$return_html .='</div>';
$return_html .= '</div></div></a></div>';
endwhile;
endif;
if ($paged < $max_pages) { // if the current page is less than the total number of pages, then we display the button for loading
$next_page = $paged + 1; // in the date attributes of the button, we pass the number of the next page and the id of the current terms
$return_html .= '<a id="load-more-products" href="#" class="good__btn grey-bg" data-page="'. $next_page .'">Смотреть ещё</a>';
}
wp_reset_postdata();
echo $return_html; // returning the html code
wp_die(); // "die"
}
add_action('wp_ajax_get_hot_products', 'get_hot_products');
add_action('wp_ajax_nopriv_get_hot_products', 'get_hot_products');
You are getting the paged value from the query string, but you're not passing it into the WP_Query args, so it's always grabbing the first ones.
$paged = $_POST['paged'] ? $_POST['paged'] : 1;
$return_html = '';
$args = array(
'post_type' => 'product',
'posts_per_page' => 2,
---> 'paged' => $paged,
'post_status' => 'publish',
'meta_key' => 'hot',
'meta_value' => true
);
I solved the problem by putting the output of 4 products instead of 2. But this is not quite the right decision. At the moment it is suitable, since I have only 8 "hot products" on the site
'posts_per_page' => 4,

How to add Pagination to a blog page in Wordpress

I need to insert a pagination to the post instead of the load more button and I don't know how how to do it. I require pagination of Next & Previous or numbers.
Here's our dev work, but I don't know where to start or where I should put this example.
<?php
/*
* Template Name: Blog
* description: >-
Page template without sidebar
*/
get_header(); ?>
<body class=" pageHeader--gray">
<div class="wrapper">
<div class="content">
<div class="pageHeader">
<div class="container animate">
<h1 class="pageHeader__title"><?php the_field('title'); ?>
</h1>
</div>
<div class="pageHeader__background">
<svg xmlns="http://www.w3.org/2000/svg" width="1920" viewBox="0 0 1920 126">
<path fill="#FFF" fill-rule="evenodd" d="M9.09494702e-13,7.95807864e-13 L1920,7.95807864e-13 L1920,22.1174168 C1622.41146,91.3724723 1302.41146,126 960,126 C617.588542,126 297.588542,91.3724723 9.09494702e-13,22.1174168 L9.09494702e-13,7.95807864e-13 Z" transform="rotate(180 960 63)"></path>
</svg>
</div>
<div class="pageHeader__decor animate animate--wrapper">
<div class="pageHeader__decor-1 animate__child">
</div>
<div class="pageHeader__decor-2 animate__child">
</div>
</div>
</div>
<div class="blog">
<div class="container">
<div class="blog__tags animate">
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
$active = "";
if ( null == #$_GET['category_id'] ) {
$active = "active";
}
echo '<a class="blog__tag '.$active.'" href="'. site_url() .'/blog">All Categories</a>';
foreach( $categories as $category ) {
$active = "";
if ( $category->name == #$_GET['category_id']) {
$active = "active";
}
echo '<a class="blog__tag '.$active.'" href="'. site_url() .'/blog?category_id='.$category->name.'">'.$category->name.'</a>';
}
?>
</div>
<div class="blog__wrapper">
<?php
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1,
'category_name' => #$_GET['category_id']
);
$sticky_query = new WP_Query( $args );
while ( $sticky_query->have_posts() ) : $sticky_query->the_post();
?>
<a class="newsCard newsCard--big animate" href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail( get_the_ID() ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'single-post-thumbnail' ); ?>
<div class="newsCard__image"><img src="<?php echo $image[0]; ?>" alt=""/></div>
<?php endif; ?>
<div class="newsCard__content">
<div class="newsCard__tag">
<?php
$categories="";
foreach((get_the_category()) as $category){
$categories = $category->name.",";
}
echo substr($categories, 0, -1);
?>
</div>
<div class="newsCard__title"><?php the_title(); ?>
</div>
<div class="newsCard__description"><?php the_excerpt(); ?>
</div>
<div class="newsCard__link">Learn more
<div class="newsCard__link-icon">
</div>
</div>
</div>
</a>
<?php
endwhile;
wp_reset_postdata();
?>
<?php
$load = 0;
$total_post =wp_count_posts()->publish;
if (null !== #$_GET['load']){
$load = $_GET['load'];
}
$i = 6 + $load;
?>
<?php
// the query
$wpb_all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>$i,
'ignore_sticky_posts' => 1,
'category_name' => #$_GET['category_id']
));
$count = $wpb_all_query->found_posts;
?>
<?php if ( $wpb_all_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?>
<a class="newsCard newsCard animate" href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail( get_the_ID() ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'single-post-thumbnail' ); ?>
<div class="newsCard__image"><img src="<?php echo $image[0]; ?>" alt=""/></div>
<?php endif; ?>
<div class="newsCard__content">
<div class="newsCard__tag">
<?php
$categories="";
foreach((get_the_category()) as $category){
$categories = $category->name.",";
}
echo substr($categories, 0, -1);
?>
</div>
<div class="newsCard__title"><?php the_title(); ?>
</div>
<div class="newsCard__description"><?php the_excerpt(); ?>
</div>
<div class="newsCard__link">Learn more
<div class="newsCard__link-icon">
</div>
</div>
</div>
</a>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</div>
<?php if( null == #$_GET['load'] && $count > 6 ) : ?>
<div class="blog__button animate">
<?php
if ( null == #$_GET['category_id'] ) {
?>
<a class="btn" href="<?php echo site_url(); ?>/blog?load=<?php echo $load + $total_post; ?>"><?php the_field('load_more_button_label'); ?></a>
<?php
} else {
?>
<a class="btn" href="<?php echo site_url(); ?>/blog?category_id=<?php echo $_GET['category_id']; ?>&load=<?php echo $load + $total_post; ?>"><?php the_field('load_more_button_label'); ?></a>
<?php
}
?>
</div>
<?php endif; ?>
</div>
</div>
<div class="achievments">
<div class="container">
<div class="blockTitle blockTitle--center blockTitle--small">
<h2><?php the_field('achievement_title'); ?></h2>
</div>
<div class="rewardsCards2 animate animate--wrapper">
<?php
// the query
$wpb_all_query = new WP_Query(array(
'post_type'=>'achievement_cpt',
'post_status'=>'publish',
'posts_per_page'=>-1,
// 'ignore_sticky_posts' => 1,
// 'meta_key' => 'departament',
// 'meta_value' => 'Information Technology and Security'
));
?>
<?php if ( $wpb_all_query->have_posts() ) : ?>
<?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?>
<div class="rewardsCards2__item animate__child"><img src="<?php echo get_field('image', get_the_ID()); ?>" alt=""/>
<div class="rewardsCards2__tooltip">
<div class="rewardsCards2__tooltip-logo"><img src="<?php echo get_field('image', get_the_ID()); ?>" alt=""/>
</div>
<div class="rewardsCards2__tooltip-content">
<div class="rewardsCards2__tooltip-title"><?php echo get_field('title', get_the_ID());?>
</div>
<div class="rewardsCards2__tooltip-description"><?php echo get_field('content', get_the_ID());?>
</div><a class="rewardsCards2__tooltip-link" href="<?php echo get_field('url',get_the_ID());?>">Read More</a>
</div>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer('phone'); ?>
</div>
</body>
<?php get_footer(); ?>
So I'm not going to repeat what's already said in the article, but I hope these help you:
Remove the $load (or $_GET['load']) and $i part:
// Find and remove this:
$load = 0;
$total_post =wp_count_posts()->publish;
if (null !== #$_GET['load']){
$load = $_GET['load'];
}
$i = 2 + $load;
Add paged in the first // the query. We also set a static posts_per_page, although you may make it dynamic later.
// Find and replace this:
// the query
$wpb_all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>$i,
'ignore_sticky_posts' => 1,
'category_name' => #$_GET['category_id'],
));
$count = $wpb_all_query->found_posts;
// With this one:
// the query
$wpb_all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
// Set a static posts_per_page value.
'posts_per_page'=> 6,
'ignore_sticky_posts' => 1,
'category_name' => #$_GET['category_id'],
// Add the "paged" arg.
'paged' => max( get_query_var( 'paged' ), 1 ),
));
// The $count is not needed (anymore).
After that, find and replace this:
<?php if( null == #$_GET['load'] && $count > 6 ) : ?>
<div class="blog__button animate">
<?php
if ( null == #$_GET['category_id'] ) {
?>
<a class="btn" href="<?php echo site_url(); ?>/blog?load=<?php echo $load + $total_post; ?>"><?php the_field('load_more_button_label'); ?></a>
<?php
} else {
?>
<a class="btn" href="<?php echo site_url(); ?>/blog?category_id=<?php echo $_GET['category_id']; ?>&load=<?php echo $load + $total_post; ?>"><?php the_field('load_more_button_label'); ?></a>
<?php
}
?>
</div>
<?php endif; ?>
With one of the following, whichever you prefer (either simple or numerical pagination):
1) Simple previous-and-next Pagination
Here, we are using previous_posts_link() and next_posts_link().
<?php
if ( $wpb_all_query->max_num_pages > 1 ) :
$paged = max( get_query_var( 'paged' ), 1 );
?>
<div class="simple-pagination"><?php
previous_posts_link( '← Older Posts' );
if ( $paged > 1 && $paged < $wpb_all_query->max_num_pages ) {
echo ' <span class="sep">•</span> ';
}
next_posts_link( 'Newer Posts →', $wpb_all_query->max_num_pages );
?></div>
<?php endif; ?>
2) Numerical Pagination
Here, we are using paginate_links() — please check the function reference for more details on the parameters.
<?php
$links = paginate_links( array(
'total' => $wpb_all_query->max_num_pages,
'prev_text' => '← Older Posts',
'next_text' => 'Newer Posts →',
) );
if ( $links ) {
echo "<div class='numeric-pagination'>$links</div>";
}
?>
Two important things to note:
In your new WP_Query() call, the args need to have the paged arg so that WordPress knows the current page number and then retrieves only the posts for that specific page.
With next_posts_link() and paginate_links(), you need to pass the $wpb_all_query->max_num_pages which is the total number of pages for your custom WordPress query (WP_Query).
That's all, and once again, I hope this answer helps and note that I used only basic HTML in my examples above, so just modify it to your liking.
Paste this code in functions.php
<?php
//Custom pagination
function the_pagination() {
if( is_singular() )
return;
global $wp_query;
/** Stop execution if there's only 1 page */
if( $wp_query->max_num_pages <= 1 )
return;
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$max = intval( $wp_query->max_num_pages );
/** Add current page to the array */
if ( $paged >= 1 )
$links[] = $paged;
/** Add the pages around the current page to the array */
if ( $paged >= 3 ) {
$links[] = $paged - 1;
$links[] = $paged - 2;
}
if ( ( $paged + 2 ) <= $max ) {
$links[] = $paged + 2;
$links[] = $paged + 1;
}
echo '<ul class="pagination " itemscope itemtype="http://schema.org/SiteNavigationElement/Pagination">' . "\n";
/** Previous Post Link */
if ( get_previous_posts_link() )
printf( ' <li class="page-item">%s</li>
' . "\n", get_previous_posts_link('
<span aria-hidden="true" class="page-link ripple">«</span>
<span class="sr-only">Previous</span>
') );
/** Link to first page, plus ellipses if necessary */
if ( ! in_array( 1, $links ) ) {
$class = 1 == $paged ? ' class="page-item active"' : '';
printf( '<li%s class="page-item">%s</li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
if ( ! in_array( 2, $links ) )
echo '<li>…</li>';
}
/** Link to current page, plus 2 pages in either direction if necessary */
sort( $links );
foreach ( (array) $links as $link ) {
$class = $paged == $link ? ' class="page-item active"' : '';
printf( '<li%s class="page-item">%s</li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
}
/** Link to last page, plus ellipses if necessary */
if ( ! in_array( $max, $links ) ) {
if ( ! in_array( $max - 1, $links ) )
echo '<li>…</li>' . "\n";
$class = $paged == $max ? ' class="page-item active"' : '';
printf( '<li%s class="page-item">%s</li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
}
/** Next Post Link */
if ( get_next_posts_link() )
printf( '<li class="page-item ">%s</li>
' . "\n", get_next_posts_link('<span aria-hidden="true" class="page-link ripple">»</span>
<span class="sr-only">Next</span>') );
echo '</ul>' . "\n";
}
?>
And use <?php the_pagination(); ?> where you want the pagination

WordPress: Display particular category on load with filters

I have a theme with a portfolio that uses filters (ALL, NEW, OLD) to display categories. However, on load, I wish for a particular ("new") category to be the ONLY category displayed.
Then if a user wishes to see past products, they'd click "OLD" and so on..
Please keep in mind that I would create another portfolio and that portfolio's new items would be displayed only on load at first.
I've attempted to find the answer for hours but I have yet to be able to find it.
Here is the code of the portfolio php page:
<?php
/**
* Taxonomy Template for the Portfolios
*/
?>
<?php get_header(); ?>
<?php
if ( $post ) :
$port = wp_get_post_terms( $post->ID, array('portfolios') );
$portfolio = $port[0];
$post_img_width = "";
$post_img_height = "";
global $mav_data; // fetch options stored in $mav_data
$portfolio_order_1 = $mav_data['portfolio_order_1']; // date, title
$portfolio_order_2 = $mav_data['portfolio_order_2']; // ASC, DESC
$tax_query[] = array(
//'taxonomy' => $wp_query->query_vars['taxonomy'],
'taxonomy' => 'portfolios',
'field' => 'slug',
'terms' => array( $portfolio->slug )
);
$args = array(
'post_type'=> 'project',
'posts_per_page'=> -1,
'orderby' => $portfolio_order_1,
'order' => $portfolio_order_2,
'tax_query' => $tax_query
);
$port_query = new WP_Query($args);
?>
<?php
$tag_extra_fields = get_option('portfolios_fields');
$portfolio_layout = $tag_extra_fields[$portfolio->term_id]['_portfolio_layout'];
?>
<section id="content" class="portfolio one-column <?php echo esc_attr( $portfolio_layout ); ?>" role="main">
<div class="wrapper clearfix">
<header class="page-header">
<h1 class="entry-title"><?php echo( $portfolio->name ); ?></h1>
<?php if ($portfolio->description) { ?><p class="portfolio-header-description"><?php echo( $portfolio->description ); ?></p><?php } ?>
<?php
$temp = array();
foreach ( $posts as $post ) {
$temp_args = array();
while ($port_query->have_posts()) : $port_query->the_post(); // the loop begins, we need it here. It's important!!
$temp_cats = wp_get_object_terms( $post->ID, 'project_category'/*, $args*/ );
if ( $temp_cats ) {
foreach ( $temp_cats as $temp_cat ) {
if ( ! in_array( $temp_cat->slug, $temp ) ) {
$temp[] = $temp_cat->slug;
$categories[] = $temp_cat;
}
}
}
endwhile;
}
// DAHEX
$temp = array();
if(!empty($categories)) {
foreach ( $categories as $category ) {
$temp[] = array ('term_id'=>$category->term_id,'name'=>$category->name,'slug'=>$category->slug,'term_group'=>$category->term_group,'term_taxonomy_id'=>$category->term_taxonomy_id,'taxonomy'=>$category->taxonomy,'description'=> $category->description,'parent'=>$category->parent,'count'=> $category->count);
}
}
usort($temp, array(new Sorter('slug'), 'sort')); // Sorting Array by slug
$categories = array();
foreach ( $temp as $category ){
$categories[] =(object) $category;
}
// DAHEX
if(!empty($categories)) {
if(!is_wp_error( $categories )){
echo( '<ul id="filters" class="option-set">
<li>All</li>' );
foreach ( $categories as $category ) {
echo '<li><span class="sep">/</span>' . $category->name . '</li>';
}
echo( '</ul> <!-- /end #filters -->' );
} else {
echo '<span class="ooops">';
_e( 'Ooops! nothing found...', 'mav_framework' );
echo '</span>';
}
}
?>
</header> <!-- /end .page-header -->
<section id="projects">
<?php
while ($port_query->have_posts()) : $port_query->the_post(); // the loop begins
$terms = get_the_terms( get_the_ID(), 'project_category' );
$terms = $terms == false ? array() : $terms;
?>
<?php
$custom = get_post_custom($post->ID);
$portfolio_permalink = $custom["project_permalink"][0];
$portfolio_desc = $custom["project_desc"][0];
if ( !isset( $lightbox_path ) ) {
$lightbox_path = '';
}
// Prepare Project Image Thumb
$project_img = $custom["project_img"][0];
$project_img_ID = $custom['project_img_ID'][0];
// Need some proof check to ensure that no "notice" is thrown ...
if ( ! empty( $portfolio ) ) {
$term_slug = $portfolio->slug;
if ( isset( $custom["lightbox_path"][0] ) ) {
$lightbox_path = $custom["lightbox_path"][0];
} else {
$lightbox_path = '';
}
$empty_thumb = '<img class="portfolios_single_thumb portfolio-image" src="' . get_template_directory_uri() . '/images/thumb.png" width="' . $post_img_width . '" height="' . $post_img_height . '" alt="' . $post->post_title . '" />';
if ( isset( $project_img_ID ) ) {
if ( is_numeric( $project_img_ID ) ) {
$thumb_ID = $project_img_ID;
$thumb = wp_get_attachment_image( $thumb_ID, 'mav-thumbnails', false, array( 'class' => 'portfolios_post_image_thumb portfolio-image', 'alt' => $post->post_title ) );
if ( empty ($thumb) ) {
$thumb = $empty_thumb;
}
} elseif( $project_img_ID != "" ) {
$thumb = '<div class="project_iframe_thumb-$term_slug"><iframe width="' . $post_img_width . '" height="' . $post_img_height . '" src="' . $project_img . '" title="' . $project_img_ID . '" frameborder="0" allowfullscreen></iframe></div>';
} else {
$thumb = $empty_thumb;
}
} else {
$thumb = $empty_thumb;
}
}
?>
<article id="project-<?php the_ID(); ?>" class="element <?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->slug)). ' '; } ?>">
<?php
/**
* Generate the Project Image (Thumb)
*/
if ( $lightbox_path != '' ) { ?>
<figure class="thumb-container">
<a href="<?php echo esc_attr( $lightbox_path ); ?>" data-rel="prettyPhoto" title="<?php the_title_attribute(); ?>">
<span class="overlay lightbox"></span>
<?php mav_framework_project_label( $post, array( 'portfolios-project-label' ) ); ?>
<?php echo( $thumb ); ?>
</a>
</figure> <!-- /end .thumb-container -->
<?php
} elseif ($portfolio_permalink) {
?>
<figure class="thumb-container">
<a target="_blank" href="<?php echo esc_attr( $portfolio_permalink ); ?>" rel="bookmark">
<span class="overlay link"></span>
<?php mav_framework_project_label( $post, array( 'portfolios-project-label' ) ); ?>
<?php echo( $thumb ); ?>
</a>
</figure> <!-- /end .thumb-container -->
<?php } else { ?>
<figure class="thumb-container">
<a href="<?php the_permalink() ?>" rel="bookmark">
<span class="overlay">
<span class="view"><?php _e( 'View', 'mav_framework' ); ?></span>
</span>
<?php mav_framework_project_label( $post, array( 'portfolios-project-label' ) ); ?>
<?php echo( $thumb ); ?>
</a>
</figure> <!-- /end .thumb-container -->
<?php } // end Generate the Project Image (Thumb) ?>
<h2 class="project-title">
<?php if ($portfolio_permalink) { ?>
<a target="_blank" href="<?php echo esc_url( $portfolio_permalink ); ?>" rel="bookmark"><?php the_title(); ?></a>
<?php } else { ?>
<?php the_title(); ?>
<?php } ?>
</h2>
<?php if ($portfolio_desc) { ?><p class="project-description"><?php echo do_shortcode(stripslashes($portfolio_desc)); ?></p><?php } ?>
<footer class="entry-meta">
<span class="posted-on">
<?php _e( '<span class="posted-on-title">Posted on: </span>', 'mav_framework' ); ?><?php /* http://codex.wordpress.org/Formatting_Date_and_Time */ echo get_the_date('F j, Y'); ?>
</span> <!-- /end .posted-on -->
<?php
$project_categories = wp_get_object_terms($post->ID, 'project_category');
if ($project_categories) { ?>
<span class="cat-links">
<?php
_e( '<span class="cat-links-title">Category: </span>', 'mav_framework' );
$project_category = array();
foreach($project_categories as $category) {
$project_category[] = '' . $category->name . '';
}
echo implode(', ', $project_category);
?>
</span> <!-- /end .cat-links -->
<?php } ?>
<?php // Project Tags
$project_tags = wp_get_object_terms($post->ID, 'project_tag');
if ($project_tags) {
$project_tag = array();
foreach($project_tags as $tag) {
$project_tag[] = '' . $tag->name . '';
} ?>
<span class="tag-links">
<?php _e( '<span class="tag-links-title">Tagged: </span>', 'mav_framework' ); ?> <?php echo implode(', ', $project_tag); ?>
</span> <!-- /end .tag-links -->
<?php } ?>
</footer> <!-- /end .entry-meta -->
</article> <!-- /end #project-<?php the_ID(); ?> .element -->
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</section> <!-- /end #projects -->
</div> <!-- /end .wrapper -->
</section> <!-- /end #content -->
<?php endif; ?>
<?php
/**
* Add portfolio bottom quote
*/
if ( $mav_data['portfolio_quote_text'] ) : ?>
<section id="portfolio-quote" class="clearfix">
<div class="wrapper clearfix">
<?php get_template_part( 'inc/block_portfolio_quote' ); ?>
</div> <!-- /end .wrapper -->
</section> <!-- /end #portfolio-quote -->
<?php endif; ?>
<?php get_footer(); ?>
This problem is not related with the Wordpress itself but with the plugin that you, or your theme are using to sort the data.
In this case, it's using Isotope, which is what is filtering the results you see on the page.
By addressing the Isotope's documentation in terms of filtering, we see that the filters can be done through functions or buttons, in this case we're using a combination of both as we want the data to change while clicking but at the same time it already needs to come filtered, as you requested.
So, to solve the problem, it's one line in the isotope's function file:
$container.isotope({
itemSelector : '.element',
filter: '.workshops'
});
I just added the last one.
Apart from this, you just need to hack the code you provided in order to add the "selected" class to the button:
echo( '<ul id="filters" class="option-set">
<li>All</li>' );
foreach ( $categories as $category ) { ?>
<li>
<span class="sep">/</span>
<?php echo $category->name;?>
</li>
<?php
}
echo( '</ul>' );
Now some considerations:
If you change the slug, this will stop working as it's checking for the class "workshops", if you do it, you need to edit the code provided above;
Isotope was masked inside your theme's custom jquery file, which is not a good practice at all, specially for maintenance issues.

return in shortcode wordpress

I have this code for displaying a shortcode.
<?php
function recent_posts_function() {
$mypost = array( 'post_type' => 'gallery_pictures', );
$loop = new WP_Query( $mypost );
?>
<div id="boxhover">
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<!--Fade-->
<?php $ddd = '<div class="mosaic-block fade">
<a href="'. $image[0] . '" data-fancybox-group="gallery" target="_blank" class="mosaic-overlay preview fancybox" title="' . the_title . '">
<div class="details">
<h4>' . the_title() . '</h4>
<p>' . the_content_rss('', TRUE, '', 30) . '</p>
<br/>
<div class="btt">VIEW</div>
</div>
</a>
<div class="mosaic-backdrop"><img src="' . $image[0] . '" alt="gallery thumbnail" /></div>
</div>';
endwhile; ?>
</div>
<?php
return $ddd;
}
function register_shortcodes(){
add_shortcode('gallery', 'recent_posts_function');
}
add_action( 'init', 'register_shortcodes');
as you can see from the above codes, the 'return $ddd' should return all the output from the loops that the 'while' process done but its display only one.
Im currently looking for a solution and would love to hear any suggestion, recommendations and ideas on how to do it. Thank in advance.
You need to add a [dot] before your = [equal] on the loop while.
This will cause each loop add content current with the previous.
<?php function recent_posts_function() {
$ddd = ''; //First declare the string var ?>
...
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<?php $ddd .= '<div class="mosaic-block fade">'; // Put a [dot] before sign symbol ?>
<?php endwhile; ?>
...
return $ddd;
...
<? php } ?>

Custom post type loop

I need some guidance on this script.
I'm working on a custom post type loop but I'm stuck on how to convert this static html to a php loop
<?php
$loop = new WP_Query(array('post_type' => 'project', 'posts_per_page' => -1));
$count =0;
?>
<!--Text Sliders-->
<div class="ps-contentwrapper">
<?php if ( $loop ) :
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$terms = get_the_terms( $post->ID, 'tagproject' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term )
{
$links[] = $term->name;
}
$links = str_replace(' ', '-', $links);
$tax = join( " ", $links );
else :
$tax = '';
endif;
?>
<?php $infos = get_post_custom_values('_url'); ?>
<div class="ps-content">
<h2><?php the_title(); ?></h2>
<p><?php echo get_the_excerpt(); ?></p>
</div><!--end of ps-content-->
</div><!-- /ps-contentwrapper -->
<!--Image Sliders-->
<div class="ps-slidewrapper">
<div class="ps-slides">
<?php
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<div style="background-image: url(<?php echo $url; ?>);"></div>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
<nav>
</nav>
Here is the tutorial I'm trying to convert. Demo.
What I'm trying to figure out is how to line up everything dynamically. If someone can point me to the right direction I appreciate it.
My version of it with the current code I pasted above.
EDIT: Here is my code now after a bit of research. Now I'm trying to figure out how I can match the featured image to the appropriate post as it cycles through in this script. The div tag that echos the url needs to loop as many times the loop does and cycle appropriately.
<div class="ps-slides">
<?php
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<div style="background-image: url(<?php echo $url; ?>);"></div>
</div><!--end of ps-slides-->
Full code below:
<div class="ps-contentwrapper">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="ps-content">
<h2><?php the_title(); ?></h2>
<p><?php echo get_the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div><!--end of contentwrapper-->
<!--Image Sliders-->
<div class="ps-slidewrapper">
<div class="ps-slides">
<?php
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<div style="background-image: url(<?php echo $url; ?>);"></div>
</div><!--end of ps-slides-->
<nav>
<?php
$prev_post = get_previous_post();
$id = $prev_post->ID ;
$permalink = get_permalink( $id );
$prev_url = wp_get_attachment_url( get_post_thumbnail_id($id) );
?>
<?php
$next_post = get_next_post();
$nid = $next_post->ID ;
$permalink = get_permalink($nid);
$next_url = wp_get_attachment_url( get_post_thumbnail_id($nid) );
?>
</nav>
</div>
use code for your previous next post image url:
<?php
$prev_post = get_previous_post();
$id = $prev_post->ID ;
$permalink = get_permalink( $id );
$prev_url = wp_get_attachment_url( get_post_thumbnail_id($id) );
?>
<?php
$next_post = get_next_post();
$nid = $next_post->ID ;
$permalink = get_permalink($nid);
$next_url = wp_get_attachment_url( get_post_thumbnail_id($nid) );
?>

Categories