0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WordPress】【ワードプレス】人気記事を持ってくる

Last updated at Posted at 2024-05-13

functions.php

// 記事のPVを取得
function getPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count=='') {
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}

// 記事のPVをカウントする
function setPostViews($postID) {
    $count_key = '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);
    }
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

single.php

if (!is_user_logged_in() && !is_robots()) {
    setPostViews(get_the_ID());
}

任意のxxx.php

  <h4>よく読まれている記事</h4>
    <hr>
    <?php $args = ['post_type'=>'post','meta_key'=>'post_views_count','orderby'=>'meta_value_num','posts_per_page'=> 5,'order'=>'DESC','post_status'=>'publish'];?>
    <?php $the_view_query = new WP_Query( $args );?>
    <?php if ($the_view_query->have_posts()) {?>
      <?php while($the_view_query->have_posts()) { ?>
        <?php $the_view_query->the_post();?>
        <!-- タイトル表示 -->
        <div>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <p><?php echo getPostViews($post->ID); ?></p>
        </div>
      <?php } ?>
    <?php } ?>
    <?php wp_reset_postdata();?>


前日pv
https://dev.ore-shika.com/post/wp-last-pv/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?