Skip to content

Commit

Permalink
Merge pull request #1874 from Codeinwp/feat/posts-rank-math
Browse files Browse the repository at this point in the history
Add RankMath for Posts block
  • Loading branch information
HardeepAsrani authored Oct 9, 2023
2 parents d5f0cb8 + e14821a commit 6b995ac
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 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,37 @@ 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.
*/
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;

0 comments on commit 6b995ac

Please sign in to comment.