wordpress 自定义

tech2022-10-15  119

wordpress 自定义

WordPress makes it very easy to embed content. For example, you can grab a YouTube URL, drop it into the post editor, and automatically see a video embedded in your post. This is all powered by oEmbed, an open standard for how a page should provide embed code data.

WordPress使嵌入内容变得非常容易。 例如,您可以获取YouTube URL,将其放入帖子编辑器中,然后自动查看帖子中嵌入的视频。 这全部由oEmbed提供支持, oEmbed是页面应如何提供嵌入代码数据的开放标准。

WordPress relies on this standard in order to fetch and display a provided URL. While WordPress has long been able to consume oEmbed providers like YouTube, with the inclusion of the WP-API in WordPress 4.4, WordPress can now function as an oEmbed provider. This means other sites can embed your WordPress content on their sites as easily as you can currently embed videos as mentioned in the example above.

WordPress依靠此标准来获取和显示提供的URL。 尽管WordPress长期以来一直可以使用YouTube之类的嵌入式服务提供商,但WordPress 4.4中包含了WP-API ,WordPress现在可以用作嵌入式服务提供商。 这意味着其他站点可以像上面示例中提到的那样当前轻松地将视频嵌入WordPress内容。

The new oEmbed provider functionality leverages the WP-API to return JSON or XML structured embed data to oEmbed consumers, giving them the information they need to embed the page on their own. Like everything in WordPress, the oEmbed provider functionality is easily modifiable with actions and filters. Let’s take a look at how we can use these hooks to embed a custom post type.

新的oEmbed提供程序功能利用WP-API将JSON或XML结构的嵌入数据返回给oEmbed消费者,从而为他们提供了自己嵌入页面所需的信息。 像WordPress中的所有内容一样,oEmbed提供程序功能可以通过action和filter轻松修改。 让我们看一下如何使用这些挂钩来嵌入自定义帖子类型。

我们将要建设的 (What We’ll Be Building)

We’re going to be building a simple plugin, ‘Status Update’, which registers a custom post type (CPT), status-update. This CPT simply removes the title input in the post editor, making it function like a Facebook or Twitter status update. We’ll customize the oEmbed output of this post to show the user’s name and avatar. You can see the final product in this GitHub repo.

我们将要构建一个简单的插件“状态更新”,该插件注册自定义帖子类型(CPT),即status-update 。 该CPT只需删除帖子编辑器中的标题输入,使其功能类似于Facebook或Twitter状态更新。 我们将自定义此帖子的oEmbed输出,以显示用户的姓名和头像。 您可以在此GitHub存储库中查看最终产品。

设置插件 (Setting up the Plugin)

Go to your plugins folder in wp-content and create a folder named sp-status-update. In that directory, create a file named sp-status-update.php. This is where we’ll be creating the plugin’s main class. Add the plugin header to the top of the file:

转到wp-content plugins文件夹,然后创建一个名为sp-status-update的文件夹。 在该目录中,创建一个名为sp-status-update.php的文件。 这是我们将创建插件的主类的地方。 将插件标头添加到文件顶部:

/** * Plugin Name: Status Update * Plugin URI: https://github.com/mAAdhaTTah/sitepoint-status-update * Description: Post your own Facebook-like status updates * Version: 1.0.0 * Author: James DiGioia for SitePoint * Author URI: http://jamesdigioia.com * Text Domain: wp-status-update * Languages: /languages */

We’ll then set up the main plugin singleton on which we’ll build our plugin:

然后,我们将建立主插件单例,以在其上构建插件:

class SP_Status_Update { /** * Plugin instance. * * @var static */ protected static $instance; /** * Retrieve the plugin instance. * * @return static */ public static instance() { if (null === static::$instance) { static::$instance = new static; } return static::$instance; } /** * Plugin constructor. */ protected function __construct() { // Add actions/filters here } }

Finally, we need to start the plugin at the bottom of the file:

最后,我们需要在文件底部启动插件:

SP_Status_Update::instance();

We’ll be adding our hooks and filters in the constructor, as noted in the comment.

如注释中所述,我们将在构造函数中添加钩子和过滤器。

注册自定义帖子类型 (Register a Custom Post Type)

Using the excellent GenerateWP, we can easily customize and register our custom post type. Register the method with WordPress:

使用出色的GenerateWP ,我们可以轻松自定义和注册自定义帖子类型。 用WordPress注册方法:

add_action( 'init', array( $this, 'register_post_type' ), 0 );

and add the registration method to your class:

并将注册方法添加到您的班级:

/** * Register the Status Update custom post type. */ public function register_post_type() { $labels = array( 'name' => _x( 'Status Updates', 'Post Type General Name', 'sp-status-update' ), 'singular_name' => _x( 'Status Update', 'Post Type Singular Name', 'sp-status-update' ), 'menu_name' => __( 'Status Update', 'sp-status-update' ), 'name_admin_bar' => __( 'Status Update', 'sp-status-update' ), 'archives' => __( 'Satus Update Archives', 'sp-status-update' ), 'parent_item_colon' => __( 'Parent Update:', 'sp-status-update' ), 'all_items' => __( 'All Updates', 'sp-status-update' ), 'add_new_item' => __( 'Add New Status Update', 'sp-status-update' ), 'add_new' => __( 'Add New', 'sp-status-update' ), 'new_item' => __( 'New Status Update', 'sp-status-update' ), 'edit_item' => __( 'Edit Status Update', 'sp-status-update' ), 'update_item' => __( 'Update Status Update', 'sp-status-update' ), 'view_item' => __( 'View Status Update', 'sp-status-update' ), 'search_items' => __( 'Search Status Updates', 'sp-status-update' ), 'not_found' => __( 'Not found', 'sp-status-update' ), 'not_found_in_trash' => __( 'Not found in Trash', 'sp-status-update' ), 'featured_image' => __( 'Featured Image', 'sp-status-update' ), 'set_featured_image' => __( 'Set featured image', 'sp-status-update' ), 'remove_featured_image' => __( 'Remove featured image', 'sp-status-update' ), 'use_featured_image' => __( 'Use as featured image', 'sp-status-update' ), 'insert_into_item' => __( 'Insert into Status Update', 'sp-status-update' ), 'uploaded_to_this_item' => __( 'Uploaded to this Status Update', 'sp-status-update' ), 'items_list' => __( 'Status Updates list', 'sp-status-update' ), 'items_list_navigation' => __( 'Status Updates list navigation', 'sp-status-update' ), 'filter_items_list' => __( 'Filter Status Updates list', 'sp-status-update' ), ); $args = array( 'label' => __( 'Status Update', 'sp-status-update' ), 'description' => __( 'Simple Status Update', 'sp-status-update' ), 'labels' => $labels, 'supports' => array( 'editor', 'author', ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'sp_status_update', $args ); }

Now we’re ready to start customizing our oEmbed output!

现在我们准备开始自定义oEmbed输出!

开始之前:嵌入的工作方式 (Before We Start: How oEmbed Works)

When you drop a link into the TinyMCE editor, how does it know how to embed that URL live in your editor?

当您将链接拖放到TinyMCE编辑器中时,它如何知道如何将URL实时嵌入编辑器中?

The first step is discovery. oEmbed asks providers “to make their oEmbed support discoverable by adding elements to the head of their existing (X)HTML documents.”. Those elements direct oEmbed consumers to the API endpoints, which then provide a structured representation of the embedded post. oEmbed supports both JSON and XML formats.

第一步是发现。 oEmbed要求提供者“通过在现有(X)HTML文档的开头添加元素来使其oEmbed支持变得可发现。”。 这些元素将嵌入的使用者定向到API端点,然后这些API端点提供嵌入式帖子的结构化表示。 oEmbed支持JSON和XML格式。

WordPress includes elements and support for both formats. The function [wp_oembed_add_discovery_links], which is registered on wp_head, is responsible for including the proper <head> tags and can be customized with the oembed_discovery_links filter.

WordPress包含两种格式的元素和支持。 注册在wp_head上的函数[wp_oembed_add_discovery_links]负责包括正确的<head>标记,并且可以使用oembed_discovery_links过滤器进行自定义。

From there, the editor grabs the structured version from the API endpoint. The JSON response looks like this:

从那里,编辑器从API端点获取结构化版本。 JSON响应如下所示:

{ "version": "1.0", "provider_name": "Website Name", "provider_url": "http://example.com", "author_name": "admin", "author_url": "http://example.com/author/admin/", "title": "", "type": "rich", "width": 600, "height": 338, "html": "long string of html" }

The XML response is structured the same way, and WordPress provides support for both. It leverages the WP-API to provide both the JSON and XML formatted responses, although the XML response required special handling.

XML响应的结构相同,WordPress对此提供了支持。 尽管XML响应需要特殊处理,但它利用WP-API来提供JSON和XML格式的响应。

The editor uses this response, sanitizing the html key and injecting it into the page. In WordPress, the oEmbed HTML contains a blockquote with the post title , a <script> tag for safely and correctly handling iframe messages, and a sandboxed iframe. This HTML can be fetched with [get_post_embed_html] and filtered with embed_html.

编辑器使用此响应,清理html键并将其注入到页面中。 在WordPress中,oEmbed HTML包含带有帖子标题的blockquote ,用于安全正确处理iframe消息的<script>标记以及沙盒iframe 。 可以使用[get_post_embed_html]提取此HTML,并使用embed_html过滤。

The iframe URL is where all the magic happens. By default, it imports the built-in embed template, but you can override it completely and use your own embed template. Use the embed_template filter and return your own template file to swap it out completely:

iframe URL是发生所有魔术的地方。 默认情况下,它会导入内置的嵌入模板,但是您可以完全覆盖它并使用自己的嵌入模板。 使用embed_template过滤器并返回您自己的模板文件以将其完全替换掉:

add_filter( 'embed_template', 'my_embed_template' ); function my_embed_template( $template ) { if ( 'custom_post_type' === get_post_type() ) { return '/path/to/custom-embed-template.php'; } return $template; }

For the most part, you’re not going to need to customize any of the above filters, but it’s good to familiarize yourself with the internals of the oEmbed provider in order to leverage it more effectively. If you need that power, it’s there. We’re going to modify the built-in template with the hooks and filters it makes available to us.

在大多数情况下,您不需要自定义上述任何过滤器,但是最好熟悉oEmbed提供程序的内部结构,以便更有效地利用它。 如果您需要那种力量,那就在那里。 我们将使用提供给我们的挂钩和过滤器来修改内置模板。

自定义嵌入标题 (Customizing the oEmbed Title)

Since the plugin is embedding a status update, the first thing we should do is remove the title from the output of the oEmbed. To do that, we need to hook into the the_title filter:

由于该插件嵌入了状态更新,因此我们首先要做的是从oEmbed的输出中删除标题。 为此,我们需要插入the_title过滤器:

add_filter( 'the_title', array( $this, 'remove_embed_title' ), 10, 2 );

In the remove_embed_title, we’ll meet the first helper function provided: is_embed. This function returns true when we’re in the oEmbed context, which we can use to customize the oEmbed output.

在remove_embed_title ,我们将遇到提供的第一个帮助函数: is_embed 。 当我们处于oEmbed上下文中时,此函数返回true ,可用于自定义oEmbed输出。

Here’s how we remove the title:

我们删除标题的方法如下:

/** * Remove the title from the Status Update oembed. * * @param string $title Post title. * @param int $id Post ID. * * @return string */ public function remove_embed_title( $title, $id ) { $post = get_post( $id ); if ( is_embed() && 'sp_status_update' === $post->post_type ) { return ''; } return $title; }

This ensures the title is only removed in the oEmbed. Now, if we were building this plugin out in a more complete way, we may not need to include the is_oembed check, as you’ll probably just remove it everywhere, but this demonstrates how we can target and customize the oEmbed title output.

这样可以确保仅在oEmbed中删除标题。 现在,如果我们以更完整的方式构建此插件,则可能不需要包括is_oembed检查,因为您可能只是将其删除,但这说明了我们如何定位和自定义oEmbed标题输出。

自定义嵌入的节选 (Customizing the oEmbed Excerpt)

Because the Status Updates are supposed to be small pieces of writing, we don’t want to display an excerpt but the entirety of the post. We can modify what gets excerpted by filtering the the_excerpt_embed hook:

由于状态更新应该是一小篇文章,因此我们不想显示摘录,而是显示整个帖子。 我们可以通过过滤the_excerpt_embed钩子来修改摘录的the_excerpt_embed :

add_filter( 'the_excerpt_embed', array( $this, 'get_excerpt_embed' ) );

We then check if the current post type is our custom post type, and if it is, we return the full content output:

然后,我们检查当前帖子类型是否是我们的自定义帖子类型,如果是,则返回完整内容输出:

/** * Returns the custom excerpt for the custom post type. * * @param string $output Default embed output. * @return string Customize embed output. */ public function get_excerpt_embed( $output ) { if ( 'sp_status_update' === get_post_type() ) { return get_the_content(); } return $output; }

This ensures the excerpt is always the full post content for the Status Update. In the iframe, that excerpt is output in a div with class wp-embed-excerpt, to which you could apply custom styles. If you wanted to do something more complex, like a calendar event, you could output your custom content in that div, or you could append your own content with the embed_content action.

这样可以确保摘录始终是状态更新的完整帖子内​​容。 在iframe中,该摘录在wp-embed-excerpt类的div输出,您可以在其中应用自定义样式。 如果您想做一些更复杂的事情(例如日历事件),则可以在该div输出自定义内容,或者可以将自己的内容附加到embed_content操作中。

向oEmbed添加额外内容 (Adding Extra Content to oEmbed)

The oembed_content action fires right after the excerpt is output, providing a location between the excerpt and the footer to output your own custom HTML. For the Status Update plugin, we’re going to use it to output the author’s name and avatar. First, we add the action:

摘录输出后oembed_content触发oembed_content动作,在摘录和页脚之间提供一个位置,以输出您自己的自定义HTML。 对于状态更新插件,我们将使用它来输出作者的姓名和头像。 首先,我们添加操作:

add_action( 'embed_content', array( $this, 'embed_author' ) );

We can use this action hook to echo out our custom HTML:

我们可以使用该动作挂钩来回显我们的自定义HTML:

/** * Add the author div to the embed iframe. */ public function embed_author() { if ( 'sp_status_update' !== get_post_type() ) { return; } $output = '<div class="wp-embed-author">'; $output .= '&mdash; '; $output .= get_the_author(); $output .= get_avatar( get_the_author_meta( 'ID' ), 20 ); $output .= '</div>'; echo $output; }

We have a simple emdash, the authors name, and the author’s avatar. Again, if you need more extensive customization, this action gives an opportunity to output any additional custom HTML.

我们有一个简单的符号,作者姓名和作者的头像。 同样,如果您需要更广泛的自定义,则此操作使您有机会输出任何其他自定义HTML。

向oEmbed添加自定义样式和脚本 (Adding Custom Styles and Scripts to oEmbed)

Like a standard template page, the oEmbed template has a header and footer. The hook embed_head gives you a location to enqueue your own styles in the head of the template. Like we have been, attach your method to the hook:

像标准模板页面一样,oEmbed模板具有页眉和页脚。 钩子embed_head为您提供了一个位置,可以在模板的head加入自己的样式。 像我们以前一样,将您的方法附加到钩子上:

add_action( 'embed_head', array( $this, 'embed_styles' ) );

We can use this hook to enqueue our own styles with the standard wp_enqueue_style function, or if we don’t have that many styles to include, we can echo it out directly in the head:

我们可以使用该钩子将自己的样式与标准wp_enqueue_style函数一起排入wp_enqueue_style ,或者,如果我们没有太多样式要包含,则可以直接在头部回显它:

/** * Embed the plugin's custom styles */ public function embed_styles() { echo <<<CSS <style> .wp-embed-excerpt, .wp-embed-author { font-size: 24px; line-height: 24px; margin-bottom: 5px; } .wp-embed-author { float: right; } </style> CSS; }

On the JavaScript side, we can do the same using the embed_footer action, including using the wp_enqueue_script function to enqueue new JavaScript files, or output any custom JavaScript directly in-line.

在JavaScript方面,我们可以使用embed_footer操作执行相同的操作,包括使用wp_enqueue_script函数将新JavaScript文件wp_enqueue_script ,或者直接在线输出任何自定义JavaScript。

结论 (Conclusion)

These are the primary hooks you’ll need to interact with in order transform the output to your preferences. All of the code in this tutorial can be found in the GitHub repo.

这些是您需要与之交互的主要挂钩,以便将输出转换为您的首选项。 本教程中的所有代码都可以在GitHub repo中找到。

If you want to see these customizations in action, keep an eye on the next version of WP-Gistpen, which will leverage the WordPress oEmbed provider in order to embed syntax highlighted code snippets.

如果您想了解这些自定义的实际效果,请关注WP-Gistpen的下一个版本,该版本将利用WordPress oEmbed提供程序来嵌入突出显示语法的代码段。

How are you planning on using the oEmbed provider feature in WordPress? Let me know in the comments!

您打算如何在WordPress中使用oEmbed提供程序功能? 在评论中让我知道!

翻译自: https://www.sitepoint.com/customizing-wordpress-oembed-content/

wordpress 自定义

最新回复(0)