您正在浏览 未分类的归档。

作者:33ds

bbpress打开可视化编辑工具

2022年5月30日分类:未分类

默认bbpress的可视化编辑是关闭的,打开只需要在functions.php中加入下面的代码:

function bbp_enable_visual_editor( $args = array() ) {
    $args['tinymce'] = true;
    return $args;
}
add_filter( 'bbp_after_get_the_content_parse_args', 'bbp_enable_visual_editor' );

给可视化编辑工具加入更多的自定义功能:

function bbp_enable_visual_editor( $args = array() ) {
    $args['tinymce'] = true;
//只显示可视化工具,关闭html工具
    $args['quicktags'] = false;
    return $args;
}
add_filter( 'bbp_after_get_the_content_parse_args', 'bbp_enable_visual_editor' );

TinyMce高级工具设置

unction bbp_enable_visual_editor( $args = array() ) {
    $args['tinymce'] = true;
    $args['teeny'] = false;
    return $args;
}
add_filter( 'bbp_after_get_the_content_parse_args', 'bbp_enable_visual_editor' );

关闭粘贴文字时删除一些html代码。

function bbp_tinymce_paste_plain_text( $plugins = array() ) {
    $plugins[] = 'paste';
    return $plugins;
}
add_filter( 'bbp_get_tiny_mce_plugins', 'bbp_tinymce_paste_plain_text' );

作者:33ds

修改buddypress的数据库前缀

2022年3月17日分类:未分类

function wpeve_change_table_prefix( $prefix ) {
$prefix='wp_';
return $prefix;
}
add_filter( 'bp_core_get_table_prefix', 'wpeve_change_table_prefix', 10,1 );

作者:33ds

JWT Authentication for WP REST API 在NGINX下的配置

2021年8月19日分类:未分类

JWT Authentication for WP REST API 是使用JSON Web Tokens认证扩展WP REST API作为认证方法。

官方给出了在.htaccess的方法

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

但是在NGINX下并没给出如何配置,其实也很简单。在NGINX的配置下加入

fastcgi_pass_request_headers on;
fastcgi_pass_header Authorization;

在Wp-config.php下加入

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);

your-top-secret-key 可以用https://api.wordpress.org/secret-key/1.1/salt/来生成。

作者:33ds

修改Buddypress和BBpress固定链接的方法

2021年7月31日分类:未分类

BuddyPress和bbpress的默认的固定链接都是通过slug来实现的,slug是什么?slug是文章的别名,通常作为文章的固定链接而存在。当我们用wordpress来发表文章的时候,我们可以修改它,但是如果我们建立群组和发表帖子的时候,我们就无法修改它了,那么要实现ID作为固定链接,目前的方法是修改插件代码。

function action_groups_create_group( $group_id, $member, $group ) {
$group = groups_get_group( $group_id );
$group->slug=$group_id;
if ( ! $group->save() ) {
return false;
}
};
add_action( ‘groups_create_group’, ‘action_groups_create_group’, 10, 3 );

bbpress不用修改插件代码,本方法是将主题的slug修改为主题的id,方法较为简单。

在functions.php中添加如下代码:

add_action( 'save_post', 'using_id_as_slug', 10, 2 );
function using_id_as_slug($post_id, $post){
	if($post->post_type == 'topic'){ //只对topic文章生效
		// 如果是文章的版本,不生效
		if (wp_is_post_revision($post_id))
			return false;
		// 取消挂载该函数,防止无限循环
		remove_action('save_post', 'using_id_as_slug' );
		// 使用文章ID作为文章的别名
		wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
		// 重新挂载该函数
		add_action('save_post', 'using_id_as_slug', 10, 2 );
	}
}

作者:33ds

改变buddpress头像的默认路径

2021年7月30日分类:未分类

有时我们在使用一些第三方插件的时候,有时buddypress的头像上传文件并没有相应的存到第三方,或者需要改变原来的路径,都可以使用下面的方法:

function nfm_bp_avatar_upload_url_correct($url){
$url = "https://www.wpeve.com/wp-content/uploads";
return $url;
}
add_filter('bp_core_avatar_url', 'nfm_bp_avatar_upload_url_correct', 1);

非常简直,只有几行代码,放到functions.php下

作者:33ds

关闭WordPress本身服务器缩略图的生成功能

2021年7月30日分类:未分类

当我们再使用第三方存储的缩图功能时,wordpress本身的缩略图片生成就没有必要了,这可以节约服务器的开销。

这个功能是在我们护维GoldPoster的时候使用到的功能,GoldPoster是一个电影海报网络,每天会上传大量的超大图片,如果再使用本身wordpress的缩略图功能,无疑会给网站带来巨大的压力。

这段代码就是让wordpress误以为自己已经生成了缩略图。

class Fake {


	public function run() {
		\add_filter( 'intermediate_image_sizes_advanced', [ $this, 'getRegisteredImageSizes' ] );
		\add_filter( 'wp_generate_attachment_metadata', [ $this, 'fakeImageResize' ] );
	}

	
	public function getRegisteredImageSizes( $sizes ) {
		$this->sizes = $sizes;

		return [ ];
	}

	public function fakeImageResize( $metadata ) {
		foreach ( $this->sizes as $name => $size ) {
			// figure out what size WP would make this:
			$newsize = \image_resize_dimensions( $metadata['width'], $metadata['height'], $size['width'], $size['height'], $size['crop'] );

			if ( $newsize ) {
				$uploads = \wp_upload_dir( null, false );
				$file    = pathinfo( realpath( $uploads['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'] ) );

				// build the fake meta entry for the size in question
				$metadata['sizes'][ $name ] = [
					'file'   => sprintf( '%s-%sx%s.%s', $file['filename'], $newsize[4], $newsize[5], $file['extension'] ),
					'width'  => $newsize[4],
					'height' => $newsize[5],
				];
			}
		}

		return $metadata;
	}
}

可以直接将这个代码放到functions.php,也可以做成插件使用。

作者:33ds

WordPress插件开发基础-新手入门2

2021年7月26日分类:未分类

构建插件需要注意以下几个问题:

避免命名冲突


当您的插件中的变量、函数或类使用与另一个插件相同的名称时,就会发生命名冲突。

您可以使用以下方法避免命名冲突。

  • 编码方法,默认情况下,所有变量、函数和类都定义在全局命名空间中,这意味着您的插件可以覆盖另一个插件设置的变量、函数和类,反之亦然。在函数或类中定义的变量不受此影响。
  • 使用前缀,所有变量、函数和类都使用唯一标识符作为前缀。前缀可防止其他插件覆盖您的变量或者调用您的函数和类。
  • 检查是否存在相同的名称,PHP 提供了许多函数来验证变量、函数、类和常量的存在。 如果存在,将返回 true。

使用以下验证方法:

变量: isset() (includes arrays, objects, etc.)
函数: function_exists()
类: class_exists()
常量: defined()

示例:

//Create a function called "wporg_init" if it doesn't already exist
if ( !function_exists( 'wporg_init' ) ) {
    function wporg_init() {
        register_setting( 'wporg_settings', 'wporg_option_foo' );
    }
}
 
//Create a function called "wporg_get_foo" if it doesn't already exist
if ( !function_exists( 'wporg_get_foo' ) ) {
    function wporg_get_foo() {
        return get_option( 'wporg_option_foo' );
    }
}
  • 面向对象的方法

解决命名冲突问题的一种更简单的方法是为插件的代码使用一个类。

但仍然需要检查的类的名称是否已经被占用,其余的将由 PHP 处理。

示例:

if ( !class_exists( 'WPOrg_Plugin' ) ) {
    class WPOrg_Plugin
    {
        public static function init() {
            register_setting( 'wporg_settings', 'wporg_option_foo' );
        }
 
        public static function get_foo() {
            return get_option( 'wporg_option_foo' );
        }
    }
 
    WPOrg_Plugin::init();
    WPOrg_Plugin::get_foo();
}

文件的结构:

plugin-name.php与uninstall.php放在插件文件夹的根目录,其余的放在子文件夹下。

示例:
/plugin-name
     plugin-name.php
     uninstall.php
     /languages
     /includes
     /admin
          /js
          /css
          /images
     /public
          /js
          /css
          /images

插件的架构

小型插件,或单一用途插件,不用太细分,如果是大型插件或是方便以后扩展,单独的样式和相关的文件,有助于代码组织和插件的长期维护。

Admin管理代码和前台代码的分离

使用is_admin()

示例:

if ( is_admin() ) {
    // we are in admin mode
    require_once __DIR__ . '/admin/plugin-name-admin.php';
}

架构模式,分为三类:

  • 单个插件文件,包含函数
  • 单个插件文件,包含一个类、实例化的对象和可选的函数
  • 主插件文件,然后是一个或多个类文件

作者:33ds

WordPress插件开发基础-新手入门1

2021年7月26日分类:未分类

一、WordPress插件开发第一步是建立一个插件的文件夹。步骤如下:

1、导航至WorPress的安装目录下的wp-content文件夹。

2、打开plugins文件,Wordpress所有的插件都在这个文件夹下面。

3、新建一个文件夹并对其命名,文件夹的名字就是你插件的名字,如wpeve。

4、打开这个文件夹。

5、新建一个PHP文件,如wpeve.php。

Unix或linux终端大约如下样子:

wordpress $ cd wp-content
wp-content $ cd plugins
plugins $ mkdir wpeve
plugins $ cd wpeve
plugin-name $ vi wpeve.php

二、在wpeve.php最上面用注释行对插件设置一些基本信息,如插件名称,插件网址、插件描述,插件版本等。这些未必全都要,但至少需要一个插件的名称。

/**
 * Plugin Name: 你插件的名字
 */

涉及到的字段有

Plugin Name:插件名称

Plugin URI:插件的网址,可以是你自己的网站页面,如https://www.wpeve.com,但不能是wordpress.org

Description:插件描述

Requires at least:WordPress最低要求版本

Requires PHP:php最低版本要求

Author:插件作者的名字

Author URI:插件作者的网址

License:插件授权,如GPLv2

License URI:全部授权文字链接

Text Domain:本地化

Domain Path:本地化路径,如/languages

Network:插件是否只能在网络范围内激活。 只能设置为 true,不需要时应省略。

Update URI:第三方更新路径

两个示例

/**
 * Plugin Name:       My Basics Plugin
 * Plugin URI:        https://example.com/plugins/the-basics/
 * Description:       Handle the basics with this plugin.
 * Version:           1.10.3
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            John Smith
 * Author URI:        https://author.example.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Update URI:        https://example.com/my-plugin/
 * Text Domain:       my-basics-plugin
 * Domain Path:       /languages
 */
/**
 * Plugin Name
 *
 * @package           PluginPackage
 * @author            Your Name
 * @copyright         2019 Your Name or Company Name
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name:       Plugin Name
 * Plugin URI:        https://example.com/plugin-name
 * Description:       Description of the plugin.
 * Version:           1.0.0
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            Your Name
 * Author URI:        https://example.com
 * Text Domain:       plugin-slug
 * License:           GPL v2 or later
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Update URI:        https://example.com/my-plugin/
 */

授权示例:

/*
{Plugin Name} is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
 
{Plugin Name} is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with {Plugin Name}. If not, see {URI to Plugin License}.
*/

三、插件的启用(Activation)与禁用(Deactivation)

插件的启用与禁用通过相关的钩子完成(wordpress内的功能函数)

启用:register_activation_hook() 

禁用:register_deactivation_hook()

启用示例:

/**
 * 注册一个“book”的自定义类型
 */
function pluginprefix_setup_post_type() {
    register_post_type( 'book', ['public' => true ] ); 
} 
add_action( 'init', 'pluginprefix_setup_post_type' );
 
 
/**
 * 激活插件.
 */
function pluginprefix_activate() { 
    // Trigger our function that registers the custom post type plugin.
    pluginprefix_setup_post_type(); 
    // Clear the permalinks after the post type has been registered.
    flush_rewrite_rules(); 
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );

禁用示例:

/**
 * Deactivation hook.
 */
function pluginprefix_deactivate() {
    // Unregister the post type, so the rules are no longer in memory.
    unregister_post_type( 'book' );
    // Clear the permalinks to remove our post type's rules from the database.
    flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );

插件的卸载,卸载不用于禁用,两者有如下区别:

操作Deactivation Hook(禁用钩子)Uninstall Hook(卸载钩子)
清除缓存和临时文件
更新固定链接
从 {$wpdb->prefix}_options表中清除相关数据
删除数据表

卸载有两种方式:

方式一、register_uninstall_hook

register_uninstall_hook(__FILE__, 'pluginprefix_function_to_run');

方式二、uninstall.php

在插件根目录新建uninstall.php,在插件被删除的时候这个文件将自动运行。

文件运行时,先会检验WP_UNINSTALL_PLUGIN常量。

示例:

// if uninstall.php is not called by WordPress, die
if (!defined('WP_UNINSTALL_PLUGIN')) {
    die;
}
 
$option_name = 'wporg_option';
 
delete_option($option_name);
 
// for site options in Multisite
delete_site_option($option_name);
 
// drop a custom database table
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}mytable");

注意,在多站点中删除插件,遍历所有博客以删除选项可能会占用大量资源。

作者:33ds

BuddyPress Rest API参考

2021年7月25日分类:未分类

如果要开发BuddypRess的APP,或者是微信小程序,下面的API用得上。

  1. Activity http://site.com/wp-json/buddypress/v1/activity
  2. Groups http://site.com/wp-json/buddypress/v1/groups
  3. Group Membership http://site.com/wp-json/buddypress/v1/groups/<group_id>/members
  4. Group Membership Request(s) http://site.com/wp-json/buddypress/v1/groups/{group_id}/membership-request/
  5. Group Avatar http://site.com/wp-json/buddypress/v1/groups/<group_id>/avatar
  6. Group Cover http://site.com/wp-json/buddypress/v1/groups/<group_id>/cover
  7. Group Invites http://site.com/wp-json/buddypress/v1/groups/<group_id>/invites
  8. XProfile Fields http://site.com/wp-json/buddypress/v1/xprofile/fields
  9. XProfile Groups http://site.com/wp-json/buddypress/v1/xprofile/groups
  10. XProfile Data http://site.com/wp-json/buddypress/v1/xprofile/<field_id>/data/<user_id>
  11. Members http://site.com/wp-json/buddypress/v1/members
  12. Members Profile Photo (aka Avatar) http://site.com/wp-json/buddypress/v1/members/<user_id>/avatar
  13. Members Cover http://site.com/wp-json/buddypress/v1/members/<user_id>/cover
  14. Notifications http://site.com/wp-json/buddypress/v1/notifications
  15. Components http://site.com/wp-json/buddypress/v1/components
  16. Messages http://site.com/wp-json/buddypress/v1/messages
  17. Signup http://site.com/wp-json/buddypress/v1/signup
  18. Friends http://site.com/wp-json/buddypress/v1/friends
  19. Blogs http://site.com/wp-json/buddypress/v1/blogs
  20. Blog Avatar http://site.com/wp-json/buddypress/v1/blogs/<id>/avatar

BuddyPress REST API使用手册:

https://developer.buddypress.org/bp-rest-api/

作者:33ds

深入学习BuddyPress之bp_activity和bp_activity_meta表

2021年7月25日分类:未分类

BuddyPress作为Wordpress的重要社交插件,提供了用户系统,动态,群组,通知,消息等社交软件的基础功能。其中动态功能属于社交软件中必不可少的组成部分。

在BuddyPress相关数据表中,bp_activity和bp_activity_meta两张表负责了动态功能的数据存储。BuddyPress和WordPress一样,都采用了主表(bp_activity-BuddyPress,posts-WordPress),辅助表(bp_activity_meta-BuddyPress,postmeta-WordPress)的结构,bp_activity存储动态内容的相关信息,wp_activity_meta存储与动态内容相关联的一些信息。

我们先来看看两张表的字段(这里我们只介绍主要的字段)。

bp_activity的字段有action,component,content,is_spam,item_id

  • action字段,其内容是某某用户“发布了更新”,或者“更改了他们的资料图片”,“发布了一条新的动态评论”.
  • component字段, 这个是存储的是动态是在什么模块下产生的,如果是在动态activity下发布,则存储component,如果是用户更改资料,则存储members.
  • content,存储动态内容。
  • is_spam字段,是否为垃圾内容,默认为0,当设定为垃圾动态时,为1
  • item_id字段,当动态有评论时,存储父动态的id.默认为0

bp_activity_meta的字段比较少,与postmeta表一样,activity_id,meta_key,meta_value。这里不做具体介绍,从字面意思就可以看出,meta_key存键,meta_value为键值。比如动态中的收藏功能的meta_key为favorite_count。

在BuddyPress中添加新动态的功能函数是bp_activity_add()

用法:

$activity_id = bp_activity_add( $args );

参数:

$args An array that describes the activity item that you’re creating. Possible values:

  • 'id'
    (optional) Pass a numerical id to update an existing activity item
  • 'action'
    An HTML string summarizing the activity item, which is used by the template when displaying the activity item. Usually contains links to related users, groups, etc. E.g., '<a href="http://example.com/members/bill">Bill</a> created the group <a href="http://example.com/groups/tmnt">TMNT</a>'
  • 'content'
    (optional) The string content of the activity item. In the case of a blog post, for example, you might use an excerpt from the post content. In some cases, it’s appropriate for activity items not to have any content for this field – e.g., when a user creates a new group.
  • 'component'
    A string denoting the unique “component” that this activity item is associated with. BuddyPress components are ‘groups’, ‘members’, etc. If you are writing a BuddyPress plugin, you might consider having a single component name for all activity in your plugin.
  • 'type'
    A string denoting the specific kind of activity being created. This should be more specific than 'component'. For example, when creating a group, BuddyPress posts an activity item with the component ‘groups’ and the type ‘created_group’. 'type' is used for filtering, as in the “New Groups”, “New Blog Posts”, etc dropdown on Activity directories.
  • 'primary_link'
    (optional) The primary URL associated with the activity item. BuddyPress uses this value when creating activity RSS feeds, to tell the feed reader where to find the original item. If you omit this value, the fallback value is the permalink page for the single activity item.
  • 'user_id'
    (optional) The unique numeric id of the user associated with the activity item. In BuddyPress, the primary use of this value is to filter which items appear on the Activity tab of an individual member’s profile. If the value is omitted, it will default to the id of the currently logged-in user. Note that you can pass 0 for items that may be associated with no user at all.
  • 'item_id'
    (optional) The numeric ID of the primary item associated with this activity item. For example, when recording the creation of a group, BuddyPress sets the 'item_id' to the numeric id of the newly created group. This value can be used for filtering.
  • 'secondary_item_id'
    (optional) A second numeric ID for further filtering. For example, when recording a new blog comment, BuddyPress sets the 'item_id' to the ID of the blog, and the 'secondary_item_id' to the ID of the comment.
  • 'recorded_time'
    (optional) The time the activity is recorded. Should be in GMT, MySQL format. (In PHP, date( 'Y-m-d H:i:s', $time ).) Defaults to the current time.
  • 'hide_sitewide'
    (optional) 'hide_sitewide' is used in a few different ways:
    • To prevent duplicate entries when viewing the sitewide activity stream. For instance, when a new friendship is established, two activity items are created: one with 'user_id' set to the user who sent the request and 'item_id' set to recipient, and the other one vice versa. We need both items so that both users see the item on their own profiles, but it’s not desirable to see both of them on the sitewide stream, so the second one is marked 'hide_sitewide' => true.
    • To prevent activity items from hidden or private groups from appearing in sitewide activity streams. That is, when an activity item is posted to a non-public group, 'hide_sitewide' is set to false. Then, when viewing the group’s activity stream (which is accessible only to members), BP includes 'hide_sitewide' items; in contrast, the sitewide stream excludes these items.
    Thus, 'hide_sitewide' is used simultaneously for preventing duplicates and for privacy. Please be sure you understand the way that 'hide_sitewide' works before attempting to use it for the purposes of privacy in your own plugins.
  • 'is_spam'
    (optional) Set to true to mark an item as spam.
返回值

New database row activity ID

Source File

bp_activity_add() is located in bp-activity/bp-activity-functions.php

跳至工具栏