Wordpress list pages from parent - wordpress

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();
}

Related

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;
}

Custom query pagination problem with php parameter as arg

I have create a loop with a custom query. This query contains a php parameters that i m getting from url with GET method. This the code at my loop page:
$cat = get_queried_object();
echo '<h1 class="childcatdes">'. $cat->name . '</h1>';
echo '<p class="childcatdescr">'. $cat->description . '<br><br></p>';
do_action( 'woocommerce_before_single_product' );
$posts_per_page = 12;
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$product_args = array(
'post_type' => 'product',
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'page' => $paged,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'name',
'terms' => $cat->name,
),
array(
'taxonomy' => 'manufacturers',
'field' => 'slug',
'terms' => $_GET['filter_manufacturers'],
'operator' => 'IN'
)
),
'orderby' => 'name',
'order' => 'ASC',
);
$custom_query = new WP_Query( $product_args );
if($custom_query->have_posts()) {
echo '<ul';
while ($custom_query->have_posts() ) : $custom_query->the_post();
echo '<li>';
$link = get_the_permalink();
echo '' . get_the_title() . '';
echo '</li>';
endwhile;
echo '</ul>';
}
else {
echo 'No post found.';
}
?>
<nav class="pagination">
<?php pagination_bar( $custom_query); ?>
</nav>
And i use this code to my functions.php file for the function pagination_bar
function pagination_bar( $custom_query) {
$total_pages = $custom_query->max_num_pages;
$big = 999999999; // need an unlikely integer
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => preg_replace('/\?.*/', '/', get_pagenum_link(1)) . '%_%',
'current' => $current_page,
'format' => 'page/%#%/',
'total' => $custom_query->max_num_pages,
'add_args' => array(
'filter_manufacturers' => $_GET['filter_manufacturers'],
)
));
}
}
The problem is that the pagination (even if it counts the posts correct at first page) is not working correct. I 'm getting 404 error at second page.

How to call category in dashboard if mine posted is attached to them only?

I am making user dashboard and I create a dashboard widget for category. Now I want to show category if current user's post is attached to them.
Currently I am able to see all categories.
Here is my function
function user_categories() {
wp_add_dashboard_widget(
'wp_widget_category', // Widget slug.
'Categories', // Title.
'my_dashboard_category' // Display function.
);
function my_dashboard_category() {
if ( is_user_logged_in() ):
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
?>
<?php
$args = array(
'type' => 'recipes',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'author' => $current_user->ID,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'recipe_categories',
'pad_counts' => false );
$categories = get_categories($args);
foreach ($categories as $category) {
$url = get_term_link($category);?>
<div class="submitted_recipe">
<a href="<?php echo $url;?>"><?php echo do_shortcode(sprintf('[wp_custom_image_category size="large_blog" term_id="%s"]',$category->term_id)); ?>
<h2><?php echo $category->name; ?></h2>
</a>
</div>
<?php
}
?>
<?php
}
endif;
}
}
add_action( 'wp_dashboard_setup', 'user_categories' );
You need to query all user posts in each categorie, if it's not empty then include this category. try this revised code
function user_categories() {
wp_add_dashboard_widget(
'wp_widget_category', // Widget slug.
'Categories', // Title.
'my_dashboard_category' // Display function.
);
function my_dashboard_category() {
if ( is_user_logged_in() ):
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
?>
<?php
$args = array(
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'recipe_categories',
'pad_counts' => false );
$categories = get_categories($args);
foreach ($categories as $category) {
$posts_query = new WP_Query( array(
'post_type' => 'recipes',
'author' => $current_user->ID,
'tax_query' => array(
array('taxonomy' => 'recipe_categories',
'field' => 'slug',
'terms' => $category->slug)
),
'fields' => 'ids'
) );
$ids = $posts_query->posts;
if (!empty ($ids)) {
$url = get_term_link($category);?>
<div class="submitted_recipe">
<a href="<?php echo $url;?>"><?php echo do_shortcode(sprintf('[wp_custom_image_category size="large_blog" term_id="%s"]',$category->term_id)); ?>
<h2><?php echo $category->name; ?></h2>
</a>
</div>
<?php
}
}
?>
<?php
}
endif;
}
}
add_action( 'wp_dashboard_setup', 'user_categories' );

How to List all Child pages in wordpress?

I have a parent page A with with child pages X, Y, Z, D
I want to display link to all child pages on page X and Y
When you go to page X and Y, you should see a list of all child pages X, Y, Z, D
For some reason I get only the child page (page D)
I am using this function.
$args = array(
'sort_order' => 'asc',
'sort_column' => 'post_title',
//'hierarchical' => 1,
'exclude' => '',
'include' => '',
'meta_key' => '',
'meta_value' => '',
'authors' => '',
'child_of' => A,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_pages($args);
if ( $pages)
{
foreach($pages as $page)
{
$page = '<ul> <li> ' .$page->post_title . ' </li></ul>';
}
return $page;
}
What am I doing wrong?
In the example, you are failing to close your if statement. Also you can use echo with your foreach instead of return. I cleaned up your code a little bit.
<ul>
<?php
$args = array(
'sort_order' => 'asc',
'child_of' => '1',
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_pages($args);
if ($pages) {
foreach ($pages as $page) :
echo ' <li> ' . $page->post_title . ' </li>';
endforeach;
}
?>
</ul>
I fixed it and it worked
I modified my foreach
$links = '';
foreach($pages as $page) {
$links .= '<ul> <li> ' .$page->post_title . ' </li></ul>';
}
return $links;
Before I used
$links = instead of $links .=

Wordpress infinite previous next looping in same category

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();
};

Resources