Created
January 10, 2020 13:30
-
-
Save samikeijonen/72929fea16e78d19ec6ce1acc086bf46 to your computer and use it in GitHub Desktop.
Get featured image meta
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import debounce from 'lodash.debounce'; | |
const { subscribe, dispatch, select, withSelect } = wp.data; | |
const { getEditedPostAttribute, isCurrentPostPublished, getCurrentPostType } = select( 'core/editor' ); | |
const { isTyping } = select( 'core/block-editor' ); | |
const { getMedia } = select( 'core' ); | |
const { lockPostSaving, unlockPostSaving } = dispatch( 'core/editor' ); | |
const { createNotice, removeNotice } = dispatch( 'core/notices' ); | |
const { __ } = wp.i18n; | |
// IDs and message for the post locking and notices. | |
const LOCK_KEY = 'DOG_VALIDATE_CREDIT_LOCK'; | |
const NOTICE_ID = 'DOG_REMEMBER_CREDIT'; | |
const MESSAGE = __( 'A post must have Featured image credit field before being published.', 'denofgeek' ); | |
/** | |
* Check do we have credit field. | |
* | |
* @return {boolean} | |
*/ | |
const checkCredit = () => { | |
let passes = false; | |
const featuredImageId = getEditedPostAttribute( 'featured_media' ); | |
console.log( 'featuredImageId', featuredImageId ); | |
if ( featuredImageId && 0 !== featuredImageId ) { | |
const featuredImageInfo = getMedia( featuredImageId ); | |
const credit = featuredImageInfo ? featuredImageInfo.credit : null; | |
if ( credit ) { | |
passes = true; | |
} | |
console.log( 'featuredImageId', featuredImageId, credit ); | |
} | |
return passes; | |
}; | |
/** | |
* Set notice message. | |
*/ | |
const setCreditNotice = () => { | |
if ( ! checkCredit() ) { | |
// Lock post publishing. | |
lockPostSaving( LOCK_KEY ); | |
// Display warning notice. | |
createNotice( | |
'warning', | |
MESSAGE, | |
{ | |
id: NOTICE_ID, | |
isDismissible: false, | |
} | |
); | |
} else { | |
// Unlock post publishing. | |
unlockPostSaving( LOCK_KEY ); | |
// Remove notice. | |
removeNotice( NOTICE_ID ); | |
} | |
}; | |
wp.domReady( () => { | |
// Bail if post is published already. | |
if ( isCurrentPostPublished() ) { | |
return; | |
} | |
// Bail if post type is not 'post'. | |
if ( 'post' !== getCurrentPostType() ) { | |
return; | |
} | |
// Set credit field notice. | |
if ( ! isTyping() ) { | |
subscribe( debounce( setCreditNotice, 1000 ) ); | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment