Wordpress infinite previous next looping in same category - wordpress

I have this code but can someone help me to make it work in same category in custom post = 'project'
<?php
/**
* Infinite next and previous post looping in WordPress
*/
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '← Previous Post');
} else {
$first = new WP_Query('posts_per_page=1&order=DESC'); $first->the_post();
echo '← Previous Post';
wp_reset_query();
};
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post →');
} else {
$last = new WP_Query('posts_per_page=1&order=ASC'); $last->the_post();
echo 'Next Post →';
wp_reset_query();
};
?>

// set current category
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;
// get next post link
$next_post = get_adjacent_post( true, '', false );
if( $next_post ) {
echo 'Next post';
} else {
$first = new WP_Query( array(
'post_type' => 'project',
'post_status' => 'publish',
'posts_per_page' => 1,
'order' => 'ASC',
'cat' => $cat_ID
));
$first->the_post();
echo 'Next post';
wp_reset_query();
};
// show prev post link
$prev_post = get_adjacent_post( true, '', true );
if( $prev_post ) {
echo 'Prev post';
} else {
$last = new WP_Query( array(
'post_type' => 'project',
'post_status' => 'publish',
'posts_per_page' => 1,
'order' => 'DESC',
'cat' => $cat_ID
));
$last->the_post();
echo 'Prev post';
wp_reset_query();
};

Related

How to get post using taxonomy terms in wordpress

I have a post type called "rationale" and my taxonomy name is "company_list". In taxonomy there are list of company. Each company have many rationale.
I want to get latest rationale for each company. How can i do this ?
I try below code but it show all company list but data is duplicate
<?php
//$taxonomy = 'our_work_thematic';
$myquery = array (
'post_type' => 'rationale',
'paged'=>$paged,
'posts_per_page' => -1,
);
$loop = new WP_Query($myquery);
if( $loop->have_posts() ):
while( $loop->have_posts() ):
$loop->the_post(); global $post; ?>
<?php $terms = get_the_terms( $post->ID, 'company_list' );
foreach($terms as $term) {
$termlinks = get_term_link($term);
echo '<p class="post-content--cat">';
echo '' . $term->name . '';
echo '</p>';
}?>
<?php endwhile; ?>
<?php endif; ?>
You need to get latest term and use tax_query
$args_query = array(
'post_type' => array('rationale'),
'paged' => $paged,
'posts_per_page' => -1,
);
$terms = get_terms(array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
));
if (!empty($terms) && is_array($terms)) {
$args_query['tax_query'] => array(
array(
'taxonomy' => 'company_list',
'field' => 'term_id',
'terms' => array($terms['0']->term_id), // single or array with id's
),
),
}
$query = new WP_Query($args_query);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$terms = get_the_terms($post->ID, 'company_list');
foreach ($terms as $term) {
$termlinks = get_term_link($term);
echo '<p class="post-content--cat">';
echo '' . $term->name . '';
echo '</p>';
}
}
} else {
// no post found
}
wp_reset_postdata();
try this
$terms = get_terms( array(
'taxonomy' => 'your taxonomy name',
'hide_empty' => false,
'orderby' => 'term_id',
'order' => 'asc',
) );
foreach ($terms as $terms_row) {
$terms_row->slug;
echo "<pre>";
print_r($terms_row);
echo "</pre>";
}
Thanks

Custom Post types Pagination shows up but 404s

I can't get pagination to work with custom post types.
It's showing up correctly, when I click it goes to /page/2 and /page/3 etc, and all those give a 404 Page not found error.
index.php
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => array('name1', 'name2', 'name3', 'post'),
'posts_per_page' => 4,
'post_status' => 'publish',
'paged' => $paged
);
$query = new WP_Query( $args );
?>
<?php echo $paged; ?>
<?php if ($query->have_posts()) : ?>
<?php while ($query->have_posts()) : $query->the_post(); ?>
// do stuff here
<?php the_excerpt(); ?>
<?php endwhile; ?>
// get pagination
<?php mypagination( $query ); ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
functions.php
the built in the_posts_pagination() doesn't output anything.
function mypagination($query){ ?>
<ul class="pagination">
<?php
$pages = paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => true,
'type' => 'array',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => '<span class ="fa fa-caret-left" aria-hidden="true"></span><span class="prev-text">Prev</span>',
'next_text' => '<span class="next-text">Next</span> <span class ="fa fa-caret-right" aria-hidden="true"></span>',
'add_args' => false,
'add_fragment' => '',
) );
if (is_array($pages)):
foreach ($pages as $p): ?>
<li class="pagination-item js-ajax-link-wrap">
<?php echo $p; ?>
</li>
<?php endforeach;
endif; ?>
</ul>
<?php
}
If I create a custom API endpoint with the same query/arguments, pagination IS working.
/**
* Custom JSON API endpoint.
* Endpoint URL http://localhost/websitename/wp-json/frontpage/v1
*/
function api_frontpage_posts($data) {
$output = array();
// Get post slug.
$post = get_post($data['parent_id']);
$slug = $post->post_name;
// e.g. 1, 2, 3,...
$paged = $data['page_number'] ? $data['page_number'] : 1;
$query_args = array(
'post_type' => array('name1', 'name2', 'name3', 'post'),
'post_status' => array('publish'),
'posts_per_page' => 4,
'paged' => $paged,
);
// Create a new instance of WP_Query
$the_query = new WP_Query($query_args);
if (!$the_query->have_posts()) {
return null;
}
while ($the_query->have_posts()) {
$the_query->the_post();
$post_id = get_the_ID();
$post_title = get_the_title();
$post_content = get_the_content();
$post_excerpt = get_the_excerpt();
$post_date = get_the_date('l, j F Y');
// Get the slug.
$post = get_post($post_id);
$post_slug = $post->post_name;
// Get image alt.
$alt = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true);
$desc = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_caption', true);
// Get image description.
$description = null;
$thumbnail = get_posts(array('p' => get_post_thumbnail_id(), 'post_type' => 'attachment'));
if ($thumbnail && isset($thumbnail[0])) {
$description = $thumbnail[0]->post_content;
}
// Image data.
$post_image = array(
'id' => get_post_thumbnail_id() ,
'url' => get_the_post_thumbnail_url(),
'caption' => get_the_post_thumbnail_caption(),
'alt' => $alt,
'description' => $description,
);
// Category data.
$categories = get_the_category($post_id);
$post_categories = array();
foreach ($categories as $key => $category) {
$post_categories[] = array(
'name' => $category->name,
'slug' => $category->slug,
'url' => get_category_link($category->cat_ID),
);
}
// Push the post data into the array.
$output[] = array(
'id' => "post" . $post_id, // cannot use numbers, or hyphens between words for Zurb data toggle attribute
'slug' => $post_slug,
'title' => $post_title,
'url' => get_permalink($post_id),
'date' => $post_date,
'content' => $post_content,
'excerpt' => $post_excerpt,
'image' => $post_image,
'categories' => $post_categories
);
}
$result = array(
"next" => (int)$paged === (int)$the_query->max_num_pages ? null : site_url() . '/' . $slug . '/page/' . ($paged + 1) . '/',
"prev" => (int) $paged === 1 ? null : site_url() . '/' . $slug . '/page/' . ($paged - 1) . '/',
// Split the array every 4 items.
"chunks" => array_chunk($output, 4)
);
// Reset the post to the original after loop. otherwise the current page
// becomes the last item from the while loop.
wp_reset_query();
// Return json.
return $result;
}
add_action('rest_api_init', function () {
register_rest_route('frontpage/v1', '/page/(?P<page_number>\d+)', array(
'methods' => 'GET',
'callback' => 'api_frontpage_posts',
));
});
(hooray Reddit)
Someone pointed me to the fix.
Add this to functions.php too, via https://wordpress.stackexchange.com/questions/22528/custom-post-type-pagination-404-fix
add_action( 'parse_query','changept' );
function changept() {
if( is_category() && !is_admin() )
set_query_var( 'post_type', array( 'post', 'your_custom_type' ) );
return;
}

How to get categories product in archive.php in WordPress?

I would like to display categories (from taxonomy-product_category) in archive-product.php.
Get categories:
Fruit
Herbs
Salad
Vegetables
See screenshot what I mean:
When I added coding in archive-product.php:
<?php
$args = array(
'post_type' => 'product',
'taxonomy' => 'product_category',
'hierarchical' => 1,
'nopaging' => false,
'posts_per_page' => '2',
'posts_per_archive_page' => '10',
'ignore_sticky_posts' => true,
'order' => 'rand',
);
echo '<div class="container">';
echo '<div class="row">';
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo '<div class="col-lg-4">';
echo '<a href="'.get_the_permalink().'">';
if ( has_post_thumbnail() ) {
the_post_thumbnail(array(486,226));
}
the_title();
the_content();
echo '</a>';
echo '</div>';
}
} else {
// no posts found
echo wpautop( 'Sorry, no posts were found' );
}
echo '</div>';
echo '</div>';
// Previous/next post navigation.
previous_post_link( '%link', 'Prev post in category', true
);
next_post_link( '%link', 'Next post in category', true );
// Restore original Post Data
wp_reset_postdata();
?>
But not display categories (Fruit, Herbs, Salad, Vegetables)
Would anyone know about this?
Thanks,
Shaun.
Please try below code:
$args = array(
'taxonomy'=> 'product_category',
'order' => 'DESC',
);
$categories = get_categories($args);
print_r($categories);
You can get the list of all product categories using Below code
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}

How to Hide post that have same category

is there someone who knows how to hide post that have same category?
I have Post 1, Post 2, Post 3 that have same category. Can i just show the latest post ( post 1) at my homepage, and hide other post ( post 2 and post 3 )
One way of doing that is to have three separate wp_queries.
//Query 1
$args1 = array(
'cat' => '1',
'nopaging' => true,
'posts_per_page' => '1',
); $query_1 = new WP_Query( $args1 );
if ( $query_1->have_posts() ) {
while ( $query_1->have_posts() ) {
$query_1->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
//Query 2
$args2 = array(
'cat' => '2',
'nopaging' => true,
'posts_per_page' => '1',
); $query_2 = new WP_Query( $args2 );
if ( $query_2->have_posts() ) {
while ( $query_2->have_posts() ) {
$query_2->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
//Query 3
$args3 = array(
'cat' => '3',
'nopaging' => true,
'posts_per_page' => '1',
); $query_3 = new WP_Query( $args3 );
if ( $query_3->have_posts() ) {
while ( $query_3->have_posts() ) {
$query_3->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
<?php
$args = array(
'numberposts' => 1,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'draft, publish, future, pending, private',
'suppress_filters' => true
);
// the query
$the_query = new WP_Query( $args );?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
Add your category ID to 'category'.
reefer these links for more information.
https://codex.wordpress.org/Class_Reference/WP_Query
https://codex.wordpress.org/Function_Reference/wp_get_recent_posts
You can achieve this by alter the query of home page throught pre_get_posts hook.
Here is the code:
function txt_domain_get_distinct_post_id()
{
$post_ids = [];
//getting all non empty category
$categories = get_terms('category', array(
'orderby' => 'count',
'hide_empty' => 0,
));
foreach ($categories as $category)
{
$args = array(
'posts_per_page' => -1,
'category' => $category->term_id,
'exclude' => $post_ids,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
//getting post from a specific category
$postlist = get_posts($args);
foreach ($postlist as $post)
{
if (!in_array($post->ID, $post_ids))
{
//this will only select one post form each category
$post_ids[] = $post->ID;
break;
}
}
}
return $post_ids;
}
add_filter( 'pre_get_posts', 'txt_domain_filter_get_posts' );
function txt_domain_filter_get_posts($query)
{
if (is_home() && $query->is_main_query())
{
$post_ids = txt_domain_get_distinct_post_id();
$query->set('post__in', $post_ids);
}
return $query;
}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Reference:
is_home()
get_terms
get_posts

Wordpress list pages from parent

I need help listing all pages when on a third level (grandchild) Page.
E.g I have Page 1(grandparent) Page 2(Parent) Page 3(Child)
I need to show all these pages listed the same on all three pages such as:
Page1
Page2
Page3
I have successfully shown the right list of pages on page 1 and 2. (see below)
Can anyone please help
function widget($args, $instance) {
global $post;
extract( $args );
if($post->post_parent == 0) {
$title = ''.$post->post_title.'';
$id_to_query = $post->ID;
}
elseif($post->ancestors) {
$page = get_page($post->ancestors[0]);
$title = ''.$page->post_title.'';
$id_to_query = $post->ancestors[0];
} else {
$page = get_page($post->post_parent);
$title = ''.$page->post_title.'';
$id_to_query = $page->ID;
}
$children = get_pages('post_type='.get_post_type().'&child_of='.$id_to_query);
if(empty($children) || is_page( array(17,125) ) ) return; // excludes contact us etc...
wp_reset_query();
$widget_title = $title;
echo $before_widget;
echo $before_title . $widget_title . $after_title; ?>
<ul>
<?php wp_list_pages('title_li=&post_type='.get_post_type().'&child_of='.$id_to_query); ?>
</ul>
<?php
echo $after_widget;
wp_reset_postdata();
Try getting the top ancestor id with $topid = get_top_ancestor($postid); then using the arguement 'child_of' => $topid and be mindful of your depth
Full example:
<?php
$postid = get_the_ID();
$topid = get_top_ancestor($postid);
$args = array(
'depth' => 2,
'show_date' => '',
'date_format' => get_option('date_format'),
'child_of' => $topid,
'exclude' => '',
'include' => '',
'echo' => 1,
'authors' => '',
'sort_order' => 'ASC',
'link_before' => '',
'link_after' => '',
'walker' => '',
'post_type' => 'page',
'post_status' => 'publish'
); ?>
<ul><?php wp_list_pages( $args ); ?></ul>
Something for you to work on [Untested]:
function widget($args, $instance) {
global $post;
$postid = get_the_ID();
$topid = get_top_ancestor($postid);
$args = array(
'depth' => 2,
'show_date' => '',
'date_format' => get_option('date_format'),
'child_of' => $topid,
'exclude' => '',
'include' => '',
'echo' => 1,
'authors' => '',
'sort_order' => 'ASC',
'link_before' => '',
'link_after' => '',
'walker' => '',
'post_type' => 'page',
'post_status' => 'publish'
);
// if(empty($children) || is_page( array(17,125) ) ) return; // excludes contact us etc...
// wp_reset_query();
$widget_title = $title;
echo $before_widget;
echo $before_title . $widget_title . $after_title; ?>
<ul>
<?php wp_list_pages( $args ); ?>
</ul>
<?php
echo $after_widget;
wp_reset_postdata();
}

Resources