diff --git a/blocks/content-aggregator/block.json b/blocks/content-aggregator/block.json index 95bd5aa..7799fe7 100644 --- a/blocks/content-aggregator/block.json +++ b/blocks/content-aggregator/block.json @@ -9,7 +9,7 @@ "attributes": { "customPostType": { "type": "string", - "default": "post,posts" + "default": "post" }, "taxonomies": { "type": "array", @@ -89,8 +89,8 @@ "default": "" }, "customTaxonomy": { - "type": "string", - "default": "" + "type": "array", + "default": [] }, "termID": { "type": "number", diff --git a/blocks/content-aggregator/edit.js b/blocks/content-aggregator/edit.js index 92ba83a..b6865b3 100644 --- a/blocks/content-aggregator/edit.js +++ b/blocks/content-aggregator/edit.js @@ -234,25 +234,40 @@ export default function ContentAggregatorEdit( props ) { } } ); - // Handle deprecated taxonomy attributes if needed. + // Handle a case where customPostType has multiple slugs (e.g. document,document). if ( - isStillMounted.currrent && - ( attributes.customTaxonomy || attributes.termID ) + attributes.customPostType && + attributes.customPostType !== + attributes.customPostType.split( ',' )[ 0 ] ) { - const taxonomy = [ - { - slug: attributes.customTaxonomy, - terms: [ `${ attributes.termID }` ], - }, - ]; - setAttributes( { - taxonomies: taxonomy, - customTaxonomy: undefined, - termID: undefined, + customPostType: attributes.customPostType.split( ',' )[ 0 ], } ); } + // Handle deprecated attributes. + if ( + isStillMounted.current && + ( attributes.customTaxonomy || attributes.termID ) + ) { + // If customTaxonomy is an array of data, copy it to the taxonomies attribute. + if ( + ! taxonomies?.length && + Array.isArray( attributes.customTaxonomy ) + ) { + setAttributes( { + taxonomies: attributes.customTaxonomy, + customTaxonomy: undefined, + } ); + } + + // If taxonomies is already an array and customTaxonomy is set, just remove + // the customTaxonomy attribute. + if ( Array.isArray( taxonomies ) && attributes.customTaxonomy ) { + setAttributes( { customTaxonomy: undefined } ); + } + } + return () => { isStillMounted.current = false; }; diff --git a/build/content-aggregator.asset.php b/build/content-aggregator.asset.php index 470063a..69ae553 100644 --- a/build/content-aggregator.asset.php +++ b/build/content-aggregator.asset.php @@ -1 +1 @@ - array('react', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-core-data', 'wp-data', 'wp-date', 'wp-element', 'wp-hooks', 'wp-html-entities', 'wp-i18n', 'wp-primitives', 'wp-url'), 'version' => '64a3091040ebcfb8a459'); + array('react', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-core-data', 'wp-data', 'wp-date', 'wp-element', 'wp-hooks', 'wp-html-entities', 'wp-i18n', 'wp-primitives', 'wp-url'), 'version' => '4875b3dfffe42b9cab2b'); diff --git a/build/content-aggregator.js b/build/content-aggregator.js index ff07552..c586998 100644 --- a/build/content-aggregator.js +++ b/build/content-aggregator.js @@ -1 +1 @@ -(()=>{var e={184:(e,t)=>{var o;!function(){"use strict";var a={}.hasOwnProperty;function l(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var a in t)o.o(t,a)&&!o.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e=window.React,t=window.wp.blocks,a=window.wp.primitives,l=JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"happyprime/content-aggregator","title":"Content Aggregator","category":"widgets","description":"A list of posts for a custom post type and/or taxonomy.","keywords":["recent","latest","custom","post type"],"attributes":{"customPostType":{"type":"string","default":"post,posts"},"taxonomies":{"type":"array","items":{"type":"object"}},"taxRelation":{"type":"string","default":""},"itemCount":{"type":"integer","default":3},"order":{"type":"string","default":"desc"},"orderBy":{"type":"string","default":"date"},"displayPostDate":{"type":"boolean","default":false},"postLayout":{"type":"string","default":"list"},"columns":{"type":"integer","default":2},"displayPostContent":{"type":"boolean","default":false},"postContent":{"type":"string","default":"excerpt"},"excerptLength":{"type":"number","default":55},"displayImage":{"type":"boolean","default":false},"imageSize":{"type":"string","default":"thumbnail"},"stickyPosts":{"type":"boolean","default":true},"addLinkToFeaturedImage":{"type":"boolean","default":false},"authors":{"type":"string"},"displayPostAuthor":{"type":"boolean","default":false},"orderByMetaKey":{"type":"string","default":""},"orderByMetaOrder":{"type":"string","default":""},"customTaxonomy":{"type":"string","default":""},"termID":{"type":"number","default":0}},"supports":{"align":true,"html":false},"editorScript":"file:../../build/content-aggregator.js","editorStyle":"file:../../build/content-aggregator.css"}');var n=o(184),s=o.n(n);const r=window.wp.apiFetch;var c=o.n(r);const i=window.wp.blockEditor,m=window.wp.components,p=window.wp.data,u=window.wp.date,d=window.wp.element,g=window.wp.hooks,h=window.wp.i18n,y=(0,d.createElement)(a.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,d.createElement)(a.Path,{d:"M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21ZM15.5303 8.46967C15.8232 8.76256 15.8232 9.23744 15.5303 9.53033L13.0607 12L15.5303 14.4697C15.8232 14.7626 15.8232 15.2374 15.5303 15.5303C15.2374 15.8232 14.7626 15.8232 14.4697 15.5303L12 13.0607L9.53033 15.5303C9.23744 15.8232 8.76256 15.8232 8.46967 15.5303C8.17678 15.2374 8.17678 14.7626 8.46967 14.4697L10.9393 12L8.46967 9.53033C8.17678 9.23744 8.17678 8.76256 8.46967 8.46967C8.76256 8.17678 9.23744 8.17678 9.53033 8.46967L12 10.9393L14.4697 8.46967C14.7626 8.17678 15.2374 8.17678 15.5303 8.46967Z"})),_=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},(0,d.createElement)(a.Path,{d:"M10 1c-5 0-9 4-9 9s4 9 9 9 9-4 9-9-4-9-9-9zm0 16c-3.9 0-7-3.1-7-7s3.1-7 7-7 7 3.1 7 7-3.1 7-7 7zm1-11H9v3H6v2h3v3h2v-3h3V9h-3V6zM10 1c-5 0-9 4-9 9s4 9 9 9 9-4 9-9-4-9-9-9zm0 16c-3.9 0-7-3.1-7-7s3.1-7 7-7 7 3.1 7 7-3.1 7-7 7zm1-11H9v3H6v2h3v3h2v-3h3V9h-3V6z"})),b=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,d.createElement)(a.Path,{d:"m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z"})),v=(0,d.createElement)(a.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,d.createElement)(a.Path,{d:"M4 4v1.5h16V4H4zm8 8.5h8V11h-8v1.5zM4 20h16v-1.5H4V20zm4-8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2z"})),f=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,d.createElement)(a.Path,{d:"m3 5c0-1.10457.89543-2 2-2h13.5c1.1046 0 2 .89543 2 2v13.5c0 1.1046-.8954 2-2 2h-13.5c-1.10457 0-2-.8954-2-2zm2-.5h6v6.5h-6.5v-6c0-.27614.22386-.5.5-.5zm-.5 8v6c0 .2761.22386.5.5.5h6v-6.5zm8 0v6.5h6c.2761 0 .5-.2239.5-.5v-6zm0-8v6.5h6.5v-6c0-.27614-.2239-.5-.5-.5z",fillRule:"evenodd",clipRule:"evenodd"})),w=window.wp.url,x=window.wp.coreData,C={who:"authors",per_page:-1,_fields:"id,name",context:"view"};function E({value:t,onChange:o}){const a=(0,p.useSelect)((e=>{const{getUsers:t}=e(x.store);return t(C)}),[]);if(!a)return null;const l=(e=>{const t=e?.reduce(((e,t)=>{const{mapById:o,mapByName:a,names:l}=e;return o[t.id]=t,a[t.name]=t,l.push(t.name),e}),{mapById:{},mapByName:{},names:[]});return{entities:e,...t}})(a),n=(t?t.toString().split(","):[]).reduce(((e,t)=>{const o=l.mapById[t];return o&&e.push({id:t,value:o.name}),e}),[]);return(0,e.createElement)(m.FormTokenField,{label:(0,h.__)("Authors"),value:n,suggestions:l.names,onChange:e=>{const t=Array.from(e.reduce(((e,t)=>{const o=((e,t)=>{const o=t?.id||e[t]?.id;if(o)return o})(l.mapByName,t);return o&&e.add(o),e}),new Set));o(t.join(","))}})}const k=window.wp.htmlEntities;function P(t){const{blockProps:o}=t,{attributes:a,setAttributes:l}=o,{customPostType:n,orderByMetaKey:s,orderByMetaOrder:r}=a,[i,p]=(0,d.useState)([]),u=(0,d.useRef)();return(0,d.useEffect)((()=>(u.current=!0,c()({path:(0,w.addQueryArgs)("/content-aggregator-block/v1/meta/",{post_type:n})}).then((e=>{if(u.current){const t=[{label:(0,h.__)("None"),value:""}],o=e.map((e=>({label:(0,k.decodeEntities)(e),value:e})));p(t.concat(o))}})).catch((()=>{u.current&&p([])})),()=>{u.current=!1})),[n]),(0,e.createElement)("div",{className:"happyprime-block-cab_meta-order-settings"},(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_meta-order-key-select",label:(0,h.__)("Meta Key"),onChange:e=>l({orderByMetaKey:e}),options:i,value:s}),(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_meta-order-order-select",label:(0,h.__)("Order"),onChange:e=>l({orderByMetaOrder:e}),options:[{label:(0,h.__)("ASC"),value:"ASC"},{label:(0,h.__)("DESC"),value:"DESC"}],value:r}))}function S(t){const{onChange:o,selectedTerms:a,taxonomy:l}=t,[n,s]=(0,d.useState)([]),r=(0,d.useRef)(),i=l.split(",")[1];return(0,d.useEffect)((()=>(r.current=!0,c()({path:(0,w.addQueryArgs)(`/wp/v2/${i}`,{per_page:-1})}).then((e=>{if(r.current){const t=e.map((e=>({label:(0,k.decodeEntities)(e.name),value:e.id})));s(t)}})).catch((()=>{r.current&&s([])})),()=>{r.current=!1})),[l]),(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_taxonomy-term-select",help:(0,h.__)("Ctrl/Cmd + click to select/deselect multiple terms"),label:(0,h.__)("Term(s)"),multiple:!0,onChange:o,options:n,value:a})}const T={per_page:-1},N={slug:"",terms:[],operator:"IN"},B={from:[{type:"block",blocks:["core/latest-posts"],transform:e=>(0,t.createBlock)("happyprime/content-aggregator",{itemCount:e.postsToShow,order:e.order,orderBy:e.orderBy,displayPostDate:e.displayPostDate,postLayout:e.postLayout,columns:e.columns,displayPostContent:e.displayPostContent,postContent:e.displayPostContentRadio,excerptLength:e.excerptLength,displayImage:e.displayFeaturedImage,imageSize:e.featuredImageSizeSlug,stickyPosts:!1,addLinkToFeaturedImage:e.addLinkToFeaturedImage})},{type:"block",blocks:["happyprime/latest-custom-posts"],transform:e=>{const o=e.taxonomies&&0{const{getPostTypes:t,getTaxonomies:o}=e("core"),a=t(T),l=o(T),n=e("core/block-editor").getSettings().imageSizes,s=(0,g.applyFilters)("contentAggregatorBlock.ExcludePostTypes",["attachment"]),r=[],c=[],i=[];return a&&a.forEach((e=>{e.viewable&&e.rest_base&&!s.includes(e.slug)&&(r.push({label:e.labels.singular_name,value:e.slug}),$===e.slug&&e.taxonomies.length&&l&&(c.push({label:(0,h.__)("None"),value:""}),l.forEach((t=>{e.taxonomies.includes(t.slug)&&c.push({label:t.name,value:t.slug+","+t.rest_base})}))))})),n&&n.forEach((e=>{i.push({value:e.slug,label:e.name})})),{postTypeOptions:r,taxonomyOptions:c,imageSizeOptions:i}}),[$]),[Q,q]=(0,d.useState)(""),U=(0,d.useRef)();(0,d.useEffect)((()=>{U.current=!0;const e={post_type:$,per_page:M,order:I,orderby:O};if("meta_value"===O&&R&&(e.meta_key=R,e.order=D),cabStickyPostSupport.includes($)&&j&&(e.sticky_posts=!0),n&&(e.authors=n),G&&(e.taxonomies=G,F&&(e.tax_relation=F)),c()({path:(0,w.addQueryArgs)("/content-aggregator-block/v1/posts/",e)}).then((e=>{U.current&&q(e)})).catch((()=>{U.current&&q([])})),U.currrent&&(o.customTaxonomy||o.termID)){const e=[{slug:o.customTaxonomy,terms:[`${o.termID}`]}];a({taxonomies:e,customTaxonomy:void 0,termID:void 0})}return()=>{U.current=!1}}),[n,M,I,O,R,D,$,j,G,F]);const J=Array.isArray(Q)&&Q.length,X=(0,i.useBlockProps)({className:s()({"wp-block-latest-posts":!0,"happyprime-block-cab_error":!J,"cab-has-post-thumbnail":C,"cab-has-post-date":z,"cab-has-post-author":k,"cab-has-post-content":B&&"full_post"===V,"cab-has-post-excerpt":B&&"excerpt"===V,"is-grid":"grid"===H,[`columns-${r}`]:"grid"===H})}),Y=(e,t,o)=>{let a;if(G?.length&&(a=Object.values({...G,[e]:{...G[e],[t]:o}})),"slug"===t&&(G?.length?o!==G[e].slug&&(a=Object.values({...a,[e]:{...a[e],terms:[],operator:void 0}})):a=[{slug:o,terms:[],operator:"IN"}]),"terms"===t){const t=G[e].operator?G[e].operator:"IN";a=Object.values({...a,[e]:{...a[e],operator:t}})}return a},ee=(t,o)=>{const l=1{G.splice(o,1),a({taxonomies:[...G]}),1===G.length&&a({taxRelation:void 0})}}),(0,e.createElement)("div",{className:"happyprime-block-cab_taxonomy-setting"},(0,e.createElement)(m.SelectControl,{label:(0,h.__)("Taxonomy"),value:t.slug?t.slug:"",options:K,onChange:e=>{""===e?1===G.length?a({taxonomies:[]}):(G.splice(o,1),a({taxonomies:[...G]})):a({taxonomies:Y(o,"slug",e)})}}),""!==t.slug&&(0,e.createElement)(S,{onChange:e=>a({taxonomies:Y(o,"terms",e)}),selectedTerms:t.terms,taxonomy:t.slug}),""!==t.slug&&(0,e.createElement)(m.RadioControl,{label:(0,h.__)("Show posts:"),selected:t.operator,options:l,onChange:e=>a({taxonomies:Y(o,"operator",e)})})))},te=(0,e.createElement)(i.InspectorControls,null,(0,e.createElement)(m.PanelBody,{title:(0,h.__)("Settings"),className:"happyprime-block-cab"},"grid"===H&&(0,e.createElement)(m.RangeControl,{label:(0,h.__)("Columns"),value:r,onChange:e=>a({columns:e}),min:2,max:J?Math.min(6,Q.length):6,required:!0}),(0,e.createElement)(m.SelectControl,{help:(0,h.__)('WordPress contains different types of content which are divided into collections called "Post Types". Default types include blog posts and pages, though plugins may remove these or add others.'),label:(0,h.__)("Post Type"),value:x,options:W,onChange:e=>{a({customPostType:e,taxonomies:[]})}}),(0,e.createElement)(m.__experimentalNumberControl,{label:(0,h.__)("Number of Items"),value:M,onChange:e=>{a({itemCount:Number(e)})},min:1}),(0,e.createElement)(m.SelectControl,{key:"query-controls-order-select",label:(0,h.__)("Order By"),value:`${O}/${I}`,options:[{label:(0,h.__)("Published - Newest to Oldest"),value:"date/desc"},{label:(0,h.__)("Published - Oldest to Newest"),value:"date/asc"},{label:(0,h.__)("Modified - Newest to Oldest"),value:"modified/desc"},{label:(0,h.__)("Modified - Oldest to Newest"),value:"modified/asc"},{label:(0,h.__)("A → Z"),value:"title/asc"},{label:(0,h.__)("Z → A"),value:"title/desc"},{label:(0,h.__)("Random"),value:"rand/desc"},{label:(0,h.__)("Meta Value"),value:"meta_value/desc"},{label:(0,h.__)("Menu Order"),value:"menu_order/asc"}],onChange:e=>{const[t,o]=e.split("/"),l={};o!==I&&(l.order=o),t!==O&&(l.orderBy=t),(l.order||l.orderBy)&&a(l)}}),"meta_value"===O&&(0,e.createElement)(P,{blockProps:t}),cabStickyPostSupport.includes(x.split(",")[0])&&"date"===O&&(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Show sticky posts at the start of the set"),checked:j,onChange:e=>{a({stickyPosts:e})}})),(0,e.createElement)(m.PanelBody,{title:(0,h.__)("Filters"),className:"happyprime-block-cab"},(0,e.createElement)("div",{className:"happyprime-block-cab_taxonomy-settings"},(0,e.createElement)("p",null,(0,h.__)("Taxonomies")),0ee(e,t))):ee(N,0),0{a({taxonomies:G.concat(N)}),F||a({taxRelation:"AND"})},text:(0,h.__)("Add more taxonomy settings")}),1a({taxRelation:e})}))),(0,e.createElement)(E,{onChange:e=>a({authors:e}),value:n})),(0,e.createElement)(m.PanelBody,{title:(0,h.__)("Post Template"),className:"happyprime-block-cab"},(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Display post date"),checked:z,onChange:e=>a({displayPostDate:e})}),(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Display post author"),checked:k,onChange:e=>a({displayPostAuthor:e})}),(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Display post content"),checked:B,onChange:e=>a({displayPostContent:e})}),B&&(0,e.createElement)(m.RadioControl,{label:(0,h.__)("Show"),selected:V,options:[{label:(0,h.__)("Excerpt"),value:"excerpt"},{label:(0,h.__)("Full Post"),value:"full_post"}],onChange:e=>a({postContent:e})}),B&&"excerpt"===V&&(0,e.createElement)(m.RangeControl,{label:(0,h.__)("Max number of words in excerpt"),value:A,onChange:e=>a({excerptLength:e}),min:10,max:100}),(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Display featured image"),checked:C,onChange:e=>a({displayImage:e})}),C&&(0,e.createElement)(d.Fragment,null,(0,e.createElement)(m.SelectControl,{label:(0,h.__)("Image size"),onChange:e=>a({imageSize:e}),options:Z,value:L}),(0,e.createElement)(m.ToggleControl,{label:(0,h.__)("Add link to featured image"),checked:l,onChange:e=>a({addLinkToFeaturedImage:e})}))));if(!J)return(0,e.createElement)("div",{...X},te,(0,e.createElement)(m.Placeholder,{icon:b,label:(0,h.__)("Content Aggregator")},Array.isArray(Q)?(0,h.__)("No current items."):(0,e.createElement)(m.Spinner,null)));const oe=Q.length>M?Q.slice(0,M):Q;return(0,e.createElement)(d.Fragment,null,te,(0,e.createElement)(i.BlockControls,null,(0,e.createElement)(m.ToolbarGroup,{controls:[{icon:v,title:(0,h.__)("List View"),onClick:()=>a({postLayout:"list"}),isActive:"list"===H},{icon:f,title:(0,h.__)("Grid View"),onClick:()=>a({postLayout:"grid"}),isActive:"grid"===H}]})),(0,e.createElement)("ul",{...X},oe.map((t=>(t=>{const a=t.title.trim(),n=document.createElement("div");n.innerHTML=t.excerpt;const s=n.textContent||n.innerText||"",r=(0,e.createElement)("li",null,(0,e.createElement)(m.Disabled,null,(0,e.createElement)("a",{href:t.link,rel:"noreferrer noopener"},a?(0,e.createElement)(d.RawHTML,null,a):(0,h.__)("(Untitled)"))),k&&t.author&&(0,e.createElement)("div",{className:"wp-block-latest-posts__post-author"},(0,e.createElement)("span",{className:"byline"},"By ",(0,e.createElement)("span",{className:"author"},t.author))),z&&t.date_gmt&&(0,e.createElement)("time",{dateTime:(0,u.format)("c",t.date_gmt),className:"wp-block-latest-posts__post-date"},(0,u.dateI18n)((0,u.__experimentalGetSettings)().formats.date,t.date_gmt)),C&&t.image[L]&&(0,e.createElement)("figure",{className:"wp-block-latest-posts__post-thumbnail"},l?(0,e.createElement)(m.Disabled,null,(0,e.createElement)("a",{href:t.link,rel:"noreferrer noopener"},(0,e.createElement)("img",{src:t.image[L],alt:""}))):(0,e.createElement)("img",{src:t.image[L],alt:""})),B&&"excerpt"===V&&(0,e.createElement)("div",{className:"wp-block-latest-posts__post-excerpt"},(0,e.createElement)(d.RawHTML,{key:"html"},A{var e={184:(e,t)=>{var o;!function(){"use strict";var a={}.hasOwnProperty;function l(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var a in t)o.o(t,a)&&!o.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e=window.React,t=window.wp.blocks,a=window.wp.primitives,l=JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"happyprime/content-aggregator","title":"Content Aggregator","category":"widgets","description":"A list of posts for a custom post type and/or taxonomy.","keywords":["recent","latest","custom","post type"],"attributes":{"customPostType":{"type":"string","default":"post"},"taxonomies":{"type":"array","items":{"type":"object"}},"taxRelation":{"type":"string","default":""},"itemCount":{"type":"integer","default":3},"order":{"type":"string","default":"desc"},"orderBy":{"type":"string","default":"date"},"displayPostDate":{"type":"boolean","default":false},"postLayout":{"type":"string","default":"list"},"columns":{"type":"integer","default":2},"displayPostContent":{"type":"boolean","default":false},"postContent":{"type":"string","default":"excerpt"},"excerptLength":{"type":"number","default":55},"displayImage":{"type":"boolean","default":false},"imageSize":{"type":"string","default":"thumbnail"},"stickyPosts":{"type":"boolean","default":true},"addLinkToFeaturedImage":{"type":"boolean","default":false},"authors":{"type":"string"},"displayPostAuthor":{"type":"boolean","default":false},"orderByMetaKey":{"type":"string","default":""},"orderByMetaOrder":{"type":"string","default":""},"customTaxonomy":{"type":"array","default":[]},"termID":{"type":"number","default":0}},"supports":{"align":true,"html":false},"editorScript":"file:../../build/content-aggregator.js","editorStyle":"file:../../build/content-aggregator.css"}');var n=o(184),s=o.n(n);const r=window.wp.apiFetch;var c=o.n(r);const i=window.wp.blockEditor,m=window.wp.components,p=window.wp.data,u=window.wp.date,d=window.wp.element,g=window.wp.hooks,y=window.wp.i18n,h=(0,d.createElement)(a.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,d.createElement)(a.Path,{d:"M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21ZM15.5303 8.46967C15.8232 8.76256 15.8232 9.23744 15.5303 9.53033L13.0607 12L15.5303 14.4697C15.8232 14.7626 15.8232 15.2374 15.5303 15.5303C15.2374 15.8232 14.7626 15.8232 14.4697 15.5303L12 13.0607L9.53033 15.5303C9.23744 15.8232 8.76256 15.8232 8.46967 15.5303C8.17678 15.2374 8.17678 14.7626 8.46967 14.4697L10.9393 12L8.46967 9.53033C8.17678 9.23744 8.17678 8.76256 8.46967 8.46967C8.76256 8.17678 9.23744 8.17678 9.53033 8.46967L12 10.9393L14.4697 8.46967C14.7626 8.17678 15.2374 8.17678 15.5303 8.46967Z"})),_=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},(0,d.createElement)(a.Path,{d:"M10 1c-5 0-9 4-9 9s4 9 9 9 9-4 9-9-4-9-9-9zm0 16c-3.9 0-7-3.1-7-7s3.1-7 7-7 7 3.1 7 7-3.1 7-7 7zm1-11H9v3H6v2h3v3h2v-3h3V9h-3V6zM10 1c-5 0-9 4-9 9s4 9 9 9 9-4 9-9-4-9-9-9zm0 16c-3.9 0-7-3.1-7-7s3.1-7 7-7 7 3.1 7 7-3.1 7-7 7zm1-11H9v3H6v2h3v3h2v-3h3V9h-3V6z"})),b=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,d.createElement)(a.Path,{d:"m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z"})),v=(0,d.createElement)(a.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,d.createElement)(a.Path,{d:"M4 4v1.5h16V4H4zm8 8.5h8V11h-8v1.5zM4 20h16v-1.5H4V20zm4-8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2z"})),f=(0,d.createElement)(a.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,d.createElement)(a.Path,{d:"m3 5c0-1.10457.89543-2 2-2h13.5c1.1046 0 2 .89543 2 2v13.5c0 1.1046-.8954 2-2 2h-13.5c-1.10457 0-2-.8954-2-2zm2-.5h6v6.5h-6.5v-6c0-.27614.22386-.5.5-.5zm-.5 8v6c0 .2761.22386.5.5.5h6v-6.5zm8 0v6.5h6c.2761 0 .5-.2239.5-.5v-6zm0-8v6.5h6.5v-6c0-.27614-.2239-.5-.5-.5z",fillRule:"evenodd",clipRule:"evenodd"})),w=window.wp.url,x=window.wp.coreData,C={who:"authors",per_page:-1,_fields:"id,name",context:"view"};function E({value:t,onChange:o}){const a=(0,p.useSelect)((e=>{const{getUsers:t}=e(x.store);return t(C)}),[]);if(!a)return null;const l=(e=>{const t=e?.reduce(((e,t)=>{const{mapById:o,mapByName:a,names:l}=e;return o[t.id]=t,a[t.name]=t,l.push(t.name),e}),{mapById:{},mapByName:{},names:[]});return{entities:e,...t}})(a),n=(t?t.toString().split(","):[]).reduce(((e,t)=>{const o=l.mapById[t];return o&&e.push({id:t,value:o.name}),e}),[]);return(0,e.createElement)(m.FormTokenField,{label:(0,y.__)("Authors"),value:n,suggestions:l.names,onChange:e=>{const t=Array.from(e.reduce(((e,t)=>{const o=((e,t)=>{const o=t?.id||e[t]?.id;if(o)return o})(l.mapByName,t);return o&&e.add(o),e}),new Set));o(t.join(","))}})}const k=window.wp.htmlEntities;function P(t){const{blockProps:o}=t,{attributes:a,setAttributes:l}=o,{customPostType:n,orderByMetaKey:s,orderByMetaOrder:r}=a,[i,p]=(0,d.useState)([]),u=(0,d.useRef)();return(0,d.useEffect)((()=>(u.current=!0,c()({path:(0,w.addQueryArgs)("/content-aggregator-block/v1/meta/",{post_type:n})}).then((e=>{if(u.current){const t=[{label:(0,y.__)("None"),value:""}],o=e.map((e=>({label:(0,k.decodeEntities)(e),value:e})));p(t.concat(o))}})).catch((()=>{u.current&&p([])})),()=>{u.current=!1})),[n]),(0,e.createElement)("div",{className:"happyprime-block-cab_meta-order-settings"},(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_meta-order-key-select",label:(0,y.__)("Meta Key"),onChange:e=>l({orderByMetaKey:e}),options:i,value:s}),(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_meta-order-order-select",label:(0,y.__)("Order"),onChange:e=>l({orderByMetaOrder:e}),options:[{label:(0,y.__)("ASC"),value:"ASC"},{label:(0,y.__)("DESC"),value:"DESC"}],value:r}))}function T(t){const{onChange:o,selectedTerms:a,taxonomy:l}=t,[n,s]=(0,d.useState)([]),r=(0,d.useRef)(),i=l.split(",")[1];return(0,d.useEffect)((()=>(r.current=!0,c()({path:(0,w.addQueryArgs)(`/wp/v2/${i}`,{per_page:-1})}).then((e=>{if(r.current){const t=e.map((e=>({label:(0,k.decodeEntities)(e.name),value:e.id})));s(t)}})).catch((()=>{r.current&&s([])})),()=>{r.current=!1})),[l]),(0,e.createElement)(m.SelectControl,{className:"happyprime-block-cab_taxonomy-term-select",help:(0,y.__)("Ctrl/Cmd + click to select/deselect multiple terms"),label:(0,y.__)("Term(s)"),multiple:!0,onChange:o,options:n,value:a})}const S={per_page:-1},N={slug:"",terms:[],operator:"IN"},B={from:[{type:"block",blocks:["core/latest-posts"],transform:e=>(0,t.createBlock)("happyprime/content-aggregator",{itemCount:e.postsToShow,order:e.order,orderBy:e.orderBy,displayPostDate:e.displayPostDate,postLayout:e.postLayout,columns:e.columns,displayPostContent:e.displayPostContent,postContent:e.displayPostContentRadio,excerptLength:e.excerptLength,displayImage:e.displayFeaturedImage,imageSize:e.featuredImageSizeSlug,stickyPosts:!1,addLinkToFeaturedImage:e.addLinkToFeaturedImage})},{type:"block",blocks:["happyprime/latest-custom-posts"],transform:e=>{const o=e.taxonomies&&0{const{getPostTypes:t,getTaxonomies:o}=e("core"),a=t(S),l=o(S),n=e("core/block-editor").getSettings().imageSizes,s=(0,g.applyFilters)("contentAggregatorBlock.ExcludePostTypes",["attachment"]),r=[],c=[],i=[];return a&&a.forEach((e=>{e.viewable&&e.rest_base&&!s.includes(e.slug)&&(r.push({label:e.labels.singular_name,value:e.slug}),W===e.slug&&e.taxonomies.length&&l&&(c.push({label:(0,y.__)("None"),value:""}),l.forEach((t=>{e.taxonomies.includes(t.slug)&&c.push({label:t.name,value:t.slug+","+t.rest_base})}))))})),n&&n.forEach((e=>{i.push({value:e.slug,label:e.name})})),{postTypeOptions:r,taxonomyOptions:c,imageSizeOptions:i}}),[W]),[Q,q]=(0,d.useState)(""),U=(0,d.useRef)();(0,d.useEffect)((()=>{U.current=!0;const e={post_type:W,per_page:M,order:I,orderby:O};return"meta_value"===O&&R&&(e.meta_key=R,e.order=D),cabStickyPostSupport.includes(W)&&j&&(e.sticky_posts=!0),n&&(e.authors=n),G&&(e.taxonomies=G,F&&(e.tax_relation=F)),c()({path:(0,w.addQueryArgs)("/content-aggregator-block/v1/posts/",e)}).then((e=>{U.current&&q(e)})).catch((()=>{U.current&&q([])})),o.customPostType&&o.customPostType!==o.customPostType.split(",")[0]&&a({customPostType:o.customPostType.split(",")[0]}),U.current&&(o.customTaxonomy||o.termID)&&(!G?.length&&Array.isArray(o.customTaxonomy)&&a({taxonomies:o.customTaxonomy,customTaxonomy:void 0}),Array.isArray(G)&&o.customTaxonomy&&a({customTaxonomy:void 0})),()=>{U.current=!1}}),[n,M,I,O,R,D,W,j,G,F]);const J=Array.isArray(Q)&&Q.length,X=(0,i.useBlockProps)({className:s()({"wp-block-latest-posts":!0,"happyprime-block-cab_error":!J,"cab-has-post-thumbnail":C,"cab-has-post-date":A,"cab-has-post-author":k,"cab-has-post-content":B&&"full_post"===V,"cab-has-post-excerpt":B&&"excerpt"===V,"is-grid":"grid"===H,[`columns-${r}`]:"grid"===H})}),Y=(e,t,o)=>{let a;if(G?.length&&(a=Object.values({...G,[e]:{...G[e],[t]:o}})),"slug"===t&&(G?.length?o!==G[e].slug&&(a=Object.values({...a,[e]:{...a[e],terms:[],operator:void 0}})):a=[{slug:o,terms:[],operator:"IN"}]),"terms"===t){const t=G[e].operator?G[e].operator:"IN";a=Object.values({...a,[e]:{...a[e],operator:t}})}return a},ee=(t,o)=>{const l=1{G.splice(o,1),a({taxonomies:[...G]}),1===G.length&&a({taxRelation:void 0})}}),(0,e.createElement)("div",{className:"happyprime-block-cab_taxonomy-setting"},(0,e.createElement)(m.SelectControl,{label:(0,y.__)("Taxonomy"),value:t.slug?t.slug:"",options:K,onChange:e=>{""===e?1===G.length?a({taxonomies:[]}):(G.splice(o,1),a({taxonomies:[...G]})):a({taxonomies:Y(o,"slug",e)})}}),""!==t.slug&&(0,e.createElement)(T,{onChange:e=>a({taxonomies:Y(o,"terms",e)}),selectedTerms:t.terms,taxonomy:t.slug}),""!==t.slug&&(0,e.createElement)(m.RadioControl,{label:(0,y.__)("Show posts:"),selected:t.operator,options:l,onChange:e=>a({taxonomies:Y(o,"operator",e)})})))},te=(0,e.createElement)(i.InspectorControls,null,(0,e.createElement)(m.PanelBody,{title:(0,y.__)("Settings"),className:"happyprime-block-cab"},"grid"===H&&(0,e.createElement)(m.RangeControl,{label:(0,y.__)("Columns"),value:r,onChange:e=>a({columns:e}),min:2,max:J?Math.min(6,Q.length):6,required:!0}),(0,e.createElement)(m.SelectControl,{help:(0,y.__)('WordPress contains different types of content which are divided into collections called "Post Types". Default types include blog posts and pages, though plugins may remove these or add others.'),label:(0,y.__)("Post Type"),value:x,options:$,onChange:e=>{a({customPostType:e,taxonomies:[]})}}),(0,e.createElement)(m.__experimentalNumberControl,{label:(0,y.__)("Number of Items"),value:M,onChange:e=>{a({itemCount:Number(e)})},min:1}),(0,e.createElement)(m.SelectControl,{key:"query-controls-order-select",label:(0,y.__)("Order By"),value:`${O}/${I}`,options:[{label:(0,y.__)("Published - Newest to Oldest"),value:"date/desc"},{label:(0,y.__)("Published - Oldest to Newest"),value:"date/asc"},{label:(0,y.__)("Modified - Newest to Oldest"),value:"modified/desc"},{label:(0,y.__)("Modified - Oldest to Newest"),value:"modified/asc"},{label:(0,y.__)("A → Z"),value:"title/asc"},{label:(0,y.__)("Z → A"),value:"title/desc"},{label:(0,y.__)("Random"),value:"rand/desc"},{label:(0,y.__)("Meta Value"),value:"meta_value/desc"},{label:(0,y.__)("Menu Order"),value:"menu_order/asc"}],onChange:e=>{const[t,o]=e.split("/"),l={};o!==I&&(l.order=o),t!==O&&(l.orderBy=t),(l.order||l.orderBy)&&a(l)}}),"meta_value"===O&&(0,e.createElement)(P,{blockProps:t}),cabStickyPostSupport.includes(x.split(",")[0])&&"date"===O&&(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Show sticky posts at the start of the set"),checked:j,onChange:e=>{a({stickyPosts:e})}})),(0,e.createElement)(m.PanelBody,{title:(0,y.__)("Filters"),className:"happyprime-block-cab"},(0,e.createElement)("div",{className:"happyprime-block-cab_taxonomy-settings"},(0,e.createElement)("p",null,(0,y.__)("Taxonomies")),0ee(e,t))):ee(N,0),0{a({taxonomies:G.concat(N)}),F||a({taxRelation:"AND"})},text:(0,y.__)("Add more taxonomy settings")}),1a({taxRelation:e})}))),(0,e.createElement)(E,{onChange:e=>a({authors:e}),value:n})),(0,e.createElement)(m.PanelBody,{title:(0,y.__)("Post Template"),className:"happyprime-block-cab"},(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Display post date"),checked:A,onChange:e=>a({displayPostDate:e})}),(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Display post author"),checked:k,onChange:e=>a({displayPostAuthor:e})}),(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Display post content"),checked:B,onChange:e=>a({displayPostContent:e})}),B&&(0,e.createElement)(m.RadioControl,{label:(0,y.__)("Show"),selected:V,options:[{label:(0,y.__)("Excerpt"),value:"excerpt"},{label:(0,y.__)("Full Post"),value:"full_post"}],onChange:e=>a({postContent:e})}),B&&"excerpt"===V&&(0,e.createElement)(m.RangeControl,{label:(0,y.__)("Max number of words in excerpt"),value:z,onChange:e=>a({excerptLength:e}),min:10,max:100}),(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Display featured image"),checked:C,onChange:e=>a({displayImage:e})}),C&&(0,e.createElement)(d.Fragment,null,(0,e.createElement)(m.SelectControl,{label:(0,y.__)("Image size"),onChange:e=>a({imageSize:e}),options:Z,value:L}),(0,e.createElement)(m.ToggleControl,{label:(0,y.__)("Add link to featured image"),checked:l,onChange:e=>a({addLinkToFeaturedImage:e})}))));if(!J)return(0,e.createElement)("div",{...X},te,(0,e.createElement)(m.Placeholder,{icon:b,label:(0,y.__)("Content Aggregator")},Array.isArray(Q)?(0,y.__)("No current items."):(0,e.createElement)(m.Spinner,null)));const oe=Q.length>M?Q.slice(0,M):Q;return(0,e.createElement)(d.Fragment,null,te,(0,e.createElement)(i.BlockControls,null,(0,e.createElement)(m.ToolbarGroup,{controls:[{icon:v,title:(0,y.__)("List View"),onClick:()=>a({postLayout:"list"}),isActive:"list"===H},{icon:f,title:(0,y.__)("Grid View"),onClick:()=>a({postLayout:"grid"}),isActive:"grid"===H}]})),(0,e.createElement)("ul",{...X},oe.map((t=>(t=>{const a=t.title.trim(),n=document.createElement("div");n.innerHTML=t.excerpt;const s=n.textContent||n.innerText||"",r=(0,e.createElement)("li",null,(0,e.createElement)(m.Disabled,null,(0,e.createElement)("a",{href:t.link,rel:"noreferrer noopener"},a?(0,e.createElement)(d.RawHTML,null,a):(0,y.__)("(Untitled)"))),k&&t.author&&(0,e.createElement)("div",{className:"wp-block-latest-posts__post-author"},(0,e.createElement)("span",{className:"byline"},"By ",(0,e.createElement)("span",{className:"author"},t.author))),A&&t.date_gmt&&(0,e.createElement)("time",{dateTime:(0,u.format)("c",t.date_gmt),className:"wp-block-latest-posts__post-date"},(0,u.dateI18n)((0,u.__experimentalGetSettings)().formats.date,t.date_gmt)),C&&t.image[L]&&(0,e.createElement)("figure",{className:"wp-block-latest-posts__post-thumbnail"},l?(0,e.createElement)(m.Disabled,null,(0,e.createElement)("a",{href:t.link,rel:"noreferrer noopener"},(0,e.createElement)("img",{src:t.image[L],alt:""}))):(0,e.createElement)("img",{src:t.image[L],alt:""})),B&&"excerpt"===V&&(0,e.createElement)("div",{className:"wp-block-latest-posts__post-excerpt"},(0,e.createElement)(d.RawHTML,{key:"html"},z $attributes['customTaxonomy'], 'terms' => array( $attributes['termID'] ), ), ); + } elseif ( empty( $attributes['taxonomies'] ) && ! empty( $attributes['customTaxonomy'] ) && is_array( $attributes['customTaxonomy'] ) ) { + // If this is a previous iteration of the block in which the `customTaxonomy` + // attribute was stored as an array, and the taxonomies attribute is not set, + // create a taxonomies attribute from the data. + $attributes['taxonomies'] = $attributes['customTaxonomy']; } - // Use the new `taxonomies` attribute if available. - $taxonomies = ( ! empty( $attributes['taxonomies'] ) ) - ? $attributes['taxonomies'] - : $attributes['customTaxonomy'] ?? array(); + $taxonomies = $attributes['taxonomies']; if ( ! empty( $taxonomies ) ) { $tax_query = array(); @@ -167,7 +170,7 @@ function build_query_args( $attributes ) { */ function render( $attributes ) { $defaults = array( - 'customPostType' => 'post,posts', + 'customPostType' => 'post', 'taxonomies' => array(), 'taxRelation' => '', 'itemCount' => 3, @@ -390,7 +393,7 @@ function register_posts_endpoint() { function posts_rest_response( $request ) { $attributes = array( 'authors' => $request->get_param( 'authors' ) ?? '', - 'customPostType' => $request->get_param( 'post_type' ) ?? 'post,posts', + 'customPostType' => $request->get_param( 'post_type' ) ?? 'post', 'taxonomies' => $request->get_param( 'taxonomies' ) ?? array(), 'taxRelation' => $request->get_param( 'tax_relation' ) ?? '', 'itemCount' => $request->get_param( 'per_page' ) ?? 3, diff --git a/includes/cli/class-command.php b/includes/cli/class-command.php new file mode 100644 index 0000000..9d5705f --- /dev/null +++ b/includes/cli/class-command.php @@ -0,0 +1,183 @@ +flatten_blocks( $block['innerBlocks'] ); + + $flattened_blocks = array_merge( $flattened_blocks, $inner_blocks ); + } + } + + return $flattened_blocks; + } + + /** + * Retrieve a list of posts containing content aggregator blocks. + * + * @return array A list of post IDs. + */ + private function get_posts(): array { + global $wpdb; + + $post_ids = $wpdb->get_results( + "SELECT ID FROM $wpdb->posts WHERE post_content LIKE '%content-aggregator%' AND post_status IN ( 'publish', 'draft', 'pending', 'future' )" + ); + + return $post_ids ? $post_ids : array(); + } + + /** + * Retrieve a list of posts containing content aggregator blocks and the + * attributes used for each. + * + * @subcommand audit-blocks + * + * @param array $args The command arguments. + */ + public function audit_blocks( $args ): void { + $format = isset( $args[0] ) ? $args[0] : 'csv'; + $post_ids = $this->get_posts(); + $results = array(); + $progress = Utils\make_progress_bar( 'Auditing content for content aggregator blocks', count( $post_ids ) ); + + foreach ( $post_ids as $post_id ) { + $post = get_post( $post_id->ID ); + $blocks = parse_blocks( $post->post_content ); + $blocks = $this->flatten_blocks( $blocks ); + + foreach ( $blocks as $block ) { + if ( 'happyprime/content-aggregator' !== $block['blockName'] ) { + continue; + } + + $attributes = $block['attrs']; + + $type = ''; + if ( isset( $attributes['customTaxonomy'] ) ) { + $type = is_array( $attributes['customTaxonomy'] ) ? 'array' : 'string'; + } + + $results[] = array( + 'post_id' => $post_id->ID, + 'slug' => $post->post_name, + 'title' => $post->post_title, + 'status' => $post->post_status, + 'block' => $block['blockName'], + 'customPostType' => isset( $attributes['customPostType'] ) ? $attributes['customPostType'] : '', + 'taxonomies' => isset( $attributes['taxonomies'] ) ? wp_json_encode( $attributes['taxonomies'] ) : '', + 'customTaxonomy' => isset( $attributes['customTaxonomy'] ) ? wp_json_encode( $attributes['customTaxonomy'] ) : '', + 'customType' => $type, + 'itemCount' => $attributes['itemCount'] ?? '', + 'termID' => isset( $attributes['termID'] ) ? $attributes['termID'] : '', + ); + } + + $progress->tick(); + } + + $progress->finish(); + + $headers = array(); + if ( ! empty( $results ) ) { + $headers = array_keys( $results[0] ); + } + + Utils\format_items( $format, $results, $headers ); + } + + /** + * Fix incorrect and deprecated attributes on old instances of the content + * aggregator block. + * + * @subcommand fix-block-attributes + */ + public function fix_block_attributes(): void { + $posts = $this->get_posts(); + $progress = Utils\make_progress_bar( 'Fixing content aggregator block attributes', count( $posts ) ); + + foreach ( $posts as $post ) { + $post = get_post( $post->ID ); + $blocks = parse_blocks( $post->post_content ); + $blocks = $this->flatten_blocks( $blocks ); + $content = $post->post_content; + + foreach ( $blocks as $block ) { + if ( 'happyprime/content-aggregator' !== $block['blockName'] ) { + continue; + } + + $original = serialize_block( $block ); + $attributes = $block['attrs']; + + // If this is a previous iteration of the block in which the `customTaxonomy` + // attribute was stored as a string, and the taxonomies attribute is not set, + // create a taxonomies attribute from the data. + if ( empty( $attributes['taxonomies'] ) && ! empty( $attributes['termID'] ) && ! empty( $attributes['customTaxonomy'] ) && ! is_array( $attributes['customTaxonomy'] ) ) { + $attributes['taxonomies'] = array( + array( + 'slug' => $attributes['customTaxonomy'], + 'terms' => array( $attributes['termID'] ), + ), + ); + unset( $attributes['termID'] ); + unset( $attributes['customTaxonomy'] ); + } elseif ( empty( $attributes['taxonomies'] ) && ! empty( $attributes['customTaxonomy'] ) && is_array( $attributes['customTaxonomy'] ) ) { + // If this is a previous iteration of the block in which the `customTaxonomy` + // attribute was stored as an array, and the taxonomies attribute is not set, + // create a taxonomies attribute from the data. + $attributes['taxonomies'] = $attributes['customTaxonomy']; + unset( $attributes['customTaxonomy'] ); + } elseif ( ! empty( $attributes['taxonomies'] ) && ! empty( $attributes['customTaxonomy'] ) && is_array( $attributes['customTaxonomy'] ) ) { + unset( $attributes['customTaxonomy'] ); + } + + // If the customPostType attribute is a comma separated string, retrieve the first value. + if ( ! empty( $attributes['customPostType'] ) && is_string( $attributes['customPostType'] ) ) { + $attributes['customPostType'] = explode( ',', $attributes['customPostType'] )[0]; + } + + $block['attrs'] = $attributes; + $fixed = serialize_block( $block ); + + $content = str_replace( $original, $fixed, $content ); + } + + if ( $content !== $post->post_content ) { + $post->post_content = $content; + wp_update_post( $post ); + } + + $progress->tick(); + } + + $progress->finish(); + } +} diff --git a/plugin.php b/plugin.php index 2e07f4d..2eba5cd 100644 --- a/plugin.php +++ b/plugin.php @@ -18,3 +18,9 @@ require_once __DIR__ . '/includes/api.php'; require_once __DIR__ . '/includes/block.php'; require_once __DIR__ . '/includes/cache.php'; + +if ( defined( 'WP_CLI' ) ) { + require_once __DIR__ . '/includes/cli/class-command.php'; + + \WP_CLI::add_command( 'cab', 'HappyPrime\ContentAggregator\CLI\Command' ); +}