首先在 WordPress 插件目录下创建一个新目录,并在其中创建一个名为 "hide-ads-on-login" 的新文件夹。
在此文件夹中创建一个新 PHP 文件,命名为 "hide-ads-on-login.php" ,并将以下代码添加到该文件中:
<?php
/*
Plugin Name: Hide Ads on Login
Description: Hides ads for logged in users
Version: 1.0
Author: Your Name Here
License: GPL2
*/
// Set cookie on login
function hide_ads_set_cookie() {
if ( is_user_logged_in() ) {
setcookie( 'hide_ads', 'true' );
}
}
add_action( 'wp_login', 'hide_ads_set_cookie' );
// Check cookie and hide ads
function hide_ads_hide_content() {
if ( isset( $_COOKIE['hide_ads'] ) && $_COOKIE['hide_ads'] == 'true' ) {
echo '<style type="text/css">#ad-section { display:none; }</style>';
}
}
add_action( 'wp_head', 'hide_ads_hide_content' );
此插件将在用户登录时设置一个名为 "hide_ads" 的 cookie。
插件还使用了一个名为 "hide_ads_hide_content" 的函数,该函数检查 cookie,并在页面顶部添加 CSS 样式,以将 ID 为 "ad-section" 的广告部分隐藏。
现在将 "hide-ads-on-login" 文件夹上传到 WordPress 插件目录中的 "wp-content/plugins" 目录。
在 WordPress 后端页面中,启用 "Hide Ads on Login" 插件。
现在,在用户登录后,将显示页面上 ID 为 “ad-section” 的广告部分。如果它存在,将在检查 cookie 时隐藏它。如果您希望在其他部分隐藏广告,只需将 CSS 样式中的 "ad-section" ID 更改为要隐藏的部分的 ID 即可。
另外一个方法是:
让注册用户登陆 WordPress 后不显示广告
在 WordPress 插入广告代码的时候加上判断。通过 get_current_user_id () 返回当前的用户,如果没有登陆用户,那么就是 0.
$ad_code = '广告代码放这里..';
if (get_current_user_id()) {
$ad_code = '';
}
echo $ad_code;
或者是:
<php
if (!get_current_user_id()) {
?>
// 广告代码HTML
<php
}
?>
这样,只要平时登陆 WordPress, 页面就不会显示广告。一般来说是不会和缓存插件冲突的,因为一般缓存只有在不是 WordPress 用户登陆的时候才会生成缓存。当然,如果你只想你登陆的时候不显示广告 (比如有多个 wordpress 用户), 那么只要知道你用户的 user id 就可以。假设是 1 的话:
$ad_code = 'Ads code put here.';
if (get_current_user_id() == 1) {
$ad_code = '';
}
echo $ad_code;
或者,也许长这样:
<php
if (get_current_user_id() != 1) {
?>
// HTML code of the ads
<php
}
?>
- All rights reserved.
- No part of this website, including text and images, may be reproduced, modified, distributed, or transmitted in any form or by any means, without the prior written permission of the author.
- Unauthorized commercial use is strictly prohibited.
- Unauthorized personal use is strictly prohibited.