wordpress指定文章内容需要登录才能查看的插件代码,附带了经典编辑器的快捷方式。
以前都是直接改的文章页面或者主题的functions.php文件,今天为了更方便就直接让ai写的一大半代码,再加上自己修改了下。
手动加入就是:[login-restricted] 需要登录才能看见的内容 [/login-restricted] ,只会隐藏这里面的内容,其他不影响。
主要的Custom Login Restriction.php文件代码:
<?php /* Plugin Name: Custom Login Restriction Description: 需要登录才能查看内容. Version: 1.0 Author: summer */ // 当用户尝试访问受限制的内容时触发 function custom_restrict_content($content) { // 检查是否在文章页面 if (is_single() && !is_user_logged_in()) { // 使用正则表达式替换 [login-restricted] 和 [/login-restricted] 之间的内容 $content = preg_replace('/\[login-restricted\](.*?)\[\/login-restricted\]/s', wp_kses_post('<p>请登录后查看内容。</p>'), $content); } return $content; } add_filter('the_content', 'custom_restrict_content'); // 处理登录后仅隐藏短代码标记 function custom_hide_shortcode($atts, $content = null) { if (!is_user_logged_in()) { return wp_kses_post('<p>请登录后查看内容。</p>'); } return do_shortcode($content); } add_shortcode('login-restricted', 'custom_hide_shortcode'); // 添加按钮到编辑器 function custom_add_editor_button() { if (current_user_can('edit_posts')) { add_filter('mce_external_plugins', 'custom_add_plugin'); add_filter('mce_buttons', 'custom_register_button'); } } add_action('admin_head', 'custom_add_editor_button'); // 注册插件脚本 function custom_add_plugin($plugin_array) { $plugin_array['custom_button'] = plugins_url('/custom-login-restriction/logineditorbutton.js'); return $plugin_array; } // 在编辑器中注册按钮 function custom_register_button($buttons) { array_push($buttons, 'custom_button'); return $buttons; } ?>
logineditorbutton.js的代码:
(function() { tinymce.PluginManager.add('custom_button', function(editor, url) { editor.addButton('custom_button', { text: '限制登录查看', icon: false, onclick: function() { editor.execCommand('mceInsertContent', false, '[login-restricted]在这里放入受限制的内容[/login-restricted]'); } }); }); })();