javascript - 如何仅针对特定帖子类型将自定义字段数据添加到 Yoast 插件页面分析
问题描述
我有一个名为 book 的自定义帖子类型。Yoast 分析适用于任何自定义帖子类型,但任何其他内容除外,例如来自需要一些操作的自定义字段的内容。到目前为止,我从他们的网站上找到了这个有用的代码,它允许 Yoast 插件检测额外的数据。
链接 - https://developer.yoast.com/customization/yoast-seo/adding-custom-data-analysis/
- 我希望实现的是将当前代码限制为仅在帖子类型为 book 时运行。目前,自定义分析已扩展到每个帖子类型,这意味着
book
内容也将在其他地方可见。 - 从书籍自定义帖子类型的转发器字段中获取内容,并将其替换为此处添加的代码中的文本。
JS代码:
/* global YoastSEO */
class MyCustomDataPlugin {
constructor() {
// Ensure YoastSEO.js is present and can access the necessary features.
if ( typeof YoastSEO === "undefined" || typeof YoastSEO.analysis === "undefined"
|| typeof YoastSEO.analysis.worker === "undefined" ) {
return;
}
YoastSEO.app.registerPlugin( "MyCustomDataPlugin", { status: "ready" } );
this.registerModifications();
}
/**
* Registers the addContent modification.
*
* @returns {void}
*/
registerModifications() {
const callback = this.addContent.bind( this );
// Ensure that the additional data is being seen as a modification to the content.
YoastSEO.app.registerModification( "content", callback, "MyCustomDataPlugin", 10 );
}
/**
* Adds to the content to be analyzed by the analyzer.
*
* @param {string} data The current data string.
*
* @returns {string} The data string parameter with the added content.
* The text below 'Hello, I'm some additional data!' is what needs to be replaced
with the code that will output the repeater field content.
*/
addContent( data ) {
data += "Hello, I'm some additional data!";
return data ;
}
}
/**
* Adds eventlistener to load the plugin.
*/
if ( typeof YoastSEO !== "undefined" && typeof YoastSEO.app !== "undefined" ) {
new MyCustomDataPlugin();
} else {
jQuery( window ).on(
"YoastSEO:ready",
function() {
new MyCustomDataPlugin();
}
);
}
PHP代码:
<?php
// ...
class MyCustomPlugin {
/**
* MyCustomPlugin constructor.
*/
public function __construct() {
// ...
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
}
/**
* Enqueues the plugin file.
*/
public function enqueue_scripts() {
wp_enqueue_script( 'my-custom-plugin', plugins_url( 'js/MyCustomDataPlugin.js', __FILE__ ),
[], '1.', true );
}
}
/**
* Loads the plugin.
*/
function loadMyCustomPlugin() {
new MyCustomPlugin();
}
if ( ! wp_installing() ) {
add_action( 'plugins_loaded', 'loadMyCustomPlugin', 20 );
}
我尝试使用 PHP,但似乎无法将 PHP 与 js 代码一起使用。
谢谢!
解决方案
推荐阅读
- reactjs - 单击一下,我尝试使用索引更改某个对象,但是,这不会导致
- python - Jinja 模板未正确呈现内联样式
- impala - 如何使用 Impala 中某个位置的 3 个 .csv 文件创建表
- date - 无法正确排列带有日期的 googlefinance 公式
- python - 如何在 jupyter 实验室中使用 FileUpload 小部件?
- python - Python 脚本与将内容传输到客户端的 Python Flask 服务器进行通信的最佳方式是什么?
- azure-active-directory - 使用 Terraform 从 azuread_application 获取 oauth2_permissions
- asp.net-core - 从 Visual Studio 发布 Web 应用程序不会更新视图
- c++ - 添加无符号偏移量
- audio - mp3和flac之间的歌曲位置差异。如何解决这个问题?C#