最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Add code to the header of posts by particular author

programmeradmin1浏览0评论

I want to add CSS code to the header of all the posts by a particular author.

I tried the following solution:

function hide_author_box() {
if (is_author('ritesh')) {
    ?>
<style>
    .author-box {
        display: none;
    }
</style>
    <?php
    }
}

But it doesn't work. How do I fix it?

I want to add CSS code to the header of all the posts by a particular author.

I tried the following solution:

function hide_author_box() {
if (is_author('ritesh')) {
    ?>
<style>
    .author-box {
        display: none;
    }
</style>
    <?php
    }
}

But it doesn't work. How do I fix it?

Share Improve this question edited Oct 7, 2019 at 12:15 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Oct 7, 2019 at 12:03 heyitsriteshheyitsritesh 32 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

is_author() is not for determining current user, it checks whether the Author archive page is in display or not.

Your call would be to use wp_get_current_user() or get_current_user_id() (if you are comfortable with user ID) or any similar function WP have.

Example of using wp_get_current_user()

<?php
$current_user = wp_get_current_user();

if ( 'ritesh' === $current_user->user_login ) {
    // do something
}

You're not far off.

is_author() returns a boolean meaning if you are on the archive page for Ritesh it will return true, and your code will execute.

Based on your post, I think you need to look up the page author based on the current post object and check against that instead. So your total code might look like this:

$id = get_queried_object()->post_author;
$author = get_the_author_meta('nickname', $id);
if($author == 'Ritesh') {
    //... Do some code here
}
  1. $id: This gets the current post object of the blog/page/post you are on, and returns the post authors ID
  2. Next we fetch the nickname as set in the User panel based on the ID we fetched earlier
  3. Then we compare the nickname against the name you want, and execute code based on that.

This should hopefully get you started :)

发布评论

评论列表(0)

  1. 暂无评论