0

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();
?>
    <li><a 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?

1 Answer 1

0

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.

1
  • Sorry, I couldn't make it work. It stills displays only the child page...
    – Gabrielle
    Commented Nov 2, 2016 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.