Get a page ancestor from a most viewed list

I'm using WPBeginner's tutorial do display a list of the most viewed pages on a site.

This is on my functions.php:

function wpb_set_post_views($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

this is on my page.php (inside the loop):

?php wpb_set_post_views(get_the_ID()); ?

and this is in a custom template page, where I'll display the top hits list (instead of the regular the_content):

?php echo 'ul';
    $popularpost = new WP_Query( array( 'post_type' = 'page', 'posts_per_page' = 20, 'meta_key' = 'wpb_post_views_count', 'orderby' = 'meta_value_num', 'order' = 'DESC', 'exclude' = '19,21,22', 'date_query' = array('before' = '1 month ago') ) );
    while ( $popularpost-have_posts() ) : $popularpost-the_post();
?
    lia href="?php the_permalink() ?" title="?php the_title(); ?"?php the_title(); ?/a/li
?php endwhile;
echo '/ul'; ?

It works just fine, but I'd like to have the page ancestor before the page link on the list. I tried adding these inside li, right before the link for the page - but they didn't return anything:

?php get_ancestors(); ? 

?php $ancestors = get_ancestors( '$post-ID', 'page', 'post_type' ); ?

How can I display the ancestor of a page there?

Topic popular-posts child-pages wp-query pages Wordpress

Category Web


get_ancestors will return array form value. So if you talking about how to get and display that ancestors with link:

<?php 
 $arrAncestors = get_ancestors( $post->ID, 'page'); 
 $cntAncestors = COUNT($arrAncestors);
 if($cntAncestors > 0) {
   $parentPostId = $arrAncestors[$cntAncestors - 1];
   $parentPageLink = get_permalink($parentPostId);
   $parentTitle = get_the_title($parentPostId);
   print '<li><a href="<?php $parentPageLink ?>" title="<?php $parentTitle; ?>"><?php $parentTitle; ?></a></li>';
 }
?>

Hope you get solution from above snippet.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.