如何将内容限制为注册的 WordPress 用户
最近,大多数在线新闻和信息发布网站都采用免费增值模式,即非注册会员的读者可以阅读一定数量的文章;另一方面,付费注册用户可以无限制地访问文章。
在本文中,我们将向您展示如何构建一个简单的插件,让 WordPress 站点的管理员能够将某些帖子、页面和部分帖子内容限制为仅注册用户。
编写插件
在编写 WordPress 插件时,标题(PHP 注释块)部分包含插件的名称、描述、作者和作者 URL 等信息。这是插件标题:
1个
2个
3个
4个
5个
6个
7
8个
9
|
<?php /* Plugin Name: Restrict Content to registered users Plugin URI: http://hongkiat.com Description: Restricting content to registered users only Version: 0.1 Author: Agbonghama Collins Author URI: http://tech4sky.com */ |
该插件将有一个设置页面,该页面由一个表单字段组成,该表单字段将包含要限制的帖子或页面 ID。
下面的代码将在标题为 的设置Restrict content To Registered User
中添加一个子菜单。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
|
add_action( 'admin_menu' , 'rcru_plugin_menu' ); // Adding Submenu to settings function rcru_plugin_menu() { add_options_page( 'Restrict content To Registered User' , 'Restrict content To Registered User' , 'manage_options' , 'rcru-restrict-content-user' , 'rcru_content_user_settings' ); } |
rcru_content_user_settings
传递给上面的第五个参数add_options_page
是将输出插件设置内容的函数。
1个
2个
3个
4个
5个
6个
7
8个
9
|
function rcru_content_user_settings() { echo '<div class="wrap">' ; screen_icon(); echo '<h2>Restrict content To Registered User</h2>' ; echo '<form action="options.php" method="post">' ; do_settings_sections( 'rcru-restrict-content-user' ); settings_fields( 'rcru_settings_group' ); submit_button(); } |
该表单缺少该<input>
字段,并且它还不能将数据保存到数据库中,因为我们还没有实现 WordPress设置 API。
该函数plugin_option
定义设置部分和字段。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
|
// plugin field and sections function plugin_option() { add_settings_section( 'rcru_settings_section' , 'Plugin Options' , null, 'rcru-restrict-content-user '); add_settings_field( 'post-page-id' , '<label for="post-page-id">Post and page ID to be restricted.</label>' , 'post_page_field' , 'rcru-restrict-content-user' , 'rcru_settings_section' ); // register settings register_setting( 'rcru_settings_group' , 'rcru_post-id-option' ); |
请注意,post_page_field
传递给add_settings_field
上面函数的第三个参数被调用以回显表单<input>
字段。
1个
2个
3个
4个
5个
|
function post_page_field() { echo "Enter Post or Page ID separated by comma. " ; echo '<input style="width: 300px; height:80px" type="text" id="post-page-id" name="rcru_post-id-option" value="' . get_option( 'rcru_post-id-option' ) . '">' ; } |
该函数plugin_option
最终挂钩到admin_init
动作以将其付诸行动。
1个
|
add_action( 'admin_init' , 'plugin_option' ); |
我们已经完成了插件设置页面的构建,但是如果不使用设置页面保存到数据库的数据有什么用呢?
接下来是函数的编码,restrict_content_register_user
该函数将检索帖子或页面 ID 以仅限于注册用户(已保存到插件设置页面中的数据库)。这确保当前查看帖子的用户已注册;否则会显示一条错误消息,告诉用户注册。
最后,该函数将挂钩到 the_content 过滤器,以影响帖子或页面的更改。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
function restrict_content_register_user( $content ) { global $post ; $post_database = get_option( 'rcru_post-id-option' ); $post_database = explode ( ',' , $post_database ); $current_user = wp_get_current_user(); /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old If there is no content, return . */ if ( is_null ( $content )) return $content ; foreach ( $post_database as $posts ) { $posts = trim( $posts ); if ( $posts == $post -> ID) { if (username_exists( $current_user -> user_login)) { /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Return the private content. */ return $content ; } else { /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Return an alternate message. */ return '<div align= "center" style= "color: #fff; padding: 20px; border: 1px solid border-color: rgb(221, 204, 119); background-color: #3B5998" > You must be a registered user to read this content. <br/> <a style= "font-size: 20px;" href= "' . get_site_url() . '/wp-login.php?action=register" >Register Here</a> </div>'; } } } return $content ; } add_filter( 'the_content' , 'restrict_content_register_user' ); |
我们现在完成了插件工作的第一种方式:使用插件设置页面。
剩下的就是将 metabox和短代码功能添加到插件中。
添加元数据
在帖子和页面编辑屏幕中添加包含复选框的元框将允许在勾选复选框时将该帖子或页面限制为注册用户。当挂钩到操作时,该函数rcru_mb_create
将在所有帖子和页面中包含元框add_meta_boxes
。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
|
function rcru_mb_create() { /** 10 Apple Watch Apps You Will Love.html 10 Free Multipurpose WordPress Themes.html 10 Interesting Talks Designers Must Watch.html 10 Little-Known Tips to Secure WordPress Sites.html 10 Tested SEO Hacks to Attract More Traffic to WordPress Website.html 10 Things Windows Phones Did Better Than Android Phones.html 10 Things You Should Know Before You Try Coding.html 10 Ways Technology Makes Marketing Look Easy.html 15 Clever Examples of Interactive Packaging Design.html 20 New Tech Words You Should Know.html 20 Websites with Unorthodox Geometry Elements for Your Inspiration.html 30 Commonly Misused Words on the Internet.html 30 Sci-Fi-riffic Fonts to Download For Free.html 40+ Free Icon Sets You Should Have in Your Bookmarks.html 4 Creative Photoshop Artists Who Cleverly Manipulate Landscapes [PHOTOS].html 50+ Beautiful & Captivating Bokeh Photos - Volume 2.html 5 Android Apps for Less Boring Lock Screens.html 5 End-of-Year Tax Tips for Freelancers.html 5 Practices to Keep Your DIY WordPress Website Fast and Secure.html 5 Remote Worker Myths You Need To Stop Believing.html 5 Rugged Smartphone Cases to Survive (Almost) Any Drop.html 5 Simple Ways to Boost Your Online Sales Revenue.html 5 Smart Ways to Get Your Clients to Pay Your Rates.html 5 Social Commerce Trends for 2021 (From Facebook Shops to Shoppable Video).html 5 Things You Should Know About Mobile Advertising.html 5 Types of Social Media Followers & How to Engage Them.html 5 Web Hosting Technology Trends in 2021.html 60 Beautiful Flowers Wallpapers to Download.html 7 Content Curation Tools For Bloggers.html 9 Indie Marketplaces to Sell Your Designs.html 9 Lessons I Learned From Building My First App.html A Guide to Choose Fonts for Your Web Design.html Basic Guidelines to Product Sketching.html Brand Identity Lessons You Can Learn from Marvel Studios.html Calculating Percentage Margins in CSS.html Can't Find the Best 3D Modeling Software? Here Are Some Relatively Better Ones.html Changing The Face Of Web Design: A Case Study of 25 Years.html Creatives: Why You Should Always Have a Side Project.html Demo Day: 5 Tips To Prevent Bugs And Blunders.html get-posts-html.sh get-posts-url.sh Guide to Calculating Breakeven Point for Freelancers.html Hackers Love Your Social Media Shares. Here's Why..html Happiness Can Be The Best Strategy For Increasing Productivity: Here's How.html How 10 Global Startups are Solving World Problems.html How Big Data Analytics Make Cities Smarter.html How Can AI Chatbots Improve Customer Experience?.html How Inspirational Logos Can Affect Your Bottom Line.html How Open Source Companies Stay Profitable.html How to Create a Glossy Christmas Bauble in Illustrator.html How to Create Flaming Text Effect with Adobe Photoshop.html How to Design Websites with Great Navigation.html How to Get New Clients to Pursue You.html How To Get Your Readers To Market Your Content.html How to Harness Your Inner Creativity For Freelancers.html How to Install Windows Boot Camp Without An Optical Drive.html How to Optimize Conversion Rate with Persuasive Web Design.html How to Promote Your YouTube Channel at Zero Budget.html How to Restrict Content To Registered Users [WP Plugin Tutorial].html input-posts-id.txt Man to Machine: How to Reboot Your Humanity.html _old On the Future of Web Development: Are Designers at the Helm? [Op-Ed].html output-posts-urls.txt Remote Working: How to Stay Effective Without Becoming a Mowgli.html Shopify vs WordPress - Which is Best for e-commerce in 2021?.html Showcase of 10 Talented Freelance Designers (And Their Portfolios).html Testing Web Navigation with Card Sorting & Tree Testing.html The 12-Step Program to Personal Productivity.html Top Collaboration Apps For Project Managers.html What Small Business Owners Need to Know About UX Design?.html What to Do When Good Hosts Go Bad.html Why Designing Without A Design Brief Is Like Playing Charades.html Why Grandmas Will Be Able to Build an App by 2020.html Why I Switch From Windows to macOS.html @array $screens Write screen on which to show the meta box 10 Apple Watch Apps You Will Love.html 10 Free Multipurpose WordPress Themes.html 10 Interesting Talks Designers Must Watch.html 10 Little-Known Tips to Secure WordPress Sites.html 10 Tested SEO Hacks to Attract More Traffic to WordPress Website.html 10 Things Windows Phones Did Better Than Android Phones.html 10 Things You Should Know Before You Try Coding.html 10 Ways Technology Makes Marketing Look Easy.html 15 Clever Examples of Interactive Packaging Design.html 20 New Tech Words You Should Know.html 20 Websites with Unorthodox Geometry Elements for Your Inspiration.html 30 Commonly Misused Words on the Internet.html 30 Sci-Fi-riffic Fonts to Download For Free.html 40+ Free Icon Sets You Should Have in Your Bookmarks.html 4 Creative Photoshop Artists Who Cleverly Manipulate Landscapes [PHOTOS].html 50+ Beautiful & Captivating Bokeh Photos - Volume 2.html 5 Android Apps for Less Boring Lock Screens.html 5 End-of-Year Tax Tips for Freelancers.html 5 Practices to Keep Your DIY WordPress Website Fast and Secure.html 5 Remote Worker Myths You Need To Stop Believing.html 5 Rugged Smartphone Cases to Survive (Almost) Any Drop.html 5 Simple Ways to Boost Your Online Sales Revenue.html 5 Smart Ways to Get Your Clients to Pay Your Rates.html 5 Social Commerce Trends for 2021 (From Facebook Shops to Shoppable Video).html 5 Things You Should Know About Mobile Advertising.html 5 Types of Social Media Followers & How to Engage Them.html 5 Web Hosting Technology Trends in 2021.html 60 Beautiful Flowers Wallpapers to Download.html 7 Content Curation Tools For Bloggers.html 9 Indie Marketplaces to Sell Your Designs.html 9 Lessons I Learned From Building My First App.html A Guide to Choose Fonts for Your Web Design.html Basic Guidelines to Product Sketching.html Brand Identity Lessons You Can Learn from Marvel Studios.html Calculating Percentage Margins in CSS.html Can't Find the Best 3D Modeling Software? Here Are Some Relatively Better Ones.html Changing The Face Of Web Design: A Case Study of 25 Years.html Creatives: Why You Should Always Have a Side Project.html Demo Day: 5 Tips To Prevent Bugs And Blunders.html get-posts-html.sh get-posts-url.sh Guide to Calculating Breakeven Point for Freelancers.html Hackers Love Your Social Media Shares. Here's Why..html Happiness Can Be The Best Strategy For Increasing Productivity: Here's How.html How 10 Global Startups are Solving World Problems.html How Big Data Analytics Make Cities Smarter.html How Can AI Chatbots Improve Customer Experience?.html How Inspirational Logos Can Affect Your Bottom Line.html How Open Source Companies Stay Profitable.html How to Create a Glossy Christmas Bauble in Illustrator.html How to Create Flaming Text Effect with Adobe Photoshop.html How to Design Websites with Great Navigation.html How to Get New Clients to Pursue You.html How To Get Your Readers To Market Your Content.html How to Harness Your Inner Creativity For Freelancers.html How to Install Windows Boot Camp Without An Optical Drive.html How to Optimize Conversion Rate with Persuasive Web Design.html How to Promote Your YouTube Channel at Zero Budget.html How to Restrict Content To Registered Users [WP Plugin Tutorial].html input-posts-id.txt Man to Machine: How to Reboot Your Humanity.html _old On the Future of Web Development: Are Designers at the Helm? [Op-Ed].html output-posts-urls.txt Remote Working: How to Stay Effective Without Becoming a Mowgli.html Shopify vs WordPress - Which is Best for e-commerce in 2021?.html Showcase of 10 Talented Freelance Designers (And Their Portfolios).html Testing Web Navigation with Card Sorting & Tree Testing.html The 12-Step Program to Personal Productivity.html Top Collaboration Apps For Project Managers.html What Small Business Owners Need to Know About UX Design?.html What to Do When Good Hosts Go Bad.html Why Designing Without A Design Brief Is Like Playing Charades.html Why Grandmas Will Be Able to Build an App by 2020.html Why I Switch From Windows to macOS.html @values post, page, dashboard, link, attachment, custom_post_type */ $screens = array ( 'post' , 'page' ); foreach ( $screens as $screen ) { add_meta_box( 'rcru-meta' , 'Restrict Post / Page' , 'rcru_mb_function' , $screen , 'normal' , 'high' ); } } add_action( 'add_meta_boxes' , 'rcru_mb_create' ); |
该函数rcru_mb_function
包含元框的复选框和描述。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
20
|
function rcru_mb_function( $post ) { //retrieve the metadata values if they exist $restrict_post = get_post_meta( $post -> ID, '_rcru_restrict_content' , true); // Add an nonce field so we can check for it later when validating wp_nonce_field( 'rcru_inner_custom_box' , 'rcru_inner_custom_box_nonce' ); echo '<div style= "margin: 10px 100px; text-align: center" > <table> <tr> <th scope= "row" ><label for = "rcru-restrict-content" >Restrict content?</label></th> <td> <input type= "checkbox" value= "1" name= "rcru_restrict_content" id= "rcru-restrict-content" ' . checked($restrict_post, 1, false) . ' > <span class = "description" >Checking this setting will restrict this post to only registered users.</span> </td> </tr> </table> </div>'; } |
该rcru_mb_save_data
函数处理安全检查并将表单值保存到数据库。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
function rcru_mb_save_data( $post_id ) { /* 10 Apple Watch Apps You Will Love.html 10 Free Multipurpose WordPress Themes.html 10 Interesting Talks Designers Must Watch.html 10 Little-Known Tips to Secure WordPress Sites.html 10 Tested SEO Hacks to Attract More Traffic to WordPress Website.html 10 Things Windows Phones Did Better Than Android Phones.html 10 Things You Should Know Before You Try Coding.html 10 Ways Technology Makes Marketing Look Easy.html 15 Clever Examples of Interactive Packaging Design.html 20 New Tech Words You Should Know.html 20 Websites with Unorthodox Geometry Elements for Your Inspiration.html 30 Commonly Misused Words on the Internet.html 30 Sci-Fi-riffic Fonts to Download For Free.html 40+ Free Icon Sets You Should Have in Your Bookmarks.html 4 Creative Photoshop Artists Who Cleverly Manipulate Landscapes [PHOTOS].html 50+ Beautiful & Captivating Bokeh Photos - Volume 2.html 5 Android Apps for Less Boring Lock Screens.html 5 End-of-Year Tax Tips for Freelancers.html 5 Practices to Keep Your DIY WordPress Website Fast and Secure.html 5 Remote Worker Myths You Need To Stop Believing.html 5 Rugged Smartphone Cases to Survive (Almost) Any Drop.html 5 Simple Ways to Boost Your Online Sales Revenue.html 5 Smart Ways to Get Your Clients to Pay Your Rates.html 5 Social Commerce Trends for 2021 (From Facebook Shops to Shoppable Video).html 5 Things You Should Know About Mobile Advertising.html 5 Types of Social Media Followers & How to Engage Them.html 5 Web Hosting Technology Trends in 2021.html 60 Beautiful Flowers Wallpapers to Download.html 7 Content Curation Tools For Bloggers.html 9 Indie Marketplaces to Sell Your Designs.html 9 Lessons I Learned From Building My First App.html A Guide to Choose Fonts for Your Web Design.html Basic Guidelines to Product Sketching.html Brand Identity Lessons You Can Learn from Marvel Studios.html Calculating Percentage Margins in CSS.html Can't Find the Best 3D Modeling Software? Here Are Some Relatively Better Ones.html Changing The Face Of Web Design: A Case Study of 25 Years.html Creatives: Why You Should Always Have a Side Project.html Demo Day: 5 Tips To Prevent Bugs And Blunders.html get-posts-html.sh get-posts-url.sh Guide to Calculating Breakeven Point for Freelancers.html Hackers Love Your Social Media Shares. Here's Why..html Happiness Can Be The Best Strategy For Increasing Productivity: Here's How.html How 10 Global Startups are Solving World Problems.html How Big Data Analytics Make Cities Smarter.html How Can AI Chatbots Improve Customer Experience?.html How Inspirational Logos Can Affect Your Bottom Line.html How Open Source Companies Stay Profitable.html How to Create a Glossy Christmas Bauble in Illustrator.html How to Create Flaming Text Effect with Adobe Photoshop.html How to Design Websites with Great Navigation.html How to Get New Clients to Pursue You.html How To Get Your Readers To Market Your Content.html How to Harness Your Inner Creativity For Freelancers.html How to Install Windows Boot Camp Without An Optical Drive.html How to Optimize Conversion Rate with Persuasive Web Design.html How to Promote Your YouTube Channel at Zero Budget.html How to Restrict Content To Registered Users [WP Plugin Tutorial].html input-posts-id.txt Man to Machine: How to Reboot Your Humanity.html _old On the Future of Web Development: Are Designers at the Helm? [Op-Ed].html output-posts-urls.txt Remote Working: How to Stay Effective Without Becoming a Mowgli.html Shopify vs WordPress - Which is Best for e-commerce in 2021?.html Showcase of 10 Talented Freelance Designers (And Their Portfolios).html Testing Web Navigation with Card Sorting & Tree Testing.html The 12-Step Program to Personal Productivity.html Top Collaboration Apps For Project Managers.html What Small Business Owners Need to Know About UX Design?.html What to Do When Good Hosts Go Bad.html Why Designing Without A Design Brief Is Like Playing Charades.html Why Grandmas Will Be Able to Build an App by 2020.html Why I Switch From Windows to macOS.html We need to verify this came from the our screen and with proper authorization, 10 Apple Watch Apps You Will Love.html 10 Free Multipurpose WordPress Themes.html 10 Interesting Talks Designers Must Watch.html 10 Little-Known Tips to Secure WordPress Sites.html 10 Tested SEO Hacks to Attract More Traffic to WordPress Website.html 10 Things Windows Phones Did Better Than Android Phones.html 10 Things You Should Know Before You Try Coding.html 10 Ways Technology Makes Marketing Look Easy.html 15 Clever Examples of Interactive Packaging Design.html 20 New Tech Words You Should Know.html 20 Websites with Unorthodox Geometry Elements for Your Inspiration.html 30 Commonly Misused Words on the Internet.html 30 Sci-Fi-riffic Fonts to Download For Free.html 40+ Free Icon Sets You Should Have in Your Bookmarks.html 4 Creative Photoshop Artists Who Cleverly Manipulate Landscapes [PHOTOS].html 50+ Beautiful & Captivating Bokeh Photos - Volume 2.html 5 Android Apps for Less Boring Lock Screens.html 5 End-of-Year Tax Tips for Freelancers.html 5 Practices to Keep Your DIY WordPress Website Fast and Secure.html 5 Remote Worker Myths You Need To Stop Believing.html 5 Rugged Smartphone Cases to Survive (Almost) Any Drop.html 5 Simple Ways to Boost Your Online Sales Revenue.html 5 Smart Ways to Get Your Clients to Pay Your Rates.html 5 Social Commerce Trends for 2021 (From Facebook Shops to Shoppable Video).html 5 Things You Should Know About Mobile Advertising.html 5 Types of Social Media Followers & How to Engage Them.html 5 Web Hosting Technology Trends in 2021.html 60 Beautiful Flowers Wallpapers to Download.html 7 Content Curation Tools For Bloggers.html 9 Indie Marketplaces to Sell Your Designs.html 9 Lessons I Learned From Building My First App.html A Guide to Choose Fonts for Your Web Design.html Basic Guidelines to Product Sketching.html Brand Identity Lessons You Can Learn from Marvel Studios.html Calculating Percentage Margins in CSS.html Can't Find the Best 3D Modeling Software? Here Are Some Relatively Better Ones.html Changing The Face Of Web Design: A Case Study of 25 Years.html Creatives: Why You Should Always Have a Side Project.html Demo Day: 5 Tips To Prevent Bugs And Blunders.html get-posts-html.sh get-posts-url.sh Guide to Calculating Breakeven Point for Freelancers.html Hackers Love Your Social Media Shares. Here's Why..html Happiness Can Be The Best Strategy For Increasing Productivity: Here's How.html How 10 Global Startups are Solving World Problems.html How Big Data Analytics Make Cities Smarter.html How Can AI Chatbots Improve Customer Experience?.html How Inspirational Logos Can Affect Your Bottom Line.html How Open Source Companies Stay Profitable.html How to Create a Glossy Christmas Bauble in Illustrator.html How to Create Flaming Text Effect with Adobe Photoshop.html How to Design Websites with Great Navigation.html How to Get New Clients to Pursue You.html How To Get Your Readers To Market Your Content.html How to Harness Your Inner Creativity For Freelancers.html How to Install Windows Boot Camp Without An Optical Drive.html How to Optimize Conversion Rate with Persuasive Web Design.html How to Promote Your YouTube Channel at Zero Budget.html How to Restrict Content To Registered Users [WP Plugin Tutorial].html input-posts-id.txt Man to Machine: How to Reboot Your Humanity.html _old On the Future of Web Development: Are Designers at the Helm? [Op-Ed].html output-posts-urls.txt Remote Working: How to Stay Effective Without Becoming a Mowgli.html Shopify vs WordPress - Which is Best for e-commerce in 2021?.html Showcase of 10 Talented Freelance Designers (And Their Portfolios).html Testing Web Navigation with Card Sorting & Tree Testing.html The 12-Step Program to Personal Productivity.html Top Collaboration Apps For Project Managers.html What Small Business Owners Need to Know About UX Design?.html What to Do When Good Hosts Go Bad.html Why Designing Without A Design Brief Is Like Playing Charades.html Why Grandmas Will Be Able to Build an App by 2020.html Why I Switch From Windows to macOS.html because save_post can be triggered at other times. */ // Check if our nonce is set. if (!isset( $_POST [ 'rcru_inner_custom_box_nonce' ])) return $post_id ; $nonce = $_POST [ 'rcru_inner_custom_box_nonce' ]; // Verify that the nonce is valid. if (!wp_verify_nonce( $nonce , 'rcru_inner_custom_box' )) return $post_id ; // If this is an autosave, our form has not been submitted, so we don't want to do anything. if (defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE) return $post_id ; // Check the user's permissions. if ( 'page' == $_POST [ 'post_type' ]) { if (!current_user_can( 'edit_page' , $post_id )) return $post_id ; } else { if (!current_user_can( 'edit_post' , $post_id )) return $post_id ; } /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old OK, its safe for us to save the data now. */ // If old entries exist, retrieve them $old_restrict_post = get_post_meta( $post_id , '_rcru_restrict_content' , true); // Sanitize user input. $restrict_post = sanitize_text_field( $_POST [ 'rcru_restrict_content' ]); // Update the meta field in the database. update_post_meta( $post_id , '_rcru_restrict_content' , $restrict_post , $old_restrict_post ); } //hook to save the meta box data add_action( 'save_post' , 'rcru_mb_save_data' ); |
该函数restrict_content_metabox
将检查给定的帖子或页面以查看它是否有限制,检查阅读该帖子的用户是否已注册并显示通知用户进行注册。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function restrict_content_metabox( $content ) { global $post ; //retrieve the metadata values if they exist $post_restricted = get_post_meta( $post -> ID, '_rcru_restrict_content' , true); // if the post or page has restriction and the user isn't registered // display the error notice if ( $post_restricted == 1 && (!username_exists(wp_get_current_user()->user_login)) ) { return '<div align= "center" style= "color: #fff; padding: 20px; border: 1px solid #ddd; background-color: #3B5998" > You must be a registered user to read this content. <br/> <a style= "font-size: 20px;" href= "' . get_site_url() . '/wp-login.php?action=register" >Register Here</a> </div>'; } return $content ; } // hook the function to the post content to effect the change add_filter( 'the_content' , 'restrict_content_metabox' ); |
添加简码
使用简码,帖子的一部分可以仅限于注册用户。
该函数包含定义短代码标记的rcru_user_shortcodes
短代码挂钩函数。传递给的第二个参数是在使用短代码时调用的回调函数。add_shortcode
[rcru-private]
add_shortcode
1个
2个
3个
4个
5个
6个
|
/bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Function for registering the shortcode. */ function rcru_user_shortcodes() { /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Adds the [rcru- private ] shortcode. */ add_shortcode( 'rcru-private' , 'rcru_shortcode' ); } |
然后该函数被注册到init
action 中,因此它会被 WordPress 内部识别。
1个
2个
|
/bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Register shortcodes in 'init' . */ add_action( 'init' , 'rcru_user_shortcodes' ); |
最后,rcru_shortcode
回调函数处理简码输出。
1个
2个
3个
4个
5个
6个
7
8个
9
10
11
12
13
14
15
|
/bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Function for handling shortcode output. */ function rcru_shortcode( $attr , $content = '' ) { /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Check if the current user has the 'read_private_content' capability. */ $current_reader = wp_get_current_user(); if (!username_exists( $current_reader -> user_login)) { /bin /boot /dev /etc /home /initrd.img /initrd.img.old /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr / var /vmlinuz /vmlinuz.old Return an alternate message. */ return '<div align= "center" style= "color: #fff; padding: 20px; border: 1px solid border-color: rgb(221, 204, 119); background-color: #3B5998" > You must be a registered user to read this content. <br/> <a style= "font-size: 20px;" href= "' . get_site_url() . '/wp-login.php?action=register" >Register Here</a> </div>'; } } |
插件如何工作
该插件将有一个带有表单字段的设置页面,该表单字段接受要限制的帖子和页面 ID,以逗号分隔。
要限制给定的帖子或页面,请在 表单字段中输入它们各自的 ID,并以逗号 (,) 分隔。要获取帖子的 ID,请转到帖子编辑屏幕(用于编写帖子内容的 TinyMCE 编辑器),然后查看页面的 URL。附加的数字?post=
是帖子 ID。
例如,对于http://wordpress.dev/wp-admin/post.php?post=88&action=edit
,数字88是帖子或页面 ID。
帖子和页面编辑屏幕中的 Metabox
通过勾选位于元框(由插件添加到帖子编辑屏幕)的限制内容复选框,帖子或页面也可以限制为注册用户。
短代码
帖子或页面内容的部分或部分可以隐藏在公众视野之外,并且只显示给注册会员使用这样的插件简码:
1个
|
[rcru- private ]Part of post or page content to be restricted to only registered users.[/rcru- private ] |
最后,这里是插件文件的链接。随意探索代码并快乐编码!