首页 > 解决方案 > 如何仅针对特定帖子类型将自定义字段数据添加到 Yoast 插件页面分析

问题描述

我有一个名为 book 的自定义帖子类型。Yoast 分析适用于任何自定义帖子类型,但任何其他内容除外,例如来自需要一些操作的自定义字段的内容。到目前为止,我从他们的网站上找到了这个有用的代码,它允许 Yoast 插件检测额外的数据。

链接 - https://developer.yoast.com/customization/yoast-seo/adding-custom-data-analysis/

  1. 我希望实现的是将当前代码限制为仅在帖子类型为 book 时运行。目前,自定义分析已扩展到每个帖子类型,这意味着book内容也将在其他地方可见。
  2. 从书籍自定义帖子类型的转发器字段中获取内容,并将其替换为此处添加的代码中的文本。

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 代码一起使用。

谢谢!

标签: javascriptphpwordpressyoast

解决方案


推荐阅读