Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RankMath for Posts block #1874

Merged
merged 5 commits into from
Oct 9, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/blocks/blocks/posts/edit.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* External dependencies
*/
import { debounce } from 'lodash';

/**
* WordPress dependencies
*/
Expand Down Expand Up @@ -52,6 +57,7 @@ import {
} from '../../helpers/utility-hooks.js';
import '../../components/store/index.js';
import FeaturedPost from './components/layout/featured.js';
import { domReady } from '../../helpers/frontend-helper-functions';

const { attributes: defaultAttributes } = metadata;

Expand All @@ -65,6 +71,7 @@ const Edit = ({
setAttributes,
clientId
}) => {

useEffect( () => {
const unsubscribe = blockInit( clientId, defaultAttributes );
return () => unsubscribe( attributes.id );
Expand Down Expand Up @@ -184,6 +191,16 @@ const Edit = ({
.map( taxonomy => select( 'core' ).getEntityRecords( 'taxonomy', taxonomy, { per_page: -1 }) ?? [])
.flat();

if ( window?.rankMathEditor ) {

/**
* If RankMath is present on the page, we will refresh the RankMath editor analysis when the posts are updated.
*/
debounce( () => {
window?.rankMathEditor.refresh( 'content' );
}, 500 );
}

return {
posts,
categoriesList: categoriesList,
Expand Down Expand Up @@ -329,4 +346,45 @@ const Edit = ({
);
};

domReady( () => {

/**
* If the RankMath plugin is present on the page, we will sent the content of the posts grid to RankMath for analysis.
*/

/** @type {HTMLScriptElement} */
const rankMathScript = document.querySelector( 'script[src*="rank-math-app"]' );

if ( ! rankMathScript ) {
return;
}

let maxTries = 10;

const init = () => {
window.wp.hooks.addFilter( 'rank_math_content', 'rank-math', () => {

/**
* @type {NodeListOf<HTMLDivElement>} postsHtml - The HTML nodes which contain the relevent post content for RankMath.
*/
const postsHtml = document.querySelectorAll( '.o-posts-grid-post-body' );
return Array.from( postsHtml ).map( ( post ) => post.innerHTML ).join( '' );
});

window?.rankMathEditor?.refresh( 'content' );
};

const t = setInterval( () => {
if ( window?.rankMathEditor ) {
clearInterval( t );
init();
} else {
maxTries--;
if ( 0 === maxTries ) {
clearInterval( t );
}
}
}, 1000 );
});

export default Edit;
Loading