| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
|
| 3 |
const postTypes = { page: 'pages', post: 'posts' }; |
| 4 |
|
| 5 |
export default async ({ postId, postType }) => { |
| 6 |
// Get all nav menus that are presented in the post/page. |
| 7 |
const postNavigations = Array.from( |
| 8 |
window.document?.querySelectorAll('nav[data-extendify-menu-id]') ?? [], |
| 9 |
) |
| 10 |
.map((nav) => nav.dataset.extendifyMenuId) |
| 11 |
.filter(Boolean); |
| 12 |
|
| 13 |
// get the data about those nav menus |
| 14 |
const navigations = |
| 15 |
postNavigations.length > 0 |
| 16 |
? await apiFetch({ |
| 17 |
method: 'POST', |
| 18 |
path: '/extendify/v1/agent/site-navigation', |
| 19 |
data: { only: postNavigations.join(',') }, |
| 20 |
}).catch(() => []) |
| 21 |
: []; |
| 22 |
|
| 23 |
// we only to update the post url when the post is not a draft. |
| 24 |
if ( |
| 25 |
window.extAgentData?.context && |
| 26 |
window.extAgentData?.context?.postStatus !== 'draft' |
| 27 |
) { |
| 28 |
// When a draft post/page becomes published, we need to update the URL |
| 29 |
// from `?page_id=123` format to the SEO-friendly permalink structure |
| 30 |
// to ensure a proper link in the menu. |
| 31 |
|
| 32 |
let postUrl = window.wp?.data |
| 33 |
?.select('core') |
| 34 |
?.getEntityRecord('postType', postType, postId)?.link; |
| 35 |
|
| 36 |
// fallback if the above fails |
| 37 |
if (!postUrl && postTypes[postType]) { |
| 38 |
const postInfo = await apiFetch({ |
| 39 |
path: `/wp/v2/${postTypes[postType]}/${postId}`, |
| 40 |
}).catch(console.error); |
| 41 |
postUrl = postInfo?.link; |
| 42 |
} |
| 43 |
|
| 44 |
if (postUrl && window.extAgentData?.context) { |
| 45 |
window.extAgentData.context.postUrl = postUrl; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
return { navigations }; |
| 50 |
}; |
| 51 |
|