{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n\n\nYou can use pagination and also view each \"member\" with the same slug.\n\nBut as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ?\n\nDon't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page\n\nHere is the solution with .htacess. Add this to your .htaccess :\n\n`RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]`\n\nand don't forget to fix you rule :\n`add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`.\n\nI have made another test just for you : \n\nThis solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url"}}},{"rowIdx":7657414,"cells":{"qid":{"kind":"number","value":393836,"string":"393,836"},"question":{"kind":"string","value":"

I have successfully changed the name of a specific page using this code in my functions.php file:

\n
add_filter('pre_get_document_title', 'change_my_property_title');\n\nfunction change_my_property_title($title) {\n     if ( is_page('property') ) {\n       return 'Property';\n     }\n     return $title;\n}\n
\n

My problem is I can't figure out how to change the name to an actual php variable that is on the property page. I am pulling property information from a json url and would like the address to be the title. If I try to point to the variable in my return statement nothing comes up.

\n

Here is the page I'm working on: http://geekoutaustin.com/live/property/?id=d86967ad43c2f5271b02f94247ef858d&wpf28382_5=8252427

\n"},"answers":{"kind":"list like","value":[{"answer_id":393749,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":-1,"selected":false,"text":"

You should keep the slug page in your URL.\nIt is way more easier and better to read.

\n

Here is something correct :

\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\n
\n"},{"answer_id":393788,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":0,"selected":false,"text":"

I'll add another answer because the rule is only a part of the problem.

\n

Here is what I have tested and is working :

\n
<?php\nclass BadRewritesRules {\n\n    public function __construct() {\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n        remove_filter('template_redirect', 'redirect_canonical');\n    }\n\n    public function custom_post_types_rewrite_rules() {\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\n    }\n\n}\n\nnew BadRewritesRules();\n
\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\nYou can use pagination and also view each "member" with the same slug.

\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\n

Here is the solution with .htacess. Add this to your .htaccess :

\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\n

and don't forget to fix you rule :\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\n"}],"string":"[\n {\n \"answer_id\": 393749,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

You should keep the slug page in your URL.\\nIt is way more easier and better to read.

\\n

Here is something correct :

\\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\\n
\\n\"\n },\n {\n \"answer_id\": 393788,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

I'll add another answer because the rule is only a part of the problem.

\\n

Here is what I have tested and is working :

\\n
<?php\\nclass BadRewritesRules {\\n\\n    public function __construct() {\\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\\n        remove_filter('template_redirect', 'redirect_canonical');\\n    }\\n\\n    public function custom_post_types_rewrite_rules() {\\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\\n    }\\n\\n}\\n\\nnew BadRewritesRules();\\n
\\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\\nYou can use pagination and also view each "member" with the same slug.

\\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\\n

Here is the solution with .htacess. Add this to your .htaccess :

\\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\\n

and don't forget to fix you rule :\\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/08/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/393836","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210568/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/393836\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210568/\"\n]"},"input":{"kind":"string","value":"I have successfully changed the name of a specific page using this code in my functions.php file:\n\n```\nadd_filter('pre_get_document_title', 'change_my_property_title');\n\nfunction change_my_property_title($title) {\n if ( is_page('property') ) {\n return 'Property';\n }\n return $title;\n}\n\n```\n\nMy problem is I can't figure out how to change the name to an actual php variable that is on the property page. I am pulling property information from a json url and would like the address to be the title. If I try to point to the variable in my return statement nothing comes up.\n\nHere is the page I'm working on: "},"output":{"kind":"string","value":"I'll add another answer because the rule is only a part of the problem.\n\nHere is what I have tested and is working :\n\n```\n\nYou can use pagination and also view each \"member\" with the same slug.\n\nBut as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ?\n\nDon't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page\n\nHere is the solution with .htacess. Add this to your .htaccess :\n\n`RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]`\n\nand don't forget to fix you rule :\n`add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`.\n\nI have made another test just for you : \n\nThis solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url"}}},{"rowIdx":7657415,"cells":{"qid":{"kind":"number","value":393858,"string":"393,858"},"question":{"kind":"string","value":"

This is my Shortcode: [mbv name=”product-info”]

\n

And i want to display this shortcode's content after WooCommerce Short Product Description

\n

How can i do it?

\n"},"answers":{"kind":"list like","value":[{"answer_id":393749,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":-1,"selected":false,"text":"

You should keep the slug page in your URL.\nIt is way more easier and better to read.

\n

Here is something correct :

\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\n
\n"},{"answer_id":393788,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":0,"selected":false,"text":"

I'll add another answer because the rule is only a part of the problem.

\n

Here is what I have tested and is working :

\n
<?php\nclass BadRewritesRules {\n\n    public function __construct() {\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n        remove_filter('template_redirect', 'redirect_canonical');\n    }\n\n    public function custom_post_types_rewrite_rules() {\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\n    }\n\n}\n\nnew BadRewritesRules();\n
\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\nYou can use pagination and also view each "member" with the same slug.

\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\n

Here is the solution with .htacess. Add this to your .htaccess :

\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\n

and don't forget to fix you rule :\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\n"}],"string":"[\n {\n \"answer_id\": 393749,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

You should keep the slug page in your URL.\\nIt is way more easier and better to read.

\\n

Here is something correct :

\\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\\n
\\n\"\n },\n {\n \"answer_id\": 393788,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

I'll add another answer because the rule is only a part of the problem.

\\n

Here is what I have tested and is working :

\\n
<?php\\nclass BadRewritesRules {\\n\\n    public function __construct() {\\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\\n        remove_filter('template_redirect', 'redirect_canonical');\\n    }\\n\\n    public function custom_post_types_rewrite_rules() {\\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\\n    }\\n\\n}\\n\\nnew BadRewritesRules();\\n
\\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\\nYou can use pagination and also view each "member" with the same slug.

\\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\\n

Here is the solution with .htacess. Add this to your .htaccess :

\\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\\n

and don't forget to fix you rule :\\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/08/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/393858","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210558/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/393858\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210558/\"\n]"},"input":{"kind":"string","value":"This is my Shortcode: `[mbv name=”product-info”]`\n\nAnd i want to display this shortcode's content after [WooCommerce Short Product Description](https://github.com/woocommerce/woocommerce/blob/b19500728b4b292562afb65eb3a0c0f50d5859de/templates/single-product/short-description.php#L24)\n\nHow can i do it?"},"output":{"kind":"string","value":"I'll add another answer because the rule is only a part of the problem.\n\nHere is what I have tested and is working :\n\n```\n\nYou can use pagination and also view each \"member\" with the same slug.\n\nBut as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ?\n\nDon't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page\n\nHere is the solution with .htacess. Add this to your .htaccess :\n\n`RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]`\n\nand don't forget to fix you rule :\n`add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`.\n\nI have made another test just for you : \n\nThis solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url"}}},{"rowIdx":7657416,"cells":{"qid":{"kind":"number","value":393877,"string":"393,877"},"question":{"kind":"string","value":"

Hope someone can help me with this.

\n

This is my code:

\n
function swh_woocommerce_store_credit_shortcode() {\n    $store_credits = swh_woocommerce_get_store_credits();\n    echo "<span style= 'display: inline;'>Remaining Credit:</span>";\n    return wc_price($store_credits);\n    \n}\nadd_shortcode( 'swh_store_credit_total_value', 'swh_woocommerce_store_credit_shortcode' );\n
\n

I'm trying to display echo and return in the same line.

\n

i. e. Remaning Credit: $80 and not

\n
Remaining Credit:\n\n$80\n
\n

Thanks!

\n"},"answers":{"kind":"list like","value":[{"answer_id":393749,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":-1,"selected":false,"text":"

You should keep the slug page in your URL.\nIt is way more easier and better to read.

\n

Here is something correct :

\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\n
\n"},{"answer_id":393788,"author":"Pierre R","author_id":134512,"author_profile":"https://wordpress.stackexchange.com/users/134512","pm_score":0,"selected":false,"text":"

I'll add another answer because the rule is only a part of the problem.

\n

Here is what I have tested and is working :

\n
<?php\nclass BadRewritesRules {\n\n    public function __construct() {\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n        remove_filter('template_redirect', 'redirect_canonical');\n    }\n\n    public function custom_post_types_rewrite_rules() {\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\n    }\n\n}\n\nnew BadRewritesRules();\n
\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\nYou can use pagination and also view each "member" with the same slug.

\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\n

Here is the solution with .htacess. Add this to your .htaccess :

\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\n

and don't forget to fix you rule :\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\n"}],"string":"[\n {\n \"answer_id\": 393749,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

You should keep the slug page in your URL.\\nIt is way more easier and better to read.

\\n

Here is something correct :

\\n
add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top' );\\n
\\n\"\n },\n {\n \"answer_id\": 393788,\n \"author\": \"Pierre R\",\n \"author_id\": 134512,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/134512\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

I'll add another answer because the rule is only a part of the problem.

\\n

Here is what I have tested and is working :

\\n
<?php\\nclass BadRewritesRules {\\n\\n    public function __construct() {\\n        add_action('init', [$this, 'custom_post_types_rewrite_rules']);\\n        remove_filter('template_redirect', 'redirect_canonical');\\n    }\\n\\n    public function custom_post_types_rewrite_rules() {\\n        add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');\\n    }\\n\\n}\\n\\nnew BadRewritesRules();\\n
\\n

In reality, I used another URL and you can see it working here : https://tests.pierre-roels.com/bad-rewrite-rules/2/\\nYou can use pagination and also view each "member" with the same slug.

\\n

But as I said, this is a poor solution in my opinion because we must remove the template_redirect action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an .htaccess redirect ?

\\n

Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page

\\n

Here is the solution with .htacess. Add this to your .htaccess :

\\n

RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]

\\n

and don't forget to fix you rule :\\nadd_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');.

\\n

I have made another test just for you : https://tests.pierre-roels.com/blog/2/

\\n

This solution allow you to not remove the template_redirect hook, it redirects the user the right end-url

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/08/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/393877","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210770/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/393877\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210770/\"\n]"},"input":{"kind":"string","value":"Hope someone can help me with this.\n\nThis is my code:\n\n```\nfunction swh_woocommerce_store_credit_shortcode() {\n $store_credits = swh_woocommerce_get_store_credits();\n echo \"Remaining Credit:\";\n return wc_price($store_credits);\n\n}\nadd_shortcode( 'swh_store_credit_total_value', 'swh_woocommerce_store_credit_shortcode' );\n\n```\n\nI'm trying to display echo and return in the same line.\n\ni. e. `Remaning Credit: $80` and not\n\n```\nRemaining Credit:\n\n$80\n\n```\n\nThanks!"},"output":{"kind":"string","value":"I'll add another answer because the rule is only a part of the problem.\n\nHere is what I have tested and is working :\n\n```\n\nYou can use pagination and also view each \"member\" with the same slug.\n\nBut as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ?\n\nDon't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page\n\nHere is the solution with .htacess. Add this to your .htaccess :\n\n`RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]`\n\nand don't forget to fix you rule :\n`add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`.\n\nI have made another test just for you : \n\nThis solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url"}}},{"rowIdx":7657417,"cells":{"qid":{"kind":"number","value":394020,"string":"394,020"},"question":{"kind":"string","value":"

I recently noticed a new feature in the Gutenberg editor (I'm guessing introduced in Wordpress 5.8) that seemingly allows any user to post as any other user:

\n

\"enter

\n

I confirmed that using this new option, a user belonging to the Author role was able to successfully to post as a user belonging to the Admin role. Why on Earth was this feature introduced with seemingly no permissions checks, and can it be disabled?

\n"},"answers":{"kind":"list like","value":[{"answer_id":394027,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":3,"selected":true,"text":"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\n

If we take a look at the authorship plugin we see that it can be removed:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n    }\n\n    return $response;\n}\n
\n

So something like this might remove it for all users when editing posts:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n    }\n\n    return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n
\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\n"},{"answer_id":394029,"author":"Hashim Aziz","author_id":167562,"author_profile":"https://wordpress.stackexchange.com/users/167562","pm_score":1,"selected":false,"text":"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\n
\n

This dropdown is a side effect of the edit_others_posts capability

\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\n"}],"string":"[\n {\n \"answer_id\": 394027,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\\n

If we take a look at the authorship plugin we see that it can be removed:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\\n    }\\n\\n    return $response;\\n}\\n
\\n

So something like this might remove it for all users when editing posts:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n    }\\n\\n    return $response;\\n}\\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\\n
\\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\\n\"\n },\n {\n \"answer_id\": 394029,\n \"author\": \"Hashim Aziz\",\n \"author_id\": 167562,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/167562\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\\n
\\n

This dropdown is a side effect of the edit_others_posts capability

\\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/08/31"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/394020","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/167562/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/394020\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/167562/\"\n]"},"input":{"kind":"string","value":"I recently noticed a new feature in the Gutenberg editor (I'm guessing introduced in Wordpress 5.8) that seemingly allows any user to post as any other user:\n\n[![enter image description here](https://i.stack.imgur.com/nIo3m.png)](https://i.stack.imgur.com/nIo3m.png)\n\nI confirmed that using this new option, a user belonging to the Author role was able to successfully to post as a user belonging to the Admin role. Why on Earth was this feature introduced with seemingly no permissions checks, and can it be disabled?"},"output":{"kind":"string","value":"This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!\n\nIn the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).\n\nIf we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed:\n\n```\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n\n```\n\nSo something like this might remove it for all users when editing posts:\n\n```php\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n\n```\n\nYou may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.\n\n***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***"}}},{"rowIdx":7657418,"cells":{"qid":{"kind":"number","value":394032,"string":"394,032"},"question":{"kind":"string","value":"

I wonder if this is possible on wordpress. In my application I will have a contact form, in this contact form, when filling in the fields, there must be a field that will generate an ID. This ID the customer will be able to write down and save. I will also receive this ID along with the details this person has filled in.\nIt is possible? Or is there already a plugin for this type of situation?

\n"},"answers":{"kind":"list like","value":[{"answer_id":394027,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":3,"selected":true,"text":"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\n

If we take a look at the authorship plugin we see that it can be removed:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n    }\n\n    return $response;\n}\n
\n

So something like this might remove it for all users when editing posts:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n    }\n\n    return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n
\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\n"},{"answer_id":394029,"author":"Hashim Aziz","author_id":167562,"author_profile":"https://wordpress.stackexchange.com/users/167562","pm_score":1,"selected":false,"text":"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\n
\n

This dropdown is a side effect of the edit_others_posts capability

\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\n"}],"string":"[\n {\n \"answer_id\": 394027,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\\n

If we take a look at the authorship plugin we see that it can be removed:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\\n    }\\n\\n    return $response;\\n}\\n
\\n

So something like this might remove it for all users when editing posts:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n    }\\n\\n    return $response;\\n}\\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\\n
\\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\\n\"\n },\n {\n \"answer_id\": 394029,\n \"author\": \"Hashim Aziz\",\n \"author_id\": 167562,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/167562\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\\n
\\n

This dropdown is a side effect of the edit_others_posts capability

\\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/08/31"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/394032","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/203043/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/394032\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/203043/\"\n]"},"input":{"kind":"string","value":"I wonder if this is possible on wordpress. In my application I will have a contact form, in this contact form, when filling in the fields, there must be a field that will generate an ID. This ID the customer will be able to write down and save. I will also receive this ID along with the details this person has filled in.\nIt is possible? Or is there already a plugin for this type of situation?"},"output":{"kind":"string","value":"This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!\n\nIn the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).\n\nIf we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed:\n\n```\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n\n```\n\nSo something like this might remove it for all users when editing posts:\n\n```php\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n\n```\n\nYou may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.\n\n***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***"}}},{"rowIdx":7657419,"cells":{"qid":{"kind":"number","value":394086,"string":"394,086"},"question":{"kind":"string","value":"

I have created a form and the table in the database I want submissions to be sent to. From my research I've found that this code should send it to the database:

\n
<?php /* PHP code that processes form */\n    if(isset($_POST['submit'])){\n        \n        global $wpdb;\n        $tablename = Form_Submissions;\n      \n        $data=array(\n            'FirstName' => $_POST['fname'],\n            'LastName' => $POST['lname'],\n            'Consent' => $POST['consent']\n        );\n        \n        $format = array(\n            '%s',\n            '%s',\n            '%s'\n        );\n      \n        $wpdb -> insert($tablename, $data, $format);\n\n        echo '<script type="text/javascript"> document.getElementById("frm").style.display="none"; </script>';\n    }\n?>\n
\n

However, nothing is happening. I'm at complete loss on where to go from here. Am I missing something simple, or am I completely off target? Thank you for your help!

\n

Here is the code for the form and the code that activates the form just in case.

\n
<html>\n<style>\n\n/* Stylings for Heading Statement */\n    .h3{\n        text-align: center;\n        font-size: 24px;\n        padding: 10px;\n        color: white;\n    }\n/* Stylings for checkbox */\n    .box{\n        font-size: 22px;\n        padding: 20px;\n        color: white;\n    }\n/* Stylings for input labels (names and checkbox labels) */\n    .input-label{\n        text-align: center;\n        font-size: 22px;\n        padding: 10px;\n        color: white;\n    }\n/* Button used to open the contact form - fixed at the bottom of the page */\n    .open-button {\n        width: 170px; \n        height: 60px; \n        background-color: transparent; \n        outline: none; \n        position: relative; \n        left: -168px; \n        top: 20px;\n    }\n/* The popup form - hidden by default */\n    .form-popup {\n        display: none;\n        position: absolute;\n        top: 25%;\n        left: -530px;\n        border: none;\n        z-index: 9;\n        background-color: #1e1e1e;\n        width: 1000px;\n        padding: 20px;\n        border-radius: 20px;\n        text-align: center;\n    }\n/* Sets style and size of input fields  */\n    .form-popup input[type=text] {\n        width: 30%;\n        padding: 5px;\n        margin: 5px 0 22px 0;\n        border: none;\n        background: #FFFFFF;\n    }\n/* Sets color and style of the input boxes when selected */\n    .form-popup input:focus {\n        background-color: #FFFFFF;\n        outline: none;\n    }\n/* Stylings of the submit button */\n    .btn {\n        background-color: #DB2600;\n        border-radius: 9999px;\n        font-size: 24px;\n        width: 120px;\n        height: 45px;\n        transition: 0.3s;\n        color: white;\n    }\n/* Changes the color of the sugmit button when curser hovers over it */\n    .btn:hover {\n        opacity: 1;\n        background-color: #000000;\n    }\n/* Hides the default checkbox */\n    .box input {\n        position: absolute;\n        opacity: 0;\n        cursor: pointer;\n        height: 0;\n        width: 0;\n    }\n/* creates custom checkbox */\n    .checkmark {\n        position: absolute;\n        height: 20px;\n        width: 20px;\n        background-color: white;\n        border-radius: 2px;\n    }\n/* Sets the color of checkbox when checked */\n    .box input:checked ~ .checkmark {\n        background-color: #DB2600;\n    }\n/* creates checkmark inside checkbox */\n    .checkmark:after {\n        content: "";\n        position: absolute;\n        display: none;\n    }\n/* Displays checkmark when checkbox is clicked */\n    .box input:checked ~ .checkmark:after {\n        display: block;\n    }\n/* Positions and styles checkmark */\n    .box .checkmark:after {\n        left: 7px;\n        top: 3px;\n        width: 6px;\n        height: 12px;\n        border: solid white;\n        border-width: 0 3px 3px 0;\n        -webkit-transform: rotate(45deg);\n        -ms-transform: rotate(45deg);\n        transform: rotate(45deg);\n    }\n/* Column formatting for checkbos and statement. This is what is aligning the two items. */\n    .column1 {\n        float: left;\n        width: 26%;\n    }\n    .column2 {\n        float: left;\n        width: 74%;\n        margin-top:-5px;\n    }\n/* Clears floats after the columns */\n    .row:after {\n        content: "";\n        display: table;\n        clear: both;\n    }\n\n</style>\n<body>\n\n<!-- Code for the form -->\n\n    <div class="form-popup" id="Form"> \n        <form method="post">\n        \n        <!-- acknolwdgement statment -->\n              <h3 class="h3">form statement</h3> \n\n        <!-- label and input for First Name -->\n              <label for="fname" class="input-label">First name:</label>\n              <input type="text" name="fname" required/>\n\n        <!-- label and input for Last Name -->\n              <label for="lname" class="input-label">&nbsp &nbsp Last name:</label>\n              <input type="text" name="lname" required/> <br> <br>\n\n        <!-- checkbox and label, placed to columns to achieve desired formating -->\n              <div class="row">\n                  <div class="column1" style="text-align: right;">\n                      <label  class="box" style="border-color: red;">  \n                      <input type="checkbox" name="consent" value="agree" class="box" required/>\n                      <span class="checkmark"></span>\n                      </label></div>\n                  <div class="column2" style="text-align: left;">\n                      <label class="input-label"> I have read and understand the above statement.\n                      </label>\n                  </div>\n              </div>\n              <br><br>  \n\n        <!-- Submit Button -->\n              <input type="submit" name="submit" value="Submit" class="btn">\n\n        </form>\n    </div>\n\n<script>\n    function openForm() { /* Opens Consent Form */\n        document.getElementById("Form").style.display = "block";\n    }\n</script>\n\n</body>\n\n\n<?php /* PHP code that processes form */\n    if(isset($_POST['submit'])){\n        \n        global $wpdb;\n        $tablename = Form_Submissions;\n      \n        $data=array(\n            'FirstName' => $_POST['fname'],\n            'LastName' => $POST['lname'],\n            'Consent' => $POST['consent']\n        );\n        \n        $format = array(\n            '%s',\n            '%s',\n            '%s'\n        );\n      \n        $wpdb -> insert($tablename, $data, $format);\n\n        echo '<script type="text/javascript"> document.getElementById("frm").style.display="none"; </script>';\n    }\n?>\n</html>\n
\n

The Switch Case that activates it:

\n
<?php /* code for pop-up button conditions */\n$host = 'https://' .$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; /* gets the current page's URL */\nswitch ( $host ){\n  case 'https://example1.com': \n  case 'https://example2.com': \n  case 'https://example3.com':\n    require 'pop-up-button.php'; /*calls the PHP file containing the code for the form*/\n    echo '<button id="close" class="open-button" onclick="openForm()"></button>'; \n    break; \n  default : /* the default case leaves the function and allows all pages with URL's not match the cases to run as normal pages */\n    break; \n}; ?>\n
\n"},"answers":{"kind":"list like","value":[{"answer_id":394027,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":3,"selected":true,"text":"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\n

If we take a look at the authorship plugin we see that it can be removed:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n    }\n\n    return $response;\n}\n
\n

So something like this might remove it for all users when editing posts:

\n
/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post          $post     Post object.\n * @param WP_REST_Request  $request  Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n    $links = $response->get_links();\n\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\n    }\n\n    return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n
\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\n"},{"answer_id":394029,"author":"Hashim Aziz","author_id":167562,"author_profile":"https://wordpress.stackexchange.com/users/167562","pm_score":1,"selected":false,"text":"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\n
\n

This dropdown is a side effect of the edit_others_posts capability

\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\n"}],"string":"[\n {\n \"answer_id\": 394027,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!

\\n

In the block editor, the presence of the author field depends on wether the user has the action wp:action-assign-author, but there is no direct capability that determines this. It is added because it's implied via the edit_others_posts capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).

\\n

If we take a look at the authorship plugin we see that it can be removed:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n        $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\\n    }\\n\\n    return $response;\\n}\\n
\\n

So something like this might remove it for all users when editing posts:

\\n
/**\\n * Filters the post data for a REST API response.\\n *\\n * This removes the `wp:action-assign-author` rel from the response so the default post author\\n * control doesn't get shown on the block editor post editing screen.\\n *\\n * @param WP_REST_Response $response The response object.\\n * @param WP_Post          $post     Post object.\\n * @param WP_REST_Request  $request  Request object.\\n * @return WP_REST_Response The response object.\\n */\\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\\n    $links = $response->get_links();\\n\\n    if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\\n        $response->remove_link( 'https://api.w.org/action-assign-author' );\\n    }\\n\\n    return $response;\\n}\\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\\n
\\n

You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.

\\n

This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI

\\n\"\n },\n {\n \"answer_id\": 394029,\n \"author\": \"Hashim Aziz\",\n \"author_id\": 167562,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/167562\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

After a lot of testing (easier since I remembered that any cap added to a role with add_cap has to explicitly be removed with remove_cap rather than just removing the add_cap call, and that even wp-cli can't help for this purpose), I finally managed to determine that...

\\n
\\n

This dropdown is a side effect of the edit_others_posts capability

\\n

I had originally enabled this cap for my Author role because another of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, even when the moderate_comments capability is also enabled. Enabling edit_others_posts at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.

\\n

In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that should be unrelated.

\\n

I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the moderate_comments cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/01"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/394086","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210914/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/394086\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210914/\"\n]"},"input":{"kind":"string","value":"I have created a form and the table in the database I want submissions to be sent to. From my research I've found that this code should send it to the database:\n\n```\n $_POST['fname'],\n 'LastName' => $POST['lname'],\n 'Consent' => $POST['consent']\n );\n\n $format = array(\n '%s',\n '%s',\n '%s'\n );\n\n $wpdb -> insert($tablename, $data, $format);\n\n echo '';\n }\n?>\n\n```\n\nHowever, nothing is happening. I'm at complete loss on where to go from here. Am I missing something simple, or am I completely off target? Thank you for your help!\n\nHere is the code for the form and the code that activates the form just in case.\n\n```\n\n\n\n\n\n\n
\n
\n\n \n

form statement

\n\n \n \n \n\n \n \n

\n\n \n
\n
\n
\n
\n \n
\n
\n

\n\n \n \n\n
\n
\n\n\n\n\n\n $_POST['fname'],\n 'LastName' => $POST['lname'],\n 'Consent' => $POST['consent']\n );\n\n $format = array(\n '%s',\n '%s',\n '%s'\n );\n\n $wpdb -> insert($tablename, $data, $format);\n\n echo '';\n }\n?>\n\n\n```\n\nThe Switch Case that activates it:\n\n```\n'; \n break; \n default : /* the default case leaves the function and allows all pages with URL's not match the cases to run as normal pages */\n break; \n}; ?>\n\n```"},"output":{"kind":"string","value":"This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!\n\nIn the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).\n\nIf we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed:\n\n```\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n\n```\n\nSo something like this might remove it for all users when editing posts:\n\n```php\n/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response->get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response->remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n\n```\n\nYou may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.\n\n***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***"}}},{"rowIdx":7657420,"cells":{"qid":{"kind":"number","value":395152,"string":"395,152"},"question":{"kind":"string","value":"

I use wordpress for my Social Media site. WordPress Pings allow other blog posts to appear in comments when they link to us.

\n

I want to limit it to only blog posts created on my own site. Basically I only want SELF-PINGS/Trackbacks.

\n

If Other site tries to send ping reject it then and their, but if my own site https://milyin.com's post tries to send a ping readily accept it and show it in comment section.

\n

I tried, wp-admin -> discussion -> (unselect) Allow links from other blog posts.

\n

But that disables internal Pings too.\nSecondly My authors are able to turn on/off the pingbacks for each post. So, many of the posts still recieve external pings.

\n

Here's a screenshot of the same: https://snipboard.io/8lVIrE.jpg

\n

I tried to do some code.

\n

I found a tutorial from How Disable Self Pingbacks in WordPress

\n

And I tried to modify it to fit my needs

\n
function SelfPing( &$links ) {\n    $Home = get_option( 'home' );\n    foreach ( $links as $l => $link ){\n        if ( strpos( $link, $Home )  === false){\n            unset($links[$l]);\n        }\n    }\n}\nadd_action( 'pre_ping', 'SelfPing' );\n\n
\n

However this didn't solve the purpose.

\n

I still recieve pings from all sorts of sites, on my posts, as majority of my authors manually turn on Pings.

\n

So How can I have only self pings, and remove external pings, even when my authors manually turn on pings for all posts.

\n"},"answers":{"kind":"list like","value":[{"answer_id":395178,"author":"vlood","author_id":733,"author_profile":"https://wordpress.stackexchange.com/users/733","pm_score":1,"selected":false,"text":"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\n
<Files xmlrpc.php>\n    Order deny,allow\n    Deny from all\n    Allow from 127.0.0.1\n</Files>\n
\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\n

Edit:

\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n    if ( 'pingback.ping' !== $type_of_call ) {\n        return;\n    }\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n        wp_die();\n    }\n\n}\n
\n"},{"answer_id":395254,"author":"Sally CJ","author_id":137402,"author_profile":"https://wordpress.stackexchange.com/users/137402","pm_score":3,"selected":true,"text":"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\n
    \n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n        // Exit with a proper error.\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n    }\n}\n
    \n
  2. \n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n    if ( false === strpos( $tb_url, home_url() ) ) {\n        // Exit with a proper error.\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n    }\n}\n
    \n
  4. \n
\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\n"}],"string":"[\n {\n \"answer_id\": 395178,\n \"author\": \"vlood\",\n \"author_id\": 733,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/733\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\\n
<Files xmlrpc.php>\\n    Order deny,allow\\n    Deny from all\\n    Allow from 127.0.0.1\\n</Files>\\n
\\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\\n

Edit:

\\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\\n    if ( 'pingback.ping' !== $type_of_call ) {\\n        return;\\n    }\\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\\n        wp_die();\\n    }\\n\\n}\\n
\\n\"\n },\n {\n \"answer_id\": 395254,\n \"author\": \"Sally CJ\",\n \"author_id\": 137402,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/137402\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\\n
    \\n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \\n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\\n        // Exit with a proper error.\\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\\n    }\\n}\\n
    \\n
  2. \\n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \\n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\\n    if ( false === strpos( $tb_url, home_url() ) ) {\\n        // Exit with a proper error.\\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\\n    }\\n}\\n
    \\n
  4. \\n
\\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395152","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/166927/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395152\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/166927/\"\n]"},"input":{"kind":"string","value":"I use wordpress for my Social Media site. WordPress Pings allow other blog posts to appear in comments when they link to us.\n\nI want to limit it to only blog posts created on my own site. Basically I only want SELF-PINGS/Trackbacks.\n\nIf Other site tries to send ping reject it then and their, but if my own site https://milyin.com's post tries to send a ping readily accept it and show it in comment section.\n\nI tried, **wp-admin** -> **discussion** -> (unselect) **Allow links from other blog posts.**\n\nBut that disables internal Pings too.\nSecondly My authors are able to turn on/off the pingbacks for each post. So, many of the posts still recieve external pings.\n\nHere's a screenshot of the same: ****\n\nI tried to do some code.\n\nI found a tutorial from **[How Disable Self Pingbacks in WordPress](https://www.wpbeginner.com/wp-tutorials/how-disable-self-pingbacks-in-wordpress/)**\n\nAnd I tried to modify it to fit my needs\n\n```\nfunction SelfPing( &$links ) {\n $Home = get_option( 'home' );\n foreach ( $links as $l => $link ){\n if ( strpos( $link, $Home ) === false){\n unset($links[$l]);\n }\n }\n}\nadd_action( 'pre_ping', 'SelfPing' );\n\n```\n\nHowever this didn't solve the purpose.\n\nI still recieve pings from all sorts of sites, on my posts, as majority of my authors manually turn on Pings.\n\nSo How can I have only self pings, and remove external pings, even when my authors manually turn on pings for all posts."},"output":{"kind":"string","value":"If you want to receive only linkbacks from your own WordPress site, then try both of these:\n\nBut if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a \"Pingback\" in the post's comments section.\n\n1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method:\n\n```php\nadd_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n\n```\n2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC):\n\n```php\nadd_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n\n```\n\nAnd BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase \"H\" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, \"*variable name is case-sensitive*\" :) )."}}},{"rowIdx":7657421,"cells":{"qid":{"kind":"number","value":395169,"string":"395,169"},"question":{"kind":"string","value":"

I have a huge problem! I am in the middle of migrating a drupal based online database to wordpress. In the old database every object (post) had downloadable qr code. Because the database is used for scientific purposes and users where allowed to use the downloaded qr code in their own publications for reference purposes.\nSince the system is five years old, some books have been printed using those qr codes, with the objects url embedded in the short code. It used the normal structure in drupal\nsite-url/node/XXXX (where XXXX is the number of the content node)\nOn the wordpress version the permalink structure is (and should be) for example like this:\nsite-url/audio/name-of-the-post\nSo for example https://soundandscience.de/node/1040 becomes https://soundandscience.de/audio/lautarchiv-recording-la-566-1-siebs-theodor-a-laute/

\n

What I can do, because I use ACF a lot, is create a field where the node number of the old post can be stored (in this example case: 1040)

\n

The post transference between drupal and wordpress will be handled manually (poor students)...

\n

But is there a way to make it possible, for the old shortcodes in printed books to be redirected to the new correct post?

\n

Best\nMartin

\n"},"answers":{"kind":"list like","value":[{"answer_id":395178,"author":"vlood","author_id":733,"author_profile":"https://wordpress.stackexchange.com/users/733","pm_score":1,"selected":false,"text":"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\n
<Files xmlrpc.php>\n    Order deny,allow\n    Deny from all\n    Allow from 127.0.0.1\n</Files>\n
\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\n

Edit:

\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n    if ( 'pingback.ping' !== $type_of_call ) {\n        return;\n    }\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n        wp_die();\n    }\n\n}\n
\n"},{"answer_id":395254,"author":"Sally CJ","author_id":137402,"author_profile":"https://wordpress.stackexchange.com/users/137402","pm_score":3,"selected":true,"text":"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\n
    \n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n        // Exit with a proper error.\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n    }\n}\n
    \n
  2. \n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n    if ( false === strpos( $tb_url, home_url() ) ) {\n        // Exit with a proper error.\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n    }\n}\n
    \n
  4. \n
\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\n"}],"string":"[\n {\n \"answer_id\": 395178,\n \"author\": \"vlood\",\n \"author_id\": 733,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/733\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\\n
<Files xmlrpc.php>\\n    Order deny,allow\\n    Deny from all\\n    Allow from 127.0.0.1\\n</Files>\\n
\\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\\n

Edit:

\\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\\n    if ( 'pingback.ping' !== $type_of_call ) {\\n        return;\\n    }\\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\\n        wp_die();\\n    }\\n\\n}\\n
\\n\"\n },\n {\n \"answer_id\": 395254,\n \"author\": \"Sally CJ\",\n \"author_id\": 137402,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/137402\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\\n
    \\n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \\n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\\n        // Exit with a proper error.\\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\\n    }\\n}\\n
    \\n
  2. \\n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \\n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\\n    if ( false === strpos( $tb_url, home_url() ) ) {\\n        // Exit with a proper error.\\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\\n    }\\n}\\n
    \\n
  4. \\n
\\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395169","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212032/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395169\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212032/\"\n]"},"input":{"kind":"string","value":"I have a huge problem! I am in the middle of migrating a drupal based online database to wordpress. In the old database every object (post) had downloadable qr code. Because the database is used for scientific purposes and users where allowed to use the downloaded qr code in their own publications for reference purposes.\nSince the system is five years old, some books have been printed using those qr codes, with the objects url embedded in the short code. It used the normal structure in drupal\nsite-url/node/XXXX (where XXXX is the number of the content node)\nOn the wordpress version the permalink structure is (and should be) for example like this:\nsite-url/audio/name-of-the-post\nSo for example becomes \n\nWhat I can do, because I use ACF a lot, is create a field where the node number of the old post can be stored (in this example case: 1040)\n\nThe post transference between drupal and wordpress will be handled manually (poor students)...\n\nBut is there a way to make it possible, for the old shortcodes in printed books to be redirected to the new correct post?\n\nBest\nMartin"},"output":{"kind":"string","value":"If you want to receive only linkbacks from your own WordPress site, then try both of these:\n\nBut if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a \"Pingback\" in the post's comments section.\n\n1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method:\n\n```php\nadd_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n\n```\n2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC):\n\n```php\nadd_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n\n```\n\nAnd BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase \"H\" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, \"*variable name is case-sensitive*\" :) )."}}},{"rowIdx":7657422,"cells":{"qid":{"kind":"number","value":395184,"string":"395,184"},"question":{"kind":"string","value":"

In my current case, the system try to find a page and show 404 if it does not find.\nI would like with the same url... like https://example.com/{{slug}}/

\n
    \n
  1. Check if a page with this slug exists :\n
      \n
    1. \n
        \n
      • Yes - show the page
      • \n
      \n
    2. \n
    3. \n
        \n
      • No - switch to the category page (with same slug)
      • \n
      \n
    4. \n
    5. \n
        \n
      • No category page -> show page 404
      • \n
      \n
    6. \n
    \n
  2. \n
\n

What is the best recommandanted way to do this in WP?

\n"},"answers":{"kind":"list like","value":[{"answer_id":395178,"author":"vlood","author_id":733,"author_profile":"https://wordpress.stackexchange.com/users/733","pm_score":1,"selected":false,"text":"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\n
<Files xmlrpc.php>\n    Order deny,allow\n    Deny from all\n    Allow from 127.0.0.1\n</Files>\n
\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\n

Edit:

\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n    if ( 'pingback.ping' !== $type_of_call ) {\n        return;\n    }\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n        wp_die();\n    }\n\n}\n
\n"},{"answer_id":395254,"author":"Sally CJ","author_id":137402,"author_profile":"https://wordpress.stackexchange.com/users/137402","pm_score":3,"selected":true,"text":"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\n
    \n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n        // Exit with a proper error.\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n    }\n}\n
    \n
  2. \n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n    if ( false === strpos( $tb_url, home_url() ) ) {\n        // Exit with a proper error.\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n    }\n}\n
    \n
  4. \n
\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\n"}],"string":"[\n {\n \"answer_id\": 395178,\n \"author\": \"vlood\",\n \"author_id\": 733,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/733\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to xmlrpc.php file only for requests from your own server by adding this to your .htaccess file

\\n
<Files xmlrpc.php>\\n    Order deny,allow\\n    Deny from all\\n    Allow from 127.0.0.1\\n</Files>\\n
\\n

This would work only if your webserver is Apache and it's configured to read local .htaccess files of overriding it's main configuration. Nginx, Litespeed and others don't use .htaccess files whatsoever, so no point in trying this with them.

\\n

Edit:

\\n

If you are using xmlrpc.php for other stuff too, you could use the xmlrpc_call hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):

\\n
add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\\n    if ( 'pingback.ping' !== $type_of_call ) {\\n        return;\\n    }\\n    if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\\n        wp_die();\\n    }\\n\\n}\\n
\\n\"\n },\n {\n \"answer_id\": 395254,\n \"author\": \"Sally CJ\",\n \"author_id\": 137402,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/137402\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

If you want to receive only linkbacks from your own WordPress site, then try both of these:

\\n

But if you want to allow all that were sent as trackbacks (where the comment type is trackback), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section.

\\n
    \\n
  1. This uses the xmlrpc_call action to disable pingbacks sent via the XML-RPC method:

    \\n
    add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\\n    if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\\n        // Exit with a proper error.\\n        $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\\n    }\\n}\\n
    \\n
  2. \\n
  3. This uses the pre_trackback_post action to disable trackbacks sent via the standard HTTP POST method (i.e. not using XML-RPC):

    \\n
    add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\\n    if ( false === strpos( $tb_url, home_url() ) ) {\\n        // Exit with a proper error.\\n        trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\\n    }\\n}\\n
    \\n
  4. \\n
\\n

And BTW, in the code in the question, $home is undefined and it should be $Home ( note the uppercase "H" and see this which says, "variable name is case-sensitive" :) ).

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395184","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/128094/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395184\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/128094/\"\n]"},"input":{"kind":"string","value":"In my current case, the system try to find a page and show 404 if it does not find.\nI would like with the same url... like [https://example.com/{{slug}}/](https://example.com/%7B%7Bslug%7D%7D/)\n\n1. Check if a page with this slug exists :\n\t1. * Yes - show the page\n\t2. * No - switch to the category page (with same slug)\n\t3. * No category page -> show page 404\n\nWhat is the best recommandanted way to do this in WP?"},"output":{"kind":"string","value":"If you want to receive only linkbacks from your own WordPress site, then try both of these:\n\nBut if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a \"Pingback\" in the post's comments section.\n\n1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method:\n\n```php\nadd_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n\n```\n2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC):\n\n```php\nadd_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n\n```\n\nAnd BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase \"H\" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, \"*variable name is case-sensitive*\" :) )."}}},{"rowIdx":7657423,"cells":{"qid":{"kind":"number","value":395222,"string":"395,222"},"question":{"kind":"string","value":"

I have little problem how implement deleting data from database using row actions. I have my custom list which includes data from database table.\n\"List\"

\n
 function column_name( $item ) {\n    $delete_nonce = wp_create_nonce();\n    $title = '<strong>' . $item['article_name'] . '</strong>';\n    $actions = [\n        'edit' => sprintf('<a href="?page=%s&id=%s">Edit</a>', 'edytuj-artykul', $item['article_id']),\n        'delete' => sprintf('<a href="?page=%s&action=%s&article_id=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint($item['article_id']), $delete_nonce)\n    ];\n    return $title. $this->row_actions( $actions );\n}\n\n\nfunction delete_article($item){\n    $article_id = $item['article_id'];\n    global $wpdb;\n     $table = 'wp_copywriter_articles';\n     $wpdb->query("DELETE FROM $table WHERE article_id = %d", $article_id);\n}\n
\n

In the same file I added

\n
add_action( 'admin_action_delete', 'delete_article' );\n
\n

When I click Delete action, nothing happend. I got link\nhttp://localhost/wordpress/wp-admin/admin.php?page=Artykuly&action=delete&article_id=26&_wpnonce=60a01b82d7

\n

but record is not deleted from database.

\n

For testing, I added a specific ID number of article to the delete_article method in the SQL query but still not works, so this method is not used by WP, when I click delete button.

\n

Someone can give me any tip what am I doing wrong, because I spent on this few few hours :)

\n

Best Regards,\nBartek

\n

@EDIT

\n

SOLVED

\n

My mistake was put delete_article() method to my custom list class. When I put my method to functions.php, everything works! :)

\n"},"answers":{"kind":"list like","value":[{"answer_id":395224,"author":"Mafnah","author_id":104860,"author_profile":"https://wordpress.stackexchange.com/users/104860","pm_score":2,"selected":false,"text":"

I think it's better to use the $wpdb->delete() function to remove a row.

\n
$article_id = $item['article_id'];\n$table = 'wp_copywriter_articles';\n$wpdb->delete( $table, array( 'id' => $article_id ) );\n
\n"},{"answer_id":395226,"author":"Howdy_McGee","author_id":7355,"author_profile":"https://wordpress.stackexchange.com/users/7355","pm_score":1,"selected":true,"text":"

The "admin_action_{$_REQUEST['action']}" hook does not pass any arguments. You would need to get the article_id from the $_REQUEST array. There are also a few other concerns such as:

\n
    \n
  1. You're not assigning an action when you call wp_create_nonce().
  2. \n
  3. As Mafnah suggets in their ansewr, you should use $wpdb::delete() as a shortcut for using $wpdb::prepare().
  4. \n
\n

Here's how you could rewrite this:

\n
function column_name( $item ) {\n    $delete_nonce = wp_create_nonce( 'delete_article' );\n    $actions = [\n        'delete' => add_query_arg( array(\n            'action'        => 'delete',\n            'article_id'    => $item['article_id'],\n            '_wpnonce'      => $delete_nonce,\n        ), admin_url( 'admin.php' ) ),\n    ];\n    /* Etc... */\n}\n\nfunction delete_article() {\n\n    global $wpdb;\n\n    // Ensure we can verify our nonce.\n    if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) {\n        wp_die( esc_html__( 'Could not verify request. Please try again.' ) );\n\n    // Ensure we have an article ID provided.\n    } else if( ! isset( $_REQUEST['article_id'] ) ) {\n        wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) );\n\n    // Ensure we're able to delete the actual article.\n    } else if( false === $wpdb->delete( 'wp_copywriter_articles', array( 'article_id' => $_REQUEST['article_id'] ) ) ) {\n        wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) );\n    }\n\n    // Redirect back to original page with 'success' $_GET\n    wp_safe_redirect( add_query_arg( array(\n        'page' => ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404',\n        'success' => 1,\n    ), admin_url( 'admin.php' ) ) );\n    exit();\n\n}\n
\n"}],"string":"[\n {\n \"answer_id\": 395224,\n \"author\": \"Mafnah\",\n \"author_id\": 104860,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/104860\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

I think it's better to use the $wpdb->delete() function to remove a row.

\\n
$article_id = $item['article_id'];\\n$table = 'wp_copywriter_articles';\\n$wpdb->delete( $table, array( 'id' => $article_id ) );\\n
\\n\"\n },\n {\n \"answer_id\": 395226,\n \"author\": \"Howdy_McGee\",\n \"author_id\": 7355,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/7355\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

The "admin_action_{$_REQUEST['action']}" hook does not pass any arguments. You would need to get the article_id from the $_REQUEST array. There are also a few other concerns such as:

\\n
    \\n
  1. You're not assigning an action when you call wp_create_nonce().
  2. \\n
  3. As Mafnah suggets in their ansewr, you should use $wpdb::delete() as a shortcut for using $wpdb::prepare().
  4. \\n
\\n

Here's how you could rewrite this:

\\n
function column_name( $item ) {\\n    $delete_nonce = wp_create_nonce( 'delete_article' );\\n    $actions = [\\n        'delete' => add_query_arg( array(\\n            'action'        => 'delete',\\n            'article_id'    => $item['article_id'],\\n            '_wpnonce'      => $delete_nonce,\\n        ), admin_url( 'admin.php' ) ),\\n    ];\\n    /* Etc... */\\n}\\n\\nfunction delete_article() {\\n\\n    global $wpdb;\\n\\n    // Ensure we can verify our nonce.\\n    if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) {\\n        wp_die( esc_html__( 'Could not verify request. Please try again.' ) );\\n\\n    // Ensure we have an article ID provided.\\n    } else if( ! isset( $_REQUEST['article_id'] ) ) {\\n        wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) );\\n\\n    // Ensure we're able to delete the actual article.\\n    } else if( false === $wpdb->delete( 'wp_copywriter_articles', array( 'article_id' => $_REQUEST['article_id'] ) ) ) {\\n        wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) );\\n    }\\n\\n    // Redirect back to original page with 'success' $_GET\\n    wp_safe_redirect( add_query_arg( array(\\n        'page' => ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404',\\n        'success' => 1,\\n    ), admin_url( 'admin.php' ) ) );\\n    exit();\\n\\n}\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/04"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395222","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212087/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395222\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212087/\"\n]"},"input":{"kind":"string","value":"I have little problem how implement deleting data from database using row actions. I have my custom list which includes data from database table.\n[![List](https://i.stack.imgur.com/v8EuB.png)](https://i.stack.imgur.com/v8EuB.png)\n\n```\n function column_name( $item ) {\n $delete_nonce = wp_create_nonce();\n $title = '' . $item['article_name'] . '';\n $actions = [\n 'edit' => sprintf('Edit', 'edytuj-artykul', $item['article_id']),\n 'delete' => sprintf('Delete', esc_attr( $_REQUEST['page'] ), 'delete', absint($item['article_id']), $delete_nonce)\n ];\n return $title. $this->row_actions( $actions );\n}\n\nfunction delete_article($item){\n $article_id = $item['article_id'];\n global $wpdb;\n $table = 'wp_copywriter_articles';\n $wpdb->query(\"DELETE FROM $table WHERE article_id = %d\", $article_id);\n}\n\n```\n\nIn the same file I added\n\n```\nadd_action( 'admin_action_delete', 'delete_article' );\n\n```\n\nWhen I click Delete action, nothing happend. I got link\nhttp://localhost/wordpress/wp-admin/admin.php?page=Artykuly&action=delete&article\\_id=26&\\_wpnonce=60a01b82d7\n\nbut record is not deleted from database.\n\nFor testing, I added a specific ID number of article to the delete\\_article method in the SQL query but still not works, so this method is not used by WP, when I click delete button.\n\nSomeone can give me any tip what am I doing wrong, because I spent on this few few hours :)\n\nBest Regards,\nBartek\n\n@EDIT\n\n**SOLVED**\n\nMy mistake was put delete\\_article() method to my custom list class. When I put my method to functions.php, everything works! :)"},"output":{"kind":"string","value":"The [\"admin\\_action\\_{$\\_REQUEST['action']}\" hook](https://developer.wordpress.org/reference/hooks/admin_action__requestaction/) does not pass any arguments. You would need to get the article\\_id from the $\\_REQUEST array. There are also a few other concerns such as:\n\n1. You're not assigning an action when you call `wp_create_nonce()`.\n2. As [Mafnah suggets in their ansewr](https://wordpress.stackexchange.com/a/395224/7355), you should use $wpdb::delete() as a shortcut for using `$wpdb::prepare()`.\n\nHere's how you could rewrite this:\n\n```\nfunction column_name( $item ) {\n $delete_nonce = wp_create_nonce( 'delete_article' );\n $actions = [\n 'delete' => add_query_arg( array(\n 'action' => 'delete',\n 'article_id' => $item['article_id'],\n '_wpnonce' => $delete_nonce,\n ), admin_url( 'admin.php' ) ),\n ];\n /* Etc... */\n}\n\nfunction delete_article() {\n\n global $wpdb;\n\n // Ensure we can verify our nonce.\n if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) {\n wp_die( esc_html__( 'Could not verify request. Please try again.' ) );\n\n // Ensure we have an article ID provided.\n } else if( ! isset( $_REQUEST['article_id'] ) ) {\n wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) );\n\n // Ensure we're able to delete the actual article.\n } else if( false === $wpdb->delete( 'wp_copywriter_articles', array( 'article_id' => $_REQUEST['article_id'] ) ) ) {\n wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) );\n }\n\n // Redirect back to original page with 'success' $_GET\n wp_safe_redirect( add_query_arg( array(\n 'page' => ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404',\n 'success' => 1,\n ), admin_url( 'admin.php' ) ) );\n exit();\n\n}\n\n```"}}},{"rowIdx":7657424,"cells":{"qid":{"kind":"number","value":395419,"string":"395,419"},"question":{"kind":"string","value":"

I have a load of data as JSON that I am trying to save into a fresh install of WordPress.

\n

I am using puppeteer to log into and create each page, and wp.blocks.createBlock to programmatically create the blocks.

\n
// Input the page title\n\n    const headingInput = document.querySelector("#post-title-0");\n    headingInput.innerHTML = json.data.heading;\n\n    var changeEvent = new Event("change", {\n        bubbles: true,\n        cancelable: true,\n    });\n    headingInput.dispatchEvent(changeEvent);\n\n\n    /**\n     * Next up, create each of the gutenberg blocks\n     */\n    json.data.blocks.forEach((block) => {\n        if (\n            block.className == "feature text-feature"\n        ) {\n            block.content.forEach((element) => {\n                if (element.hasOwnProperty("gutenbergBlock")) {\n                    var el = wp.element.createElement;\n                    insertedBlock = wp.blocks.createBlock(\n                        element.gutenbergBlock,\n                        element.attributes\n                    );\n                    wp.data.dispatch("core/editor").insertBlocks(insertedBlock);\n                }\n            });\n        }\n    });\n\n\n // Attempt to trigger the save:\n    document\n        .querySelectorAll(".editor-post-publish-button")\n        .forEach((button) => {\n            console.log("clicking button!");\n            var clickEvent = new MouseEvent("click", {\n                view: window,\n                bubbles: true,\n                cancelable: false,\n            });\n            button.dispatchEvent(clickEvent);\n        });\n
\n

Above, I attempt to click on the save button to save the post, however this part does not work.

\n

Is there a way to trigger the saving of page content? Something like: wp.blocks.save()? I have trawled the documentation but can't find anything so niche.

\n"},"answers":{"kind":"list like","value":[{"answer_id":395467,"author":"dgwyer","author_id":8961,"author_profile":"https://wordpress.stackexchange.com/users/8961","pm_score":0,"selected":false,"text":"

Have you tried using savePost?

\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\n"},{"answer_id":411100,"author":"Vakarelov","author_id":221869,"author_profile":"https://wordpress.stackexchange.com/users/221869","pm_score":1,"selected":false,"text":"

You can do this with:

\n
wp.data.dispatch( 'core/editor' ).savePost()\n
\n"}],"string":"[\n {\n \"answer_id\": 395467,\n \"author\": \"dgwyer\",\n \"author_id\": 8961,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/8961\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Have you tried using savePost?

\\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\\n\"\n },\n {\n \"answer_id\": 411100,\n \"author\": \"Vakarelov\",\n \"author_id\": 221869,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/221869\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

You can do this with:

\\n
wp.data.dispatch( 'core/editor' ).savePost()\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/09"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395419","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/27866/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395419\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/27866/\"\n]"},"input":{"kind":"string","value":"I have a load of data as JSON that I am trying to save into a fresh install of WordPress.\n\nI am using [puppeteer](https://github.com/puppeteer/puppeteer) to log into and create each page, and `wp.blocks.createBlock` to programmatically create the blocks.\n\n```\n// Input the page title\n\n const headingInput = document.querySelector(\"#post-title-0\");\n headingInput.innerHTML = json.data.heading;\n\n var changeEvent = new Event(\"change\", {\n bubbles: true,\n cancelable: true,\n });\n headingInput.dispatchEvent(changeEvent);\n\n /**\n * Next up, create each of the gutenberg blocks\n */\n json.data.blocks.forEach((block) => {\n if (\n block.className == \"feature text-feature\"\n ) {\n block.content.forEach((element) => {\n if (element.hasOwnProperty(\"gutenbergBlock\")) {\n var el = wp.element.createElement;\n insertedBlock = wp.blocks.createBlock(\n element.gutenbergBlock,\n element.attributes\n );\n wp.data.dispatch(\"core/editor\").insertBlocks(insertedBlock);\n }\n });\n }\n });\n\n // Attempt to trigger the save:\n document\n .querySelectorAll(\".editor-post-publish-button\")\n .forEach((button) => {\n console.log(\"clicking button!\");\n var clickEvent = new MouseEvent(\"click\", {\n view: window,\n bubbles: true,\n cancelable: false,\n });\n button.dispatchEvent(clickEvent);\n });\n\n```\n\nAbove, I attempt to click on the save button to save the post, however this part does not work.\n\nIs there a way to trigger the saving of page content? Something like: `wp.blocks.save()`? I have trawled the documentation but can't find anything so niche."},"output":{"kind":"string","value":"You can do this with:\n\n```\nwp.data.dispatch( 'core/editor' ).savePost()\n\n```"}}},{"rowIdx":7657425,"cells":{"qid":{"kind":"number","value":395431,"string":"395,431"},"question":{"kind":"string","value":"

I'm building a webshop with Wordpress and Woocommerce. On the productoverview (archive) of a productcategories I want to show a label if the product has the category 'New'. The following code works on the product-single, but it won't show on the productcategory-page if I add the action in content-product.php.

\n

I used the following code to show a label on the single product page and it works as it should.

\n
function resign_article_is_new(){\n\n    if ( is_product() && has_term( 'Nieuw', 'product_cat' ) ) {\n        echo '<p class="new-lable">New</p>';\n    }\n}\nadd_action( 'resign_new_article', 'resign_article_is_new');\n
\n

When I want to show the label on the productcategory overview I used this, but the label wouldn't appear.

\n
do_action('resign_new_article');\n
\n

Hope you can tell me what I'm doing wrong

\n"},"answers":{"kind":"list like","value":[{"answer_id":395467,"author":"dgwyer","author_id":8961,"author_profile":"https://wordpress.stackexchange.com/users/8961","pm_score":0,"selected":false,"text":"

Have you tried using savePost?

\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\n"},{"answer_id":411100,"author":"Vakarelov","author_id":221869,"author_profile":"https://wordpress.stackexchange.com/users/221869","pm_score":1,"selected":false,"text":"

You can do this with:

\n
wp.data.dispatch( 'core/editor' ).savePost()\n
\n"}],"string":"[\n {\n \"answer_id\": 395467,\n \"author\": \"dgwyer\",\n \"author_id\": 8961,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/8961\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Have you tried using savePost?

\\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\\n\"\n },\n {\n \"answer_id\": 411100,\n \"author\": \"Vakarelov\",\n \"author_id\": 221869,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/221869\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

You can do this with:

\\n
wp.data.dispatch( 'core/editor' ).savePost()\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/09"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395431","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/209621/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395431\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/209621/\"\n]"},"input":{"kind":"string","value":"I'm building a webshop with Wordpress and Woocommerce. On the productoverview (archive) of a productcategories I want to show a label if the product has the category 'New'. The following code works on the product-single, but it won't show on the productcategory-page if I add the action in content-product.php.\n\nI used the following code to show a label on the single product page and it works as it should.\n\n```\nfunction resign_article_is_new(){\n\n if ( is_product() && has_term( 'Nieuw', 'product_cat' ) ) {\n echo '

New

';\n }\n}\nadd_action( 'resign_new_article', 'resign_article_is_new');\n\n```\n\nWhen I want to show the label on the productcategory overview I used this, but the label wouldn't appear.\n\n```\ndo_action('resign_new_article');\n\n```\n\nHope you can tell me what I'm doing wrong"},"output":{"kind":"string","value":"You can do this with:\n\n```\nwp.data.dispatch( 'core/editor' ).savePost()\n\n```"}}},{"rowIdx":7657426,"cells":{"qid":{"kind":"number","value":395551,"string":"395,551"},"question":{"kind":"string","value":"

I have a function in a theme:

\n
$category = isset($_GET['category']) ? wp_unslash($_GET['category']) : '';\n
\n

The problem is that it outputs my categories like this:

\n

"test-category"

\n

I want, however, to show: "Test Category", just like it's saved in the backend, without the dashes and the smaller letters.

\n

Is there a way I can get rid of this slug and use the nicename instead? I tried a lot of things (like the get_term_by() function), but nothing works for me. I guess it's because of the fact that I am using the $category variable.

\n

Can someone help me?

\n"},"answers":{"kind":"list like","value":[{"answer_id":395467,"author":"dgwyer","author_id":8961,"author_profile":"https://wordpress.stackexchange.com/users/8961","pm_score":0,"selected":false,"text":"

Have you tried using savePost?

\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\n"},{"answer_id":411100,"author":"Vakarelov","author_id":221869,"author_profile":"https://wordpress.stackexchange.com/users/221869","pm_score":1,"selected":false,"text":"

You can do this with:

\n
wp.data.dispatch( 'core/editor' ).savePost()\n
\n"}],"string":"[\n {\n \"answer_id\": 395467,\n \"author\": \"dgwyer\",\n \"author_id\": 8961,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/8961\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Have you tried using savePost?

\\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\\n\"\n },\n {\n \"answer_id\": 411100,\n \"author\": \"Vakarelov\",\n \"author_id\": 221869,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/221869\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

You can do this with:

\\n
wp.data.dispatch( 'core/editor' ).savePost()\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/13"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395551","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/34977/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395551\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/34977/\"\n]"},"input":{"kind":"string","value":"I have a function in a theme:\n\n```\n$category = isset($_GET['category']) ? wp_unslash($_GET['category']) : '';\n\n```\n\nThe problem is that it outputs my categories like this:\n\n\"test-category\"\n\nI want, however, to show: **\"Test Category\"**, just like it's saved in the backend, without the dashes and the smaller letters.\n\nIs there a way I can get rid of this slug and use the nicename instead? I tried a lot of things (like the `get_term_by()` function), but nothing works for me. I guess it's because of the fact that I am using the $category variable.\n\nCan someone help me?"},"output":{"kind":"string","value":"You can do this with:\n\n```\nwp.data.dispatch( 'core/editor' ).savePost()\n\n```"}}},{"rowIdx":7657427,"cells":{"qid":{"kind":"number","value":395602,"string":"395,602"},"question":{"kind":"string","value":"

I'm beginning in PHP and I'm building a little shop with WooCommerce. I'm trying to display the top level parent category of a product in the body class.

\n

This code works well :

\n
function woo_custom_taxonomy_in_body_class( $classes ){\n$custom_terms = get_the_terms(0, 'product_cat');\nif ($custom_terms) {\n  foreach ($custom_terms as $custom_term) {\n\n    // Check if the parent category exists:\n    if( $custom_term->parent > 0 ) {\n        // Get the parent product category:\n        $parent = get_term( $custom_term->parent, 'product_cat' );\n        // Append the parent class:\n        if ( ! is_wp_error( $parent ) )\n            $classes[] = 'product_parent_cat_' . $parent->slug;\n    }\n\n    $classes[] = 'product_cat_' . $custom_term->slug;\n  }\n}\nreturn $classes;\n}\nadd_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );\n
\n

But it just gets the parent category. In a tree like this :

\n

"Toplevel cat > Parent cat > Category > My product"

\n

It will just get the parent one. However, I'd like to get the top level category.

\n

Do you have a solution ? Thank's a lot in advance!

\n"},"answers":{"kind":"list like","value":[{"answer_id":395467,"author":"dgwyer","author_id":8961,"author_profile":"https://wordpress.stackexchange.com/users/8961","pm_score":0,"selected":false,"text":"

Have you tried using savePost?

\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\n"},{"answer_id":411100,"author":"Vakarelov","author_id":221869,"author_profile":"https://wordpress.stackexchange.com/users/221869","pm_score":1,"selected":false,"text":"

You can do this with:

\n
wp.data.dispatch( 'core/editor' ).savePost()\n
\n"}],"string":"[\n {\n \"answer_id\": 395467,\n \"author\": \"dgwyer\",\n \"author_id\": 8961,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/8961\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Have you tried using savePost?

\\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\\n\"\n },\n {\n \"answer_id\": 411100,\n \"author\": \"Vakarelov\",\n \"author_id\": 221869,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/221869\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

You can do this with:

\\n
wp.data.dispatch( 'core/editor' ).savePost()\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/14"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395602","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212456/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395602\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212456/\"\n]"},"input":{"kind":"string","value":"I'm beginning in PHP and I'm building a little shop with WooCommerce. I'm trying to display the top level parent category of a product in the body class.\n\nThis code works well :\n\n```\nfunction woo_custom_taxonomy_in_body_class( $classes ){\n$custom_terms = get_the_terms(0, 'product_cat');\nif ($custom_terms) {\n foreach ($custom_terms as $custom_term) {\n\n // Check if the parent category exists:\n if( $custom_term->parent > 0 ) {\n // Get the parent product category:\n $parent = get_term( $custom_term->parent, 'product_cat' );\n // Append the parent class:\n if ( ! is_wp_error( $parent ) )\n $classes[] = 'product_parent_cat_' . $parent->slug;\n }\n\n $classes[] = 'product_cat_' . $custom_term->slug;\n }\n}\nreturn $classes;\n}\nadd_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );\n\n```\n\nBut it just gets the parent category. In a tree like this :\n\n\"Toplevel cat > Parent cat > Category > My product\"\n\nIt will just get the parent one. However, I'd like to get the top level category.\n\nDo you have a solution ? Thank's a lot in advance!"},"output":{"kind":"string","value":"You can do this with:\n\n```\nwp.data.dispatch( 'core/editor' ).savePost()\n\n```"}}},{"rowIdx":7657428,"cells":{"qid":{"kind":"number","value":395697,"string":"395,697"},"question":{"kind":"string","value":"

How can I totally disable the wordpress auto-resizing when uploading images, but only for images that have a certain string in its filename.

\n

Eg. disable auto-resizing on images in which its filenames contains the string "HD".

\n

image_xyz.jpeg >> auto-resizing function enabled\n
imageHD_xyz.jpeg >> auto-resizing function disabled\n
image_HD.jpeg >> auto-resizing function disabled

\n

Whats the reason behind this?

\n

I have to work whit images in the best quality on a specific plugin which will send them to another platform and will not be published in the mainsite, so therefore resized versions are not needed

\n

The following code works but based on file format.

\n
function wpdocs_disable_upload_sizes( $sizes, $image_meta ) {\n \n    // Get filetype data.\n    $filetype = wp_check_filetype( $image_meta['file'] );\n     \n    $exclude_file_types = array(\n        'image/png',\n    );\n \n    // Check if file type is on exclude list \n    if ( in_array( $filetype['type'], $exclude_file_types ) ) {\n        $sizes = array();\n    }\n \n    // Return sizes you want to create from image (None if image is gif.)\n    return $sizes;\n}   \nadd_filter( 'intermediate_image_sizes_advanced', 'wpdocs_disable_upload_sizes', 10, 2 );\n
\n"},"answers":{"kind":"list like","value":[{"answer_id":395467,"author":"dgwyer","author_id":8961,"author_profile":"https://wordpress.stackexchange.com/users/8961","pm_score":0,"selected":false,"text":"

Have you tried using savePost?

\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\n"},{"answer_id":411100,"author":"Vakarelov","author_id":221869,"author_profile":"https://wordpress.stackexchange.com/users/221869","pm_score":1,"selected":false,"text":"

You can do this with:

\n
wp.data.dispatch( 'core/editor' ).savePost()\n
\n"}],"string":"[\n {\n \"answer_id\": 395467,\n \"author\": \"dgwyer\",\n \"author_id\": 8961,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/8961\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Have you tried using savePost?

\\n

https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost

\\n\"\n },\n {\n \"answer_id\": 411100,\n \"author\": \"Vakarelov\",\n \"author_id\": 221869,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/221869\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

You can do this with:

\\n
wp.data.dispatch( 'core/editor' ).savePost()\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/16"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395697","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212522/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395697\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212522/\"\n]"},"input":{"kind":"string","value":"How can I totally disable the wordpress auto-resizing when uploading images, but only for images that have a certain string in its filename.\n\nEg. disable auto-resizing on images in which its filenames contains the string \"HD\".\n\nimage\\_xyz.jpeg >> auto-resizing function enabled\n\nimageHD\\_xyz.jpeg >> auto-resizing function disabled\n\nimage\\_HD.jpeg >> auto-resizing function disabled\n\nWhats the reason behind this?\n\nI have to work whit images in the best quality on a specific plugin which will send them to another platform and will not be published in the mainsite, so therefore resized versions are not needed\n\nThe following code works but based on file format.\n\n```\nfunction wpdocs_disable_upload_sizes( $sizes, $image_meta ) {\n\n // Get filetype data.\n $filetype = wp_check_filetype( $image_meta['file'] );\n\n $exclude_file_types = array(\n 'image/png',\n );\n\n // Check if file type is on exclude list \n if ( in_array( $filetype['type'], $exclude_file_types ) ) {\n $sizes = array();\n }\n\n // Return sizes you want to create from image (None if image is gif.)\n return $sizes;\n} \nadd_filter( 'intermediate_image_sizes_advanced', 'wpdocs_disable_upload_sizes', 10, 2 );\n\n```"},"output":{"kind":"string","value":"You can do this with:\n\n```\nwp.data.dispatch( 'core/editor' ).savePost()\n\n```"}}},{"rowIdx":7657429,"cells":{"qid":{"kind":"number","value":395709,"string":"395,709"},"question":{"kind":"string","value":"

Ok so basically I have this kind of situation.

\n

My first step is to filter out the posts using an array, let's say using this:

\n
$posts = get_posts(array(\n    'post_type'         => 'post',\n    'posts_per_page'    => 99999999,\n\n\n    'meta_query' => array(\n            array(\n                'key'     => 'status',\n                'value'   => 'active',\n            ),\n        ),\n\n    'orderby'               => 'rand'\n));\n
\n

So, let' say after the above code I'm left with a 20 random posts.

\n

On the second step I use the PHP filter (which is not possible in the above array):

\n
<?php \n$postid = get_the_ID(); \n$a1=get_post_meta( $postid, 'a1' , true );\n$a2=get_post_meta( $postid, 'a2' , true );\nif ($a1 < $a2): ?>\n\n    <?php the_title(); ?>  \n\n<?php endif; ?>\n
\n

The above filter's out the results, and after that I'm now left with, let's say, 5 post results.

\n

My question is, is there a php code that will choose just 1 random post from that list?

\n

I don't need 5, I just need 1.

\n

Hope I'm clear.

\n

Desperately need help here.

\n"},"answers":{"kind":"list like","value":[{"answer_id":395728,"author":"Ahmad Ahmad","author_id":212539,"author_profile":"https://wordpress.stackexchange.com/users/212539","pm_score":2,"selected":true,"text":"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\n

so you can try to test "manually disable plugins Wordpress"

\n"},{"answer_id":395743,"author":"Philtao","author_id":212524,"author_profile":"https://wordpress.stackexchange.com/users/212524","pm_score":0,"selected":false,"text":"

For no apparent reason, this morning I can login again!!!

\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions

\n"}],"string":"[\n {\n \"answer_id\": 395728,\n \"author\": \"Ahmad Ahmad\",\n \"author_id\": 212539,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212539\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\\n

so you can try to test "manually disable plugins Wordpress"

\\n\"\n },\n {\n \"answer_id\": 395743,\n \"author\": \"Philtao\",\n \"author_id\": 212524,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212524\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

For no apparent reason, this morning I can login again!!!

\\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\\nThank you for the contributions

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/16"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395709","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/202740/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395709\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/202740/\"\n]"},"input":{"kind":"string","value":"Ok so basically I have this kind of situation.\n\nMy first step is to filter out the posts using an array, let's say using this:\n\n```\n$posts = get_posts(array(\n 'post_type' => 'post',\n 'posts_per_page' => 99999999,\n\n 'meta_query' => array(\n array(\n 'key' => 'status',\n 'value' => 'active',\n ),\n ),\n\n 'orderby' => 'rand'\n));\n\n```\n\nSo, let' say after the above code I'm left with a 20 random posts.\n\nOn the second step I use the PHP filter (which is not possible in the above array):\n\n```\n\n\n \n\n\n\n```\n\nThe above filter's out the results, and after that I'm now left with, let's say, 5 post results.\n\nMy question is, is there a php code that will choose just 1 random post from that list?\n\nI don't need 5, I just need 1.\n\nHope I'm clear.\n\nDesperately need help here."},"output":{"kind":"string","value":"I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.\n\nso you can try to test \"[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)\""}}},{"rowIdx":7657430,"cells":{"qid":{"kind":"number","value":395714,"string":"395,714"},"question":{"kind":"string","value":"

I have a need to capture data in a WordPress plugin and append it into some sort of log.

\n

The data I want happens to be slow SQL queries from $wpdb->queries. I'm hoping to present useful "dirty dozen" SQL queries to my users to help them with optimizations. It's a companion plugin, or maybe a feature set, for this plugin. (I'm aware of the performance issues around this kind of system instrumentation. Capture sessions will be limited in duration. Etc.)

\n

In each relevant pageview I will capture some data and log it. Then later my plugin will retrieve, process, and delete the log. How can I do this data capture in a WordPress-friendly way?

\n

I'm thinking of using a transient to hold the log. I'm using expiring transients in my hope to avoid unprocessed logs from accumulating. My data flow would look something like this (pseudocode).

\n
$logdata = get_transient( $tName );\n$logdata .= $newdata;\nset_transient( $tName, $logdata, 86400 );\n
\n

But, on a busy site multiple php instances will race each other. One instance will do its get_transient(), then another instance will do its get before the first instance does its set. So one of the instances' data will be lost.

\n

If I were to do this with plain old MyISAM-compatible SQL I'd do something like this:

\n
UPDATE wp_options WHERE option_name='tname' SET option_value = option_value + 'newvalue'\n
\n

That avoids the possible race condition. It would be great if there were an append_transient($name, $val, $timeout) function to do this operation.

\n

I could also lock the table, but that would be really rude.

\n

If I knew my plugin was on a site with InnoDB in its database I could use an SQL transaction. But I don't know that.

\n

Is there a better way?

\n"},"answers":{"kind":"list like","value":[{"answer_id":395728,"author":"Ahmad Ahmad","author_id":212539,"author_profile":"https://wordpress.stackexchange.com/users/212539","pm_score":2,"selected":true,"text":"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\n

so you can try to test "manually disable plugins Wordpress"

\n"},{"answer_id":395743,"author":"Philtao","author_id":212524,"author_profile":"https://wordpress.stackexchange.com/users/212524","pm_score":0,"selected":false,"text":"

For no apparent reason, this morning I can login again!!!

\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions

\n"}],"string":"[\n {\n \"answer_id\": 395728,\n \"author\": \"Ahmad Ahmad\",\n \"author_id\": 212539,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212539\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\\n

so you can try to test "manually disable plugins Wordpress"

\\n\"\n },\n {\n \"answer_id\": 395743,\n \"author\": \"Philtao\",\n \"author_id\": 212524,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212524\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

For no apparent reason, this morning I can login again!!!

\\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\\nThank you for the contributions

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/16"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395714","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/13596/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395714\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/13596/\"\n]"},"input":{"kind":"string","value":"I have a need to capture data in a WordPress plugin and append it into some sort of log.\n\nThe data I want happens to be slow SQL queries from $wpdb->queries. I'm hoping to present useful \"dirty dozen\" SQL queries to my users to help them with optimizations. It's a companion plugin, or maybe a feature set, for [this plugin](https://wordpress.org/plugins/index-wp-mysql-for-speed/). (I'm aware of the performance issues around this kind of system instrumentation. Capture sessions will be limited in duration. Etc.)\n\nIn each relevant pageview I will capture some data and log it. Then later my plugin will retrieve, process, and delete the log. How can I do this data capture in a WordPress-friendly way?\n\nI'm thinking of using a transient to hold the log. I'm using expiring transients in my hope to avoid unprocessed logs from accumulating. My data flow would look something like this (pseudocode).\n\n```php\n$logdata = get_transient( $tName );\n$logdata .= $newdata;\nset_transient( $tName, $logdata, 86400 );\n\n```\n\nBut, on a busy site multiple php instances will race each other. One instance will do its `get_transient()`, then another instance will do its get before the first instance does its set. So one of the instances' data will be lost.\n\nIf I were to do this with plain old MyISAM-compatible SQL I'd do something like this:\n\n```sql\nUPDATE wp_options WHERE option_name='tname' SET option_value = option_value + 'newvalue'\n\n```\n\nThat avoids the possible race condition. It would be great if there were an `append_transient($name, $val, $timeout)` function to do this operation.\n\nI could also lock the table, but that would be really rude.\n\nIf I knew my plugin was on a site with InnoDB in its database I could use an SQL transaction. But I don't know that.\n\n**Is there a better way?**"},"output":{"kind":"string","value":"I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.\n\nso you can try to test \"[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)\""}}},{"rowIdx":7657431,"cells":{"qid":{"kind":"number","value":395795,"string":"395,795"},"question":{"kind":"string","value":"

I have been told that using this in the array:

\n
'orderby'  => 'rand'\n
\n

will cause this:

\n
\n

Ordering by random is extremely expensive to query, involving creating\ntemporary database tables, and scans, as it has to copy the entire\nposts table, then randomly re-order the posts, then finally do the\nactual query on the new table before destroying it.

\n
\n

And I have been advised:

\n
\n

It's much easier to ask for the first post that occurs after a random date.

\n
\n

Can anyone elaborate on this?

\n

Is there an array code line that will do the above?

\n

Any resource regarding this would be very appreciated.

\n"},"answers":{"kind":"list like","value":[{"answer_id":395728,"author":"Ahmad Ahmad","author_id":212539,"author_profile":"https://wordpress.stackexchange.com/users/212539","pm_score":2,"selected":true,"text":"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\n

so you can try to test "manually disable plugins Wordpress"

\n"},{"answer_id":395743,"author":"Philtao","author_id":212524,"author_profile":"https://wordpress.stackexchange.com/users/212524","pm_score":0,"selected":false,"text":"

For no apparent reason, this morning I can login again!!!

\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions

\n"}],"string":"[\n {\n \"answer_id\": 395728,\n \"author\": \"Ahmad Ahmad\",\n \"author_id\": 212539,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212539\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\\n

so you can try to test "manually disable plugins Wordpress"

\\n\"\n },\n {\n \"answer_id\": 395743,\n \"author\": \"Philtao\",\n \"author_id\": 212524,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212524\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

For no apparent reason, this morning I can login again!!!

\\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\\nThank you for the contributions

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/18"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395795","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/202740/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395795\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/202740/\"\n]"},"input":{"kind":"string","value":"I have been told that using this in the array:\n\n```\n'orderby' => 'rand'\n\n```\n\nwill cause this:\n\n> \n> Ordering by random is extremely expensive to query, involving creating\n> temporary database tables, and scans, as it has to copy the entire\n> posts table, then randomly re-order the posts, then finally do the\n> actual query on the new table before destroying it.\n> \n> \n> \n\nAnd I have been advised:\n\n> \n> It's much easier to ask for the first post that occurs after a random date.\n> \n> \n> \n\nCan anyone elaborate on this?\n\nIs there an array code line that will do the above?\n\nAny resource regarding this would be very appreciated."},"output":{"kind":"string","value":"I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.\n\nso you can try to test \"[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)\""}}},{"rowIdx":7657432,"cells":{"qid":{"kind":"number","value":395841,"string":"395,841"},"question":{"kind":"string","value":"

It's really hilarious but my the_date() and the_time() functions show the current date and time instead of the post's publication time, therefore at each refresh of the page, the time changes according to the actual time and date.\nI am using these functions in a single template for a custom post in the loop, like so:

\n
<?php if(have_posts()): ?>\n    <?php while(have_posts()): the_post(); ?>\n       <h3> <?="Titre du projet"?> </h3>\n                <?php the_title(); ?>\n       <h3><?="Description"?></h3>\n                <?php the_content(); ?>\n    <p> <?php the_date(); ?> à <?php the_time(); ?>\n    <?php endwhile?>\n<?php endif;?>\n
\n

What's wrong? I tried other similar functions or get post date in the $post object, but in their format, the date and time are inseparable. and I need them separately.\nThanks.

\n"},"answers":{"kind":"list like","value":[{"answer_id":395728,"author":"Ahmad Ahmad","author_id":212539,"author_profile":"https://wordpress.stackexchange.com/users/212539","pm_score":2,"selected":true,"text":"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\n

so you can try to test "manually disable plugins Wordpress"

\n"},{"answer_id":395743,"author":"Philtao","author_id":212524,"author_profile":"https://wordpress.stackexchange.com/users/212524","pm_score":0,"selected":false,"text":"

For no apparent reason, this morning I can login again!!!

\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions

\n"}],"string":"[\n {\n \"answer_id\": 395728,\n \"author\": \"Ahmad Ahmad\",\n \"author_id\": 212539,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212539\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.

\\n

so you can try to test "manually disable plugins Wordpress"

\\n\"\n },\n {\n \"answer_id\": 395743,\n \"author\": \"Philtao\",\n \"author_id\": 212524,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/212524\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

For no apparent reason, this morning I can login again!!!

\\n

A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\\nThank you for the contributions

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/19"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395841","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210079/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395841\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210079/\"\n]"},"input":{"kind":"string","value":"It's really hilarious but my `the_date()` and `the_time()` functions show the current date and time instead of the post's publication time, therefore at each refresh of the page, the time changes according to the actual time and date.\nI am using these functions in a single template for a custom post in the loop, like so:\n\n```\n\n \n

\n \n

\n \n

à \n \n\n\n```\n\nWhat's wrong? I tried other similar functions or get post date in the `$post` object, but in their format, the date and time are inseparable. and I need them separately.\nThanks."},"output":{"kind":"string","value":"I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.\n\nso you can try to test \"[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)\""}}},{"rowIdx":7657433,"cells":{"qid":{"kind":"number","value":395953,"string":"395,953"},"question":{"kind":"string","value":"

I have registered some styles and scripts that should be loaded if a template part is loaded in a template file. For ex:

\n

in home.php

\n
<?php get_template_part( 'template-parts/external_links'); ?>\n
\n

(this template-part is loaded across different template files) therefore, I want to enqueue (a previously registered file in functions.php)

\n

Using template files for example I use:

\n
if(is_page_template('admin.php')){\n        wp_enqueue_script( 'unicorn-admin');\n    }\n
\n

Is there a way to enqueue a file when get_template_part( 'template-parts/external_links'); is used?

\n"},"answers":{"kind":"list like","value":[{"answer_id":396106,"author":"Pixelsmith","author_id":66368,"author_profile":"https://wordpress.stackexchange.com/users/66368","pm_score":0,"selected":false,"text":"

A question very similar to this has already been answered here. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.

\n

First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:

\n
// Conditional script loading\nfunction conscripts($type) {\n  if($type==='blue'):\n    // Register blue stylesheet\n    wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n  elseif($type==='red'):\n    // Register red stylesheet\n    wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n  endif;\n}\n
\n

Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:

\n
if( get_field('color') == 'red') {\n\n        get_template_part( 'red' ); \n        conscripts('red');\n\n} elseif (get_field('color') == 'blue') {\n\n        get_template_part('blue' ); \n        conscripts('blue');\n}\n
\n

Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.

\n"},{"answer_id":396107,"author":"cameronjonesweb","author_id":65582,"author_profile":"https://wordpress.stackexchange.com/users/65582","pm_score":1,"selected":false,"text":"

Just call wp_enqueue_script/wp_enqueue_style in the template part file itself.

\n"},{"answer_id":396108,"author":"Laloptk","author_id":210397,"author_profile":"https://wordpress.stackexchange.com/users/210397","pm_score":3,"selected":false,"text":"

You can use the get_template_part_{$slug} hook, which fires before a template part is loaded. You can find the reference here, which I find more useful than the official reference.

\n

So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the template-parts/content/content-single.php part, and I created a test.js file, with an alert inside it, in the assets/js/ folder of the theme. Then, I placed the following code in functions.php.

\n
function test_template_part_hook($slug, $name, $args) {\n    wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n
\n

And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the wp_enqueue_scriptfunction with the rest of the arguments that function uses.

\n

So, basically what you need to do is what is described above, using get_template_part_slug as the action name, where slug is the path of the template part file you want to use, in your case, for what I read in you question, slug = 'template-parts/external_links', so the entire hook name should be get_template_part_template-parts/external_links.

\n"}],"string":"[\n {\n \"answer_id\": 396106,\n \"author\": \"Pixelsmith\",\n \"author_id\": 66368,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/66368\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

A question very similar to this has already been answered here. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.

\\n

First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:

\\n
// Conditional script loading\\nfunction conscripts($type) {\\n  if($type==='blue'):\\n    // Register blue stylesheet\\n    wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\\n  elseif($type==='red'):\\n    // Register red stylesheet\\n    wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\\n  endif;\\n}\\n
\\n

Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:

\\n
if( get_field('color') == 'red') {\\n\\n        get_template_part( 'red' ); \\n        conscripts('red');\\n\\n} elseif (get_field('color') == 'blue') {\\n\\n        get_template_part('blue' ); \\n        conscripts('blue');\\n}\\n
\\n

Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.

\\n\"\n },\n {\n \"answer_id\": 396107,\n \"author\": \"cameronjonesweb\",\n \"author_id\": 65582,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/65582\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

Just call wp_enqueue_script/wp_enqueue_style in the template part file itself.

\\n\"\n },\n {\n \"answer_id\": 396108,\n \"author\": \"Laloptk\",\n \"author_id\": 210397,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/210397\",\n \"pm_score\": 3,\n \"selected\": false,\n \"text\": \"

You can use the get_template_part_{$slug} hook, which fires before a template part is loaded. You can find the reference here, which I find more useful than the official reference.

\\n

So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the template-parts/content/content-single.php part, and I created a test.js file, with an alert inside it, in the assets/js/ folder of the theme. Then, I placed the following code in functions.php.

\\n
function test_template_part_hook($slug, $name, $args) {\\n    wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\\n}\\n\\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\\n
\\n

And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the wp_enqueue_scriptfunction with the rest of the arguments that function uses.

\\n

So, basically what you need to do is what is described above, using get_template_part_slug as the action name, where slug is the path of the template part file you want to use, in your case, for what I read in you question, slug = 'template-parts/external_links', so the entire hook name should be get_template_part_template-parts/external_links.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/21"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/395953","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/206371/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/395953\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/206371/\"\n]"},"input":{"kind":"string","value":"I have registered some styles and scripts that should be loaded if a template part is loaded in a template file. For ex:\n\nin home.php\n\n```\n\n\n```\n\n(this template-part is loaded across different template files) therefore, I want to enqueue (a previously registered file in functions.php)\n\nUsing template files for example I use:\n\n```\nif(is_page_template('admin.php')){\n wp_enqueue_script( 'unicorn-admin');\n }\n\n```\n\nIs there a way to enqueue a file when get\\_template\\_part( 'template-parts/external\\_links'); is used?"},"output":{"kind":"string","value":"You can use the `get_template_part_{$slug}` hook, which fires before a template part is loaded. You can find the reference [here](https://wp-kama.com/hook/get_template_part_(slug)), which I find more useful than the official reference.\n\nSo, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the `template-parts/content/content-single.php` part, and I created a `test.js` file, with an alert inside it, in the `assets/js/` folder of the theme. Then, I placed the following code in `functions.php`.\n\n```\nfunction test_template_part_hook($slug, $name, $args) {\n wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n\n```\n\nAnd the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the `wp_enqueue_script`function with the rest of the arguments that function uses.\n\nSo, basically what you need to do is what is described above, using `get_template_part_slug` as the action name, where `slug` is the path of the template part file you want to use, in your case, for what I read in you question, `slug = 'template-parts/external_links'`, so the entire hook name should be `get_template_part_template-parts/external_links`."}}},{"rowIdx":7657434,"cells":{"qid":{"kind":"number","value":396005,"string":"396,005"},"question":{"kind":"string","value":"

I made a config.php file where I store some arrays for configuration like LDAP and other things.\nI need to call it on different templates but I also need to require it into function.php.

\n

When I do this this, I have warning and all my tables become Undefined.

\n

EDIT

\n

I found this solution : call my config.php into functions.php with : require ( get_template_directory() . '/config.php' );

\n

Replaced this require from all my tempate/views by global $ARRAY_NAME;

\n"},"answers":{"kind":"list like","value":[{"answer_id":396106,"author":"Pixelsmith","author_id":66368,"author_profile":"https://wordpress.stackexchange.com/users/66368","pm_score":0,"selected":false,"text":"

A question very similar to this has already been answered here. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.

\n

First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:

\n
// Conditional script loading\nfunction conscripts($type) {\n  if($type==='blue'):\n    // Register blue stylesheet\n    wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n  elseif($type==='red'):\n    // Register red stylesheet\n    wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n  endif;\n}\n
\n

Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:

\n
if( get_field('color') == 'red') {\n\n        get_template_part( 'red' ); \n        conscripts('red');\n\n} elseif (get_field('color') == 'blue') {\n\n        get_template_part('blue' ); \n        conscripts('blue');\n}\n
\n

Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.

\n"},{"answer_id":396107,"author":"cameronjonesweb","author_id":65582,"author_profile":"https://wordpress.stackexchange.com/users/65582","pm_score":1,"selected":false,"text":"

Just call wp_enqueue_script/wp_enqueue_style in the template part file itself.

\n"},{"answer_id":396108,"author":"Laloptk","author_id":210397,"author_profile":"https://wordpress.stackexchange.com/users/210397","pm_score":3,"selected":false,"text":"

You can use the get_template_part_{$slug} hook, which fires before a template part is loaded. You can find the reference here, which I find more useful than the official reference.

\n

So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the template-parts/content/content-single.php part, and I created a test.js file, with an alert inside it, in the assets/js/ folder of the theme. Then, I placed the following code in functions.php.

\n
function test_template_part_hook($slug, $name, $args) {\n    wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n
\n

And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the wp_enqueue_scriptfunction with the rest of the arguments that function uses.

\n

So, basically what you need to do is what is described above, using get_template_part_slug as the action name, where slug is the path of the template part file you want to use, in your case, for what I read in you question, slug = 'template-parts/external_links', so the entire hook name should be get_template_part_template-parts/external_links.

\n"}],"string":"[\n {\n \"answer_id\": 396106,\n \"author\": \"Pixelsmith\",\n \"author_id\": 66368,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/66368\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

A question very similar to this has already been answered here. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.

\\n

First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:

\\n
// Conditional script loading\\nfunction conscripts($type) {\\n  if($type==='blue'):\\n    // Register blue stylesheet\\n    wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\\n  elseif($type==='red'):\\n    // Register red stylesheet\\n    wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\\n  endif;\\n}\\n
\\n

Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:

\\n
if( get_field('color') == 'red') {\\n\\n        get_template_part( 'red' ); \\n        conscripts('red');\\n\\n} elseif (get_field('color') == 'blue') {\\n\\n        get_template_part('blue' ); \\n        conscripts('blue');\\n}\\n
\\n

Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.

\\n\"\n },\n {\n \"answer_id\": 396107,\n \"author\": \"cameronjonesweb\",\n \"author_id\": 65582,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/65582\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

Just call wp_enqueue_script/wp_enqueue_style in the template part file itself.

\\n\"\n },\n {\n \"answer_id\": 396108,\n \"author\": \"Laloptk\",\n \"author_id\": 210397,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/210397\",\n \"pm_score\": 3,\n \"selected\": false,\n \"text\": \"

You can use the get_template_part_{$slug} hook, which fires before a template part is loaded. You can find the reference here, which I find more useful than the official reference.

\\n

So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the template-parts/content/content-single.php part, and I created a test.js file, with an alert inside it, in the assets/js/ folder of the theme. Then, I placed the following code in functions.php.

\\n
function test_template_part_hook($slug, $name, $args) {\\n    wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\\n}\\n\\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\\n
\\n

And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the wp_enqueue_scriptfunction with the rest of the arguments that function uses.

\\n

So, basically what you need to do is what is described above, using get_template_part_slug as the action name, where slug is the path of the template part file you want to use, in your case, for what I read in you question, slug = 'template-parts/external_links', so the entire hook name should be get_template_part_template-parts/external_links.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/22"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396005","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/194938/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396005\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/194938/\"\n]"},"input":{"kind":"string","value":"I made a config.php file where I store some arrays for configuration like LDAP and other things.\nI need to call it on different templates but I also need to require it into function.php.\n\nWhen I do this this, I have warning and all my tables become Undefined.\n\n**EDIT**\n\nI found this solution : call my config.php into functions.php with : `require ( get_template_directory() . '/config.php' );`\n\nReplaced this require from all my tempate/views by `global $ARRAY_NAME;`"},"output":{"kind":"string","value":"You can use the `get_template_part_{$slug}` hook, which fires before a template part is loaded. You can find the reference [here](https://wp-kama.com/hook/get_template_part_(slug)), which I find more useful than the official reference.\n\nSo, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the `template-parts/content/content-single.php` part, and I created a `test.js` file, with an alert inside it, in the `assets/js/` folder of the theme. Then, I placed the following code in `functions.php`.\n\n```\nfunction test_template_part_hook($slug, $name, $args) {\n wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n\n```\n\nAnd the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the `wp_enqueue_script`function with the rest of the arguments that function uses.\n\nSo, basically what you need to do is what is described above, using `get_template_part_slug` as the action name, where `slug` is the path of the template part file you want to use, in your case, for what I read in you question, `slug = 'template-parts/external_links'`, so the entire hook name should be `get_template_part_template-parts/external_links`."}}},{"rowIdx":7657435,"cells":{"qid":{"kind":"number","value":396013,"string":"396,013"},"question":{"kind":"string","value":"

I'm trying to save post id and keyword (Yoast Focus Keyword) to a custom table when post is created or updated via save_post action. It saves everything fine on Publish (first-time) but when I update the post, it gets old value for focus keyword from database and doesn't save the new value.

\n

for example\nFocus Keyword (Publish) = "Hello World" (works fine and keyword is stored properly)\nFocus Keyword (1st Update) = "Hello" (Doesn't work and keeps "Hello World" in custom table)\nFocus Keyword (2nd Update) = "Hello again" (It saves "Hello")

\n

So basically the problem is that get_post_meta($post_id, '_yoast_wpseo_focuskw', true) returns which is already in the database and not the new value that is being saved.

\n

What is the best way to get the new value while the post is being saved via save_post action?

\n

$_POST['_yoast_wpseo_focuskw'] won't work because Yoast Focus Keyword input field doesn't have name set on input field. Screenshot

\n

Any help would be appreciated. Thanks

\n

This is my code.

\n
add_action('save_post', 'my_custom_table');\nfunction my_custom_table($post_id) {\n    global $wpdb;\n    $table_name = $wpdb->prefix . "custom_table";\n\n    $data = [\n        'post_id' => $post_id,\n        'keyword' => get_post_meta( $post_id, '_yoast_wpseo_focuskw', true )\n    ];\n\n    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {\n        return;\n    } else {\n\n        //check if new post so insert\n        if( strpos( wp_get_raw_referer(), 'post-new' ) > 0 ) {\n\n            if (get_post_status($post_id) === 'publish') {\n\n                $wpdb->insert( \n                    $table_name, \n                    $data\n                );\n\n            }\n\n        } else {\n\n            $wpdb->update( \n                $table_name, \n                $data,\n                array( \n                    'post_id' => $post_id\n                ),\n                array( '%d', '%s' ),\n                array( '%d' )\n            );\n        }\n\n    }\n\n}\n
\n"},"answers":{"kind":"list like","value":[{"answer_id":396045,"author":"kovshenin","author_id":1316,"author_profile":"https://wordpress.stackexchange.com/users/1316","pm_score":0,"selected":false,"text":"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\n"},{"answer_id":396050,"author":"Linnea Huxford","author_id":86210,"author_profile":"https://wordpress.stackexchange.com/users/86210","pm_score":3,"selected":true,"text":"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\n"}],"string":"[\n {\n \"answer_id\": 396045,\n \"author\": \"kovshenin\",\n \"author_id\": 1316,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/1316\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\\n\"\n },\n {\n \"answer_id\": 396050,\n \"author\": \"Linnea Huxford\",\n \"author_id\": 86210,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/86210\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/22"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396013","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/161037/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396013\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/161037/\"\n]"},"input":{"kind":"string","value":"I'm trying to save post id and keyword (Yoast Focus Keyword) to a custom table when post is created or updated via `save_post` action. It saves everything fine on Publish (first-time) but when I update the post, it gets old value for focus keyword from database and doesn't save the new value.\n\nfor example\nFocus Keyword (Publish) = \"Hello World\" (works fine and keyword is stored properly)\nFocus Keyword (1st Update) = \"Hello\" (Doesn't work and keeps \"Hello World\" in custom table)\nFocus Keyword (2nd Update) = \"Hello again\" (It saves \"Hello\")\n\nSo basically the problem is that get\\_post\\_meta($post\\_id, '\\_yoast\\_wpseo\\_focuskw', true) returns which is already in the database and not the new value that is being saved.\n\nWhat is the best way to get the new value while the post is being saved via `save_post` action?\n\n$\\_POST['\\_yoast\\_wpseo\\_focuskw'] won't work because Yoast Focus Keyword input field doesn't have name set on input field. [Screenshot](https://i.imgur.com/a94kCl8.png)\n\nAny help would be appreciated. Thanks\n\nThis is my code.\n\n```php\nadd_action('save_post', 'my_custom_table');\nfunction my_custom_table($post_id) {\n global $wpdb;\n $table_name = $wpdb->prefix . \"custom_table\";\n\n $data = [\n 'post_id' => $post_id,\n 'keyword' => get_post_meta( $post_id, '_yoast_wpseo_focuskw', true )\n ];\n\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {\n return;\n } else {\n\n //check if new post so insert\n if( strpos( wp_get_raw_referer(), 'post-new' ) > 0 ) {\n\n if (get_post_status($post_id) === 'publish') {\n\n $wpdb->insert( \n $table_name, \n $data\n );\n\n }\n\n } else {\n\n $wpdb->update( \n $table_name, \n $data,\n array( \n 'post_id' => $post_id\n ),\n array( '%d', '%s' ),\n array( '%d' )\n );\n }\n\n }\n\n}\n\n```"},"output":{"kind":"string","value":"WordPress fires the [updated\\_{$meta\\_type}\\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook."}}},{"rowIdx":7657436,"cells":{"qid":{"kind":"number","value":396024,"string":"396,024"},"question":{"kind":"string","value":"

Here's my meta query:

\n
$taxonomy_term = 1494;\n$args['meta_query'] = array(\n        'relation' => 'OR',\n        'mp_exists' => array(\n            'key' => 'tdlrm_mp_'.$taxonomy_term,\n            'type' => 'NUMERIC',\n        ),\n        'mp_not_exists' => array(\n            'key' => 'tdlrm_mp_'.$taxonomy_term,\n            'compare' => 'NOT EXISTS'\n        )\n    );\n$args['orderby'] = array( 'meta_value_num' => 'ASC', 'title' => 'ASC' );\n
\n

The posts where 'tdlrm_mp_'.$taxonomy key exists get placed first as expected. Hovewer, the rest do not get ordered by their title (actually, I can't figure out what they are ordered by). What am I doing wrong?

\n

This answer doesn't help. I wrote my query according to this manual.

\n

Update

\n

I ran WP's MySQL query in my database and saw the postmeta table joined twice. The posts that have no tdlrm_mp_{term} meta key still have some other meta key in the resulting table and the rest of the posts get ordered by the value of that meta. (mp_exists adds the first postmeta table, mp_not_exists adds the second one, where mp_exists does not exist. Still some other meta key exists in the first joined table, so the posts keep getting ordered by that column).

\n"},"answers":{"kind":"list like","value":[{"answer_id":396045,"author":"kovshenin","author_id":1316,"author_profile":"https://wordpress.stackexchange.com/users/1316","pm_score":0,"selected":false,"text":"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\n"},{"answer_id":396050,"author":"Linnea Huxford","author_id":86210,"author_profile":"https://wordpress.stackexchange.com/users/86210","pm_score":3,"selected":true,"text":"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\n"}],"string":"[\n {\n \"answer_id\": 396045,\n \"author\": \"kovshenin\",\n \"author_id\": 1316,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/1316\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\\n\"\n },\n {\n \"answer_id\": 396050,\n \"author\": \"Linnea Huxford\",\n \"author_id\": 86210,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/86210\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/23"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396024","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/190417/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396024\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/190417/\"\n]"},"input":{"kind":"string","value":"Here's my meta query:\n\n```\n$taxonomy_term = 1494;\n$args['meta_query'] = array(\n 'relation' => 'OR',\n 'mp_exists' => array(\n 'key' => 'tdlrm_mp_'.$taxonomy_term,\n 'type' => 'NUMERIC',\n ),\n 'mp_not_exists' => array(\n 'key' => 'tdlrm_mp_'.$taxonomy_term,\n 'compare' => 'NOT EXISTS'\n )\n );\n$args['orderby'] = array( 'meta_value_num' => 'ASC', 'title' => 'ASC' );\n\n```\n\nThe posts where `'tdlrm_mp_'.$taxonomy` key exists get placed first as expected. Hovewer, the rest do not get ordered by their title (actually, I can't figure out what they are ordered by). What am I doing wrong?\n\n[This answer](https://wordpress.stackexchange.com/questions/311227/wp-query-orderby-custom-field-then-post-date-in-one-query) doesn't help. I wrote my query according to [this manual](https://developer.wordpress.org/reference/classes/wp_query/#:%7E:text=%27orderby%27%C2%A0%20%3D%3E%20array(%20%27meta_value_num%27%20%3D%3E%20%27DESC%27%2C%20%27title%27%20%3D%3E%20%27ASC%27%20)%2C).\n\n**Update**\n\nI ran WP's MySQL query in my database and saw the postmeta table joined twice. The posts that have no tdlrm\\_mp\\_{term} meta key still have some other meta key in the resulting table and the rest of the posts get ordered by the value of that meta. (`mp_exists` adds the first postmeta table, `mp_not_exists` adds the second one, where `mp_exists` does not exist. Still some other meta key exists in the first joined table, so the posts keep getting ordered by that column)."},"output":{"kind":"string","value":"WordPress fires the [updated\\_{$meta\\_type}\\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook."}}},{"rowIdx":7657437,"cells":{"qid":{"kind":"number","value":396039,"string":"396,039"},"question":{"kind":"string","value":"

I try tu run wp form with ajax but console return\nWordpress admin-ajax.php 400 bad request.

\n
 jQuery(function ($) {\n        $(document).ready(function () {\n    \n    \n            jQuery('#form_add_to_cart').on('submit', function () {\n                \n                jQuery.ajax({\n                    url: 'https://domain.com/wp-admin/admin-ajax.php', \n                    method: 'post',\n                    contentType : 'application/json; charset=utf-8',\n                    data: $("#form_add_to_cart").serializeArray(),\n                    success: function (response) {\n                        alert(response);\n                    },\n                    fail: function (err) {\n                        alert("There was an error: " + err);\n                    }\n                });\n                return false;\n            });\n        });\n    });\n
\n

here is my functions.php file:

\n
add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users\nadd_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users.\n\nfunction send_form(){\n    if (isset($_POST['send_form'])){\n        echo'ok';\n    }\n    else{\n        echo 'bad';\n    }\n}\n
\n

and my form:

\n
            <form name="form_add_to_cart" method="POST" class="form_product" id="form_add_to_cart" action="">\n\n                        <input hidden="hidden" name="action" id="add_product_to_cart"\n                               value="send_form">\n                        <input class="btn btn-primary" type="submit"\n                               name="add_to_cart-<?php echo $product_id; ?>" id="add_to_cart"\n                               value="Dodaj">\n
\n\n

all form : https://pastebin.com/YJXTjGjJ

\n

WORKING:

\n
jQuery(function ($) {\n        $(document).ready(function () {\n\n\n            jQuery('#form_add_to_cart').on('submit', function () {\n\n                jQuery.ajax({\n                    url: 'https://domain.com/wp-admin/admin-ajax.php', \n                    method: 'post',\n                    data: $("#form_add_to_cart").serializeArray(),\n                    success: function (response) {\n                        alert(response);\n                    },\n                    fail: function (err) {\n                        alert("There was an error: " + err);\n                    }\n                });\n                return false;\n            });\n        });\n    });\n
\n"},"answers":{"kind":"list like","value":[{"answer_id":396045,"author":"kovshenin","author_id":1316,"author_profile":"https://wordpress.stackexchange.com/users/1316","pm_score":0,"selected":false,"text":"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\n"},{"answer_id":396050,"author":"Linnea Huxford","author_id":86210,"author_profile":"https://wordpress.stackexchange.com/users/86210","pm_score":3,"selected":true,"text":"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\n"}],"string":"[\n {\n \"answer_id\": 396045,\n \"author\": \"kovshenin\",\n \"author_id\": 1316,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/1316\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

\\n

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

\\n\"\n },\n {\n \"answer_id\": 396050,\n \"author\": \"Linnea Huxford\",\n \"author_id\": 86210,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/86210\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/23"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396039","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212803/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396039\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212803/\"\n]"},"input":{"kind":"string","value":"I try tu run wp form with ajax but console return\nWordpress admin-ajax.php 400 bad request.\n\n```\n jQuery(function ($) {\n $(document).ready(function () {\n\n jQuery('#form_add_to_cart').on('submit', function () {\n\n jQuery.ajax({\n url: 'https://domain.com/wp-admin/admin-ajax.php', \n method: 'post',\n contentType : 'application/json; charset=utf-8',\n data: $(\"#form_add_to_cart\").serializeArray(),\n success: function (response) {\n alert(response);\n },\n fail: function (err) {\n alert(\"There was an error: \" + err);\n }\n });\n return false;\n });\n });\n });\n\n```\n\nhere is my functions.php file:\n\n```\nadd_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users\nadd_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users.\n\nfunction send_form(){\n if (isset($_POST['send_form'])){\n echo'ok';\n }\n else{\n echo 'bad';\n }\n}\n\n```\n\nand my form:\n\n```\n
\n\n \n \" id=\"add_to_cart\"\n value=\"Dodaj\">\n\n```\n\nall form : \n\nWORKING:\n\n```\njQuery(function ($) {\n $(document).ready(function () {\n\n jQuery('#form_add_to_cart').on('submit', function () {\n\n jQuery.ajax({\n url: 'https://domain.com/wp-admin/admin-ajax.php', \n method: 'post',\n data: $(\"#form_add_to_cart\").serializeArray(),\n success: function (response) {\n alert(response);\n },\n fail: function (err) {\n alert(\"There was an error: \" + err);\n }\n });\n return false;\n });\n });\n });\n\n```"},"output":{"kind":"string","value":"WordPress fires the [updated\\_{$meta\\_type}\\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook."}}},{"rowIdx":7657438,"cells":{"qid":{"kind":"number","value":396105,"string":"396,105"},"question":{"kind":"string","value":"

I would like to use the rest API to take a username and a password sent in a request and use it in wp_authenticate() then send back if the credentials were correct. How would I do this.

\n"},"answers":{"kind":"list like","value":[{"answer_id":396119,"author":"Aurovrata","author_id":52120,"author_profile":"https://wordpress.stackexchange.com/users/52120","pm_score":1,"selected":false,"text":"

There are 3 ways to authenticate a user using a REST api end-point request,

\n

1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the wp_signon() function to sign-in your user, and if successful you set the authentication cookie using wp_set_auth_cookie() function,

\n
$creds = array(\n    'user_login'    => 'example',\n    'user_password' => 'plaintextpw',\n    'remember'      => true\n);\n\n$user = wp_signon( $creds, false );\n\nif ( is_wp_error( $user ) ) {\n    $msg = $user->get_error_message();\n}else{\n  wp_clear_auth_cookie();\n  wp_set_current_user ( $user->ID ); // Set the current user detail\n  wp_set_auth_cookie  ( $user->ID ); // Set auth details in cookie\n  $msg = "Logged in successfully"; \n}\n
\n

You can find a discussion on this WordPress forum thread.

\n

2- Using Basic Authentication requests to your own server

\n

the idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a plugin on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server,

\n
let user='...', pw='...';\njQuery.ajax({\n   url: 'http://your-domain/wp-json/wp/v2/posts/50',\n   method: 'DELETE',\n   crossDomain: true,\n   beforeSend: function ( xhr ) {\n       xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) );\n   },\n   success: function( data, txtStatus, xhr ) {\n       console.log( data );\n       console.log( xhr.status );\n   }\n});\n
\n

For more details see this detailed tutorial

\n

3- using a third party authentication such the open OAuth.

\n

This is what Google uses, and allows your site to identify users based on their Google login credentials. WordPress.com also uses this method for its blog service authentication.

\n

The idea is that your users logs-in a server which identifies them (using cookies on their browser).

\n

Once authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward.

\n

You could use a third party authentication service, such Google, in which case you can follow this youtube tutorial which walks you through the basics to setting up a Google API project to allow your application to make authentication requests.

\n

Alternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as WP-OAuth Server, and its extensive documentation.

\n"},{"answer_id":396120,"author":"Mark Kaplun","author_id":23970,"author_profile":"https://wordpress.stackexchange.com/users/23970","pm_score":0,"selected":false,"text":"

The best way to "login" a user on a site is to use the wordpress login form. As other comments and answers suggest, to do it in the way the title of the question implies requires some reinvention of the wheel. The login form in addition to doing the actual login also provides feedback when the login fails and provides a flow to reset the password.

\n

Even if you are going for a fully "headless" wordpress experiance you probably should be 100% sure the effort of reinventing the login form is worth it.

\n

Now if you mean to authenticate user from a different domain it is just not going to work as cookies will be set only on the site's domain IIRC.

\n

So the only valid use case is server to server communication in which you need to store the cookies you recieve from your "login" request and reuse them in the next requests, but this implies you store the user and password on your server in which case using application passwords might actually be a better solution.

\n"}],"string":"[\n {\n \"answer_id\": 396119,\n \"author\": \"Aurovrata\",\n \"author_id\": 52120,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/52120\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

There are 3 ways to authenticate a user using a REST api end-point request,

\\n

1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the wp_signon() function to sign-in your user, and if successful you set the authentication cookie using wp_set_auth_cookie() function,

\\n
$creds = array(\\n    'user_login'    => 'example',\\n    'user_password' => 'plaintextpw',\\n    'remember'      => true\\n);\\n\\n$user = wp_signon( $creds, false );\\n\\nif ( is_wp_error( $user ) ) {\\n    $msg = $user->get_error_message();\\n}else{\\n  wp_clear_auth_cookie();\\n  wp_set_current_user ( $user->ID ); // Set the current user detail\\n  wp_set_auth_cookie  ( $user->ID ); // Set auth details in cookie\\n  $msg = "Logged in successfully"; \\n}\\n
\\n

You can find a discussion on this WordPress forum thread.

\\n

2- Using Basic Authentication requests to your own server

\\n

the idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a plugin on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server,

\\n
let user='...', pw='...';\\njQuery.ajax({\\n   url: 'http://your-domain/wp-json/wp/v2/posts/50',\\n   method: 'DELETE',\\n   crossDomain: true,\\n   beforeSend: function ( xhr ) {\\n       xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) );\\n   },\\n   success: function( data, txtStatus, xhr ) {\\n       console.log( data );\\n       console.log( xhr.status );\\n   }\\n});\\n
\\n

For more details see this detailed tutorial

\\n

3- using a third party authentication such the open OAuth.

\\n

This is what Google uses, and allows your site to identify users based on their Google login credentials. WordPress.com also uses this method for its blog service authentication.

\\n

The idea is that your users logs-in a server which identifies them (using cookies on their browser).

\\n

Once authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward.

\\n

You could use a third party authentication service, such Google, in which case you can follow this youtube tutorial which walks you through the basics to setting up a Google API project to allow your application to make authentication requests.

\\n

Alternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as WP-OAuth Server, and its extensive documentation.

\\n\"\n },\n {\n \"answer_id\": 396120,\n \"author\": \"Mark Kaplun\",\n \"author_id\": 23970,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/23970\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

The best way to "login" a user on a site is to use the wordpress login form. As other comments and answers suggest, to do it in the way the title of the question implies requires some reinvention of the wheel. The login form in addition to doing the actual login also provides feedback when the login fails and provides a flow to reset the password.

\\n

Even if you are going for a fully "headless" wordpress experiance you probably should be 100% sure the effort of reinventing the login form is worth it.

\\n

Now if you mean to authenticate user from a different domain it is just not going to work as cookies will be set only on the site's domain IIRC.

\\n

So the only valid use case is server to server communication in which you need to store the cookies you recieve from your "login" request and reuse them in the next requests, but this implies you store the user and password on your server in which case using application passwords might actually be a better solution.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/24"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396105","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212716/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396105\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212716/\"\n]"},"input":{"kind":"string","value":"I would like to use the rest API to take a username and a password sent in a request and use it in wp\\_authenticate() then send back if the credentials were correct. How would I do this."},"output":{"kind":"string","value":"There are 3 ways to authenticate a user using a REST api end-point request,\n\n1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the `wp_signon()` [function](https://developer.wordpress.org/reference/functions/wp_signon/) to sign-in your user, and if successful you set the authentication cookie using wp\\_set\\_auth\\_cookie() [function](https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/),\n\n```\n$creds = array(\n 'user_login' => 'example',\n 'user_password' => 'plaintextpw',\n 'remember' => true\n);\n\n$user = wp_signon( $creds, false );\n\nif ( is_wp_error( $user ) ) {\n $msg = $user->get_error_message();\n}else{\n wp_clear_auth_cookie();\n wp_set_current_user ( $user->ID ); // Set the current user detail\n wp_set_auth_cookie ( $user->ID ); // Set auth details in cookie\n $msg = \"Logged in successfully\"; \n}\n\n```\n\nYou can find a discussion on this WordPress forum [thread](https://wordpress.org/support/topic/login-a-wp-user-via-rest-api/).\n\n2- Using Basic Authentication requests to your own server\n\nthe idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a [plugin](https://github.com/WP-API/Basic-Auth) on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server,\n\n```\nlet user='...', pw='...';\njQuery.ajax({\n url: 'http://your-domain/wp-json/wp/v2/posts/50',\n method: 'DELETE',\n crossDomain: true,\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) );\n },\n success: function( data, txtStatus, xhr ) {\n console.log( data );\n console.log( xhr.status );\n }\n});\n\n```\n\nFor more details see this detailed [tutorial](https://www.cloudways.com/blog/setup-basic-authentication-in-wordpress-rest-api/#Send-Authenticated-Requests-Using-JavaScript)\n\n3- using a third party authentication such the open [OAuth](https://en.wikipedia.org/wiki/OAuth).\n\nThis is what Google uses, and allows your site to identify users based on their Google login credentials. [WordPress.com](https://developer.wordpress.com/docs/oauth2/) also uses this method for its blog service authentication.\n\nThe idea is that your users logs-in a server which identifies them (using cookies on their browser).\n\nOnce authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward.\n\nYou could use a third party authentication service, such Google, in which case you can follow this youtube [tutorial](https://www.youtube.com/watch?v=0UcayuC_Ay8) which walks you through the basics to setting up a Google API project to allow your application to make authentication requests.\n\nAlternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as [WP-OAuth Server](https://wordpress.org/plugins/oauth2-provider/), and its extensive [documentation](https://wp-oauth.com/docs/general/main-concepts/)."}}},{"rowIdx":7657439,"cells":{"qid":{"kind":"number","value":396171,"string":"396,171"},"question":{"kind":"string","value":"

How to display the number of articles published per user excluding users who do not publish articles. My message type is recipe. I would like to receive a code to get there in wp-query\nthank you very much for your help

\n

I give you a piece of code.\nThanks to this code I am able to display the total number of recipes, but I would have liked to have this:\nUser A posted 14 cooking recipes, User B posted 2 cooking recipes\nect..\nuser member1 should have 2 recipes

\n
<?php\n// 1. We define the arguments to define what we want to recover \n$args = array ( 'post_type' => 'recipe', 'posts_per_page' => '16', );\n\n// 2. We run the WP Query \n// The Query \n$the_query = new WP_Query ($args);\n\n// 3. we display the number of messages and the authors!\n // The Loop \nif ($the_query-> have_posts ()) {\n echo count_user_posts (2, $args); \necho 'recipes for'; \necho get_the_author (2, $args); \necho '<br>'; \necho count_user_posts (1, $args); \necho 'recipes for';\n echo get_the_author (1, $args);\n\n// 3. We launch the loop to display the articles and the authors! \n// The Loop \necho '<ul>'; \nwhile ($the_query-> have_posts ()) ​{ \n$the_query-> the_post (); \necho '<li>'. get_the_title (). '<li>'; \necho '<li>'. get_the_author (). '<li>';\n​}\n​echo '<ul>';\n​}\n​else { \n// no posts found }\n/ * Restore original Post Data * / \nwp_reset_postdata ();\n​?>\n\n        \n\n    \n
\n

\"enter

\n"},"answers":{"kind":"list like","value":[{"answer_id":396189,"author":"Joe","author_id":34273,"author_profile":"https://wordpress.stackexchange.com/users/34273","pm_score":1,"selected":true,"text":"

If you have access to user IDs, you can use the count_user_posts() function.

\n

You would get the number of posts by a user like this:

\n
//Assume the variable $thisUser is equal to a valid user ID\n$ThisUserCount = count_user_posts($thisUser, 'recipe');\n
\n

EDIT:\nWhere you're calling the count_user_posts() function, you're passing it the array $args instead of the post type, 'recipe'.

\n
<?php\n// 1. We define the arguments to define what we want to recover\n$args = array (\n    'post_type' => 'recipe',\n    'posts_per_page' => '16',\n);\n\n// 2. We run the WP Query\n// The Query\n$the_query = new WP_Query ($args);\n\n// 3. we display the number of messages and the authors!\n// The Loop\nif ($the_query-> have_posts()) {\n    //Set arguments to grab all authors with published recipes, and order them by user ID\n    $authorArgs = array(\n        'orderby' => 'ID',\n        'has_published_posts' => array('recipe'),\n    );\n\n    //Create an array of all authors with recipes published\n    $recipeAuthors = get_users($authorArgs);\n\n    //Loop through each recipe author\n    foreach($recipeAuthors as $user){\n        //Output user post count for recipes\n        echo count_user_posts($user->ID, 'recipe');\n        echo ' recipes for ';\n\n        //Output user's display name\n        echo $user->display_name;\n        echo '<br />';\n    }\n\n    // 3. We launch the loop to display the articles and the authors!\n    // The Loop\n    echo '<ul>';\n    while ($the_query-> have_posts()) {\n        $the_query-> the_post();\n        echo '<li>'. get_the_title(). '</li>';\n        echo '<li>'. get_the_author(). '</li>';\n    }\n    echo '</ul>';\n} else {\n    // no posts found\n}\nwp_reset_postdata ();​?>\n
\n

Also, your get_the_author(2,$args) function calls are not correct. get_the_author() does not accept any parameters anymore, and it only returns the Display Name of the author of the current post in the Loop.

\n"},{"answer_id":396205,"author":"Pixelsmith","author_id":66368,"author_profile":"https://wordpress.stackexchange.com/users/66368","pm_score":1,"selected":false,"text":"

If you're just looking to display authors who have posted at least one article in your custom post type you can ignore the above code and just do this:

\n
// Array of WP_User objects.\n$authors = get_users();\n\n// Loop thru the array and get the post count for each user\nforeach ( $authors as $author ) {\n    $posts = count_user_posts($author->ID, 'movies');\n\n    // Only return users who have at least one post \n    if ($posts > 0):\n        echo '<p><span>' . esc_html( $author->display_name ) . ': ' . $posts . '</span>';\n    endif; \n}\n\n// Only Necessary if you're running another loop or query on the page\nwp_reset_postdata ();​\n
\n

Good luck!

\n"}],"string":"[\n {\n \"answer_id\": 396189,\n \"author\": \"Joe\",\n \"author_id\": 34273,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/34273\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

If you have access to user IDs, you can use the count_user_posts() function.

\\n

You would get the number of posts by a user like this:

\\n
//Assume the variable $thisUser is equal to a valid user ID\\n$ThisUserCount = count_user_posts($thisUser, 'recipe');\\n
\\n

EDIT:\\nWhere you're calling the count_user_posts() function, you're passing it the array $args instead of the post type, 'recipe'.

\\n
<?php\\n// 1. We define the arguments to define what we want to recover\\n$args = array (\\n    'post_type' => 'recipe',\\n    'posts_per_page' => '16',\\n);\\n\\n// 2. We run the WP Query\\n// The Query\\n$the_query = new WP_Query ($args);\\n\\n// 3. we display the number of messages and the authors!\\n// The Loop\\nif ($the_query-> have_posts()) {\\n    //Set arguments to grab all authors with published recipes, and order them by user ID\\n    $authorArgs = array(\\n        'orderby' => 'ID',\\n        'has_published_posts' => array('recipe'),\\n    );\\n\\n    //Create an array of all authors with recipes published\\n    $recipeAuthors = get_users($authorArgs);\\n\\n    //Loop through each recipe author\\n    foreach($recipeAuthors as $user){\\n        //Output user post count for recipes\\n        echo count_user_posts($user->ID, 'recipe');\\n        echo ' recipes for ';\\n\\n        //Output user's display name\\n        echo $user->display_name;\\n        echo '<br />';\\n    }\\n\\n    // 3. We launch the loop to display the articles and the authors!\\n    // The Loop\\n    echo '<ul>';\\n    while ($the_query-> have_posts()) {\\n        $the_query-> the_post();\\n        echo '<li>'. get_the_title(). '</li>';\\n        echo '<li>'. get_the_author(). '</li>';\\n    }\\n    echo '</ul>';\\n} else {\\n    // no posts found\\n}\\nwp_reset_postdata ();​?>\\n
\\n

Also, your get_the_author(2,$args) function calls are not correct. get_the_author() does not accept any parameters anymore, and it only returns the Display Name of the author of the current post in the Loop.

\\n\"\n },\n {\n \"answer_id\": 396205,\n \"author\": \"Pixelsmith\",\n \"author_id\": 66368,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/66368\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

If you're just looking to display authors who have posted at least one article in your custom post type you can ignore the above code and just do this:

\\n
// Array of WP_User objects.\\n$authors = get_users();\\n\\n// Loop thru the array and get the post count for each user\\nforeach ( $authors as $author ) {\\n    $posts = count_user_posts($author->ID, 'movies');\\n\\n    // Only return users who have at least one post \\n    if ($posts > 0):\\n        echo '<p><span>' . esc_html( $author->display_name ) . ': ' . $posts . '</span>';\\n    endif; \\n}\\n\\n// Only Necessary if you're running another loop or query on the page\\nwp_reset_postdata ();​\\n
\\n

Good luck!

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396171","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212622/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396171\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212622/\"\n]"},"input":{"kind":"string","value":"How to display the number of articles published per user excluding users who do not publish articles. My message type is recipe. I would like to receive a code to get there in wp-query\nthank you very much for your help\n\nI give you a piece of code.\nThanks to this code I am able to display the total number of recipes, but I would have liked to have this:\nUser A posted 14 cooking recipes, User B posted 2 cooking recipes\nect..\nuser member1 should have 2 recipes\n\n```\n 'recipe', 'posts_per_page' => '16', );\n\n// 2. We run the WP Query \n// The Query \n$the_query = new WP_Query ($args);\n\n// 3. we display the number of messages and the authors!\n // The Loop \nif ($the_query-> have_posts ()) {\n echo count_user_posts (2, $args); \necho 'recipes for'; \necho get_the_author (2, $args); \necho '
'; \necho count_user_posts (1, $args); \necho 'recipes for';\n echo get_the_author (1, $args);\n\n// 3. We launch the loop to display the articles and the authors! \n// The Loop \necho '
    '; \nwhile ($the_query-> have_posts ()) ​{ \n$the_query-> the_post (); \necho '
  • '. get_the_title (). '
  • '; \necho '
  • '. get_the_author (). '
  • ';\n​}\n​echo '
      ';\n​}\n​else { \n// no posts found }\n/ * Restore original Post Data * / \nwp_reset_postdata ();\n​?>\n\n```\n\n[![enter image description here](https://i.stack.imgur.com/x40WN.jpg)](https://i.stack.imgur.com/x40WN.jpg)"},"output":{"kind":"string","value":"If you have access to user IDs, you can use the [count\\_user\\_posts()](https://developer.wordpress.org/reference/functions/count_user_posts/) function.\n\nYou would get the number of posts by a user like this:\n\n```\n//Assume the variable $thisUser is equal to a valid user ID\n$ThisUserCount = count_user_posts($thisUser, 'recipe');\n\n```\n\nEDIT:\nWhere you're calling the count\\_user\\_posts() function, you're passing it the array $args instead of the post type, 'recipe'.\n\n```\n 'recipe',\n 'posts_per_page' => '16',\n);\n\n// 2. We run the WP Query\n// The Query\n$the_query = new WP_Query ($args);\n\n// 3. we display the number of messages and the authors!\n// The Loop\nif ($the_query-> have_posts()) {\n //Set arguments to grab all authors with published recipes, and order them by user ID\n $authorArgs = array(\n 'orderby' => 'ID',\n 'has_published_posts' => array('recipe'),\n );\n\n //Create an array of all authors with recipes published\n $recipeAuthors = get_users($authorArgs);\n\n //Loop through each recipe author\n foreach($recipeAuthors as $user){\n //Output user post count for recipes\n echo count_user_posts($user->ID, 'recipe');\n echo ' recipes for ';\n\n //Output user's display name\n echo $user->display_name;\n echo '
      ';\n }\n\n // 3. We launch the loop to display the articles and the authors!\n // The Loop\n echo '
        ';\n while ($the_query-> have_posts()) {\n $the_query-> the_post();\n echo '
      • '. get_the_title(). '
      • ';\n echo '
      • '. get_the_author(). '
      • ';\n }\n echo '
      ';\n} else {\n // no posts found\n}\nwp_reset_postdata ();​?>\n\n```\n\nAlso, your get\\_the\\_author(2,$args) function calls are not correct. get\\_the\\_author() does not accept any parameters anymore, and it only returns the Display Name of the author of the current post in the Loop."}}},{"rowIdx":7657440,"cells":{"qid":{"kind":"number","value":396277,"string":"396,277"},"question":{"kind":"string","value":"

      I am trying to use a tax query in my pre_get_posts function. All is working but not when the array has multiple IDs. Let's say my URL looks like: ?listing_cat[]=1&listing_cat[]=2

      \n

      Now I am trying to filter out posts that are in those 2 categories. But my filter only gets the posts from the first category ID. I guess I will need a foreach function, but I am not sure how to implement this. Currently I have the code below. Now I know I can use filter by multiple terms with a comma, like : 'terms' => array($rt_cat_id[0], $rt_cat_id[1]), but I just need it to automatically get all the terms from the array $rt_cat_id and use those to filter the posts. How to accomplish that? Thanks

      \n
      add_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\n            $tax_query[] = array(\n                'taxonomy'  => 'listing_category',\n                'field'     => 'id',\n                'terms'     => array($rt_cat_id[0]),\n           );\n        }       \n\n\n}\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":396314,"author":"Den Isahac","author_id":113233,"author_profile":"https://wordpress.stackexchange.com/users/113233","pm_score":2,"selected":true,"text":"

      Just use:

      \n

      'terms' => $rt_cat_id

      \n

      I'll work for both array and single-based values.

      \n

      Or you can simplify your code as follows:

      \n
      if( isset( $_GET[ 'listing_cat' ] ) ) {\n   $tax_query[] = array(\n      'taxonomy' => 'listing_category',\n      'field' => 'id',\n      'terms' => $_GET[ 'listing_cat' ]\n   );\n}\n
      \n"},{"answer_id":396316,"author":"RobbTe","author_id":124244,"author_profile":"https://wordpress.stackexchange.com/users/124244","pm_score":0,"selected":false,"text":"

      So, the working code can be found below:

      \n
      add_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\n            $tax_query[] = array(\n            'relation' => 'OR',\n            array(\n            'taxonomy' => 'listing_category',\n            'field' => 'id',\n            'terms' => $rt_cat_id,\n            ),\n        );\n        }       \n\n\n}\n
      \n"}],"string":"[\n {\n \"answer_id\": 396314,\n \"author\": \"Den Isahac\",\n \"author_id\": 113233,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/113233\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

      Just use:

      \\n

      'terms' => $rt_cat_id

      \\n

      I'll work for both array and single-based values.

      \\n

      Or you can simplify your code as follows:

      \\n
      if( isset( $_GET[ 'listing_cat' ] ) ) {\\n   $tax_query[] = array(\\n      'taxonomy' => 'listing_category',\\n      'field' => 'id',\\n      'terms' => $_GET[ 'listing_cat' ]\\n   );\\n}\\n
      \\n\"\n },\n {\n \"answer_id\": 396316,\n \"author\": \"RobbTe\",\n \"author_id\": 124244,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/124244\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      So, the working code can be found below:

      \\n
      add_action( 'pre_get_posts', 'rt_tax_archive' );\\nfunction rt_tax_archive($query) {\\n$rt_cat_id = $_GET['listing_cat'];\\n\\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\\n            $tax_query[] = array(\\n            'relation' => 'OR',\\n            array(\\n            'taxonomy' => 'listing_category',\\n            'field' => 'id',\\n            'terms' => $rt_cat_id,\\n            ),\\n        );\\n        }       \\n\\n\\n}\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/29"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396277","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/124244/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396277\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/124244/\"\n]"},"input":{"kind":"string","value":"I am trying to use a tax query in my `pre_get_posts` function. All is working but not when the array has multiple IDs. Let's say my URL looks like: ?listing\\_cat[]=1&listing\\_cat[]=2\n\nNow I am trying to filter out posts that are in those 2 categories. But my filter only gets the posts from the first category ID. I guess I will need a foreach function, but I am not sure how to implement this. Currently I have the code below. Now I know I can use filter by multiple terms with a comma, like : `'terms' => array($rt_cat_id[0], $rt_cat_id[1])`, but I just need it to automatically get all the terms from the array `$rt_cat_id` and use those to filter the posts. How to accomplish that? Thanks\n\n```\nadd_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\n $tax_query[] = array(\n 'taxonomy' => 'listing_category',\n 'field' => 'id',\n 'terms' => array($rt_cat_id[0]),\n );\n } \n\n}\n\n```"},"output":{"kind":"string","value":"Just use:\n\n`'terms' => $rt_cat_id`\n\nI'll work for both array and single-based values.\n\nOr you can simplify your code as follows:\n\n```php\nif( isset( $_GET[ 'listing_cat' ] ) ) {\n $tax_query[] = array(\n 'taxonomy' => 'listing_category',\n 'field' => 'id',\n 'terms' => $_GET[ 'listing_cat' ]\n );\n}\n\n```"}}},{"rowIdx":7657441,"cells":{"qid":{"kind":"number","value":396282,"string":"396,282"},"question":{"kind":"string","value":"

      My website has a few .PNG images animated at the very start of my Contact page.\nThose images are a bit heavy (because they have transparent background), so the animation starts with some of them loading during the animation, looking pretty bad.

      \n

      So, to fix it, I must add this line <link rel="preload" as="image" href="url-of-the-image.png"/> to the <head>.

      \n

      To achieve it, I'm using Snippets plugin. If I'm not mistaken, the snippet should like this:

      \n
      add_action( 'wp_head', function () { ?>\n\nfunction my_custom_js() {\n    echo '<link rel="preload" as="image" href=href="url-of-the-image.png"/>';\n}\n\n<?php } );\n
      \n

      The thing is that the very same page (my Contact page) is different for mobile devices: it doesn't use those .PNG images because it would be too much loading time for a phone.

      \n

      This leads to my question: Is there a way to exclude mobile devices from the preloading tag I must add to the head?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396314,"author":"Den Isahac","author_id":113233,"author_profile":"https://wordpress.stackexchange.com/users/113233","pm_score":2,"selected":true,"text":"

      Just use:

      \n

      'terms' => $rt_cat_id

      \n

      I'll work for both array and single-based values.

      \n

      Or you can simplify your code as follows:

      \n
      if( isset( $_GET[ 'listing_cat' ] ) ) {\n   $tax_query[] = array(\n      'taxonomy' => 'listing_category',\n      'field' => 'id',\n      'terms' => $_GET[ 'listing_cat' ]\n   );\n}\n
      \n"},{"answer_id":396316,"author":"RobbTe","author_id":124244,"author_profile":"https://wordpress.stackexchange.com/users/124244","pm_score":0,"selected":false,"text":"

      So, the working code can be found below:

      \n
      add_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\n            $tax_query[] = array(\n            'relation' => 'OR',\n            array(\n            'taxonomy' => 'listing_category',\n            'field' => 'id',\n            'terms' => $rt_cat_id,\n            ),\n        );\n        }       \n\n\n}\n
      \n"}],"string":"[\n {\n \"answer_id\": 396314,\n \"author\": \"Den Isahac\",\n \"author_id\": 113233,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/113233\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

      Just use:

      \\n

      'terms' => $rt_cat_id

      \\n

      I'll work for both array and single-based values.

      \\n

      Or you can simplify your code as follows:

      \\n
      if( isset( $_GET[ 'listing_cat' ] ) ) {\\n   $tax_query[] = array(\\n      'taxonomy' => 'listing_category',\\n      'field' => 'id',\\n      'terms' => $_GET[ 'listing_cat' ]\\n   );\\n}\\n
      \\n\"\n },\n {\n \"answer_id\": 396316,\n \"author\": \"RobbTe\",\n \"author_id\": 124244,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/124244\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      So, the working code can be found below:

      \\n
      add_action( 'pre_get_posts', 'rt_tax_archive' );\\nfunction rt_tax_archive($query) {\\n$rt_cat_id = $_GET['listing_cat'];\\n\\nif( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {\\n            $tax_query[] = array(\\n            'relation' => 'OR',\\n            array(\\n            'taxonomy' => 'listing_category',\\n            'field' => 'id',\\n            'terms' => $rt_cat_id,\\n            ),\\n        );\\n        }       \\n\\n\\n}\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/29"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396282","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/203472/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396282\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/203472/\"\n]"},"input":{"kind":"string","value":"My website has a few .PNG images animated at the very start of my Contact page.\nThose images are a bit heavy (because they have transparent background), so the animation starts with some of them loading during the animation, looking pretty bad.\n\nSo, to fix it, I must add this line `` to the ``.\n\nTo achieve it, I'm using **Snippets plugin**. If I'm not mistaken, the snippet should like this:\n\n```\nadd_action( 'wp_head', function () { ?>\n\nfunction my_custom_js() {\n echo '';\n}\n\n $rt_cat_id`\n\nI'll work for both array and single-based values.\n\nOr you can simplify your code as follows:\n\n```php\nif( isset( $_GET[ 'listing_cat' ] ) ) {\n $tax_query[] = array(\n 'taxonomy' => 'listing_category',\n 'field' => 'id',\n 'terms' => $_GET[ 'listing_cat' ]\n );\n}\n\n```"}}},{"rowIdx":7657442,"cells":{"qid":{"kind":"number","value":396286,"string":"396,286"},"question":{"kind":"string","value":"

      Is it possible to show ONLY the first 300 words (or even 50 lines) of every blog post for anonymous users? Instead of show the whole article on the page? And after registration all the post would show.

      \n

      Thanks!!!

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396293,"author":"Pixelsmith","author_id":66368,"author_profile":"https://wordpress.stackexchange.com/users/66368","pm_score":1,"selected":false,"text":"

      It wasn't quite as easy as @Pat J made it sound, especially if you want HTML formatting with your copy. I cribbed from this answer and came up with the following code for you. I've tested it and it works:

      \n
          // If the user is logged in, display the full content\n    if(is_user_logged_in()):\n        the_content();\n    else: // The user isn't logged in and should only see the first 300 words\n        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n    endif;\n
      \n

      UPDATE

      \n

      There are 2 errors in your code. One is the ; after the initial if statement, and the arrays don't match: $roles v $role.

      \n

      The following code integrates the original answer (logged in/out) with your modifications (if is array):

      \n
          if(is_user_logged_in()): \n        if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): \n            the_content();\n        else: \n            echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n        endif; \n     else:\n        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) );\n     endif;\n
      \n

      Good luck!

      \n"},{"answer_id":396509,"author":"Alexandro Giles","author_id":206371,"author_profile":"https://wordpress.stackexchange.com/users/206371","pm_score":0,"selected":false,"text":"

      You can use the excerpt to accomplish this, nonetheless the excerpt by default filter all HTML tags. To fix this, we need to filter and add new logic to it.

      \n

      This will work filteryng the excerpt to change according to your needs:

      \n

      You have to add this function in your theme's functions.php

      \n

      functions.php

      \n
      function wpse_allowedtags() {\n    //The Tags you put here will not be removed, therefore if you want to include strong HTML tag, you should add it here as shown:\n        return '<strong>'; \n    }\n\nif ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) : \n\n    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {\n    $raw_excerpt = $wpse_excerpt;\n        if ( '' == $wpse_excerpt ) {\n\n            $wpse_excerpt = get_the_content('');\n            $wpse_excerpt = strip_shortcodes( $wpse_excerpt );\n            $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);\n            $wpse_excerpt = str_replace(']]>', ']]>', $wpse_excerpt);\n            $wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */\n\n            /*Set the excerpt word count and only break after sentence is complete.\n            You can set this to any number you want in this case we'll use 300 \n            words. */\n                $excerpt_word_count = 300;\n                $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); \n                $tokens = array();\n                $excerptOutput = '';\n                $count = 0;\n\n                // Divide the string into tokens; HTML tags, or words, followed by any whitespace in order to clean the not allowed HTML tags.\n                preg_match_all('/(<[^>]+>|[^<>\\s]+)\\s*/u', $wpse_excerpt, $tokens);\n\n                foreach ($tokens[0] as $token) { \n\n                    if ($count >= $excerpt_length && preg_match('/[\\,\\;\\?\\.\\!]\\s*$/uS', $token)) { \n                    // Limit reached, continue until , ; ? . or ! occur at the end\n                        $excerptOutput .= trim($token);\n                        break;\n                    }\n\n                    // Add words to complete sentence\n                    $count++;\n\n                    // Append what's left of the token\n                    $excerptOutput .= $token;\n                }\n\n            $wpse_excerpt = trim(force_balance_tags($excerptOutput));\n\n            if ( $count <  0) {   \n                $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . ' » ' . sprintf(__( 'Reed more: %s  »', 'wpse' ), get_the_title()) . '</a>'; \n               $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); \n               $wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */\n           }  \n           $wpse_excerpt .= ' [...]';\n\n            return $wpse_excerpt;   \n\n        }\n        return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);\n    }\n\nendif; \n\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt'); \n
      \n

      After that, you only need to call the_excerpt to non registered users in the desired template file of your theme:\n(remember that it has been previously filtered to include 300 words)

      \n
       // The user is logged in, display the full content\n    if(is_user_logged_in()){\n       the_content();\n     }else{\n        // show the_excerpt\n        <?php echo get_the_excerpt() ?>\n     }\n        \n
      \n"}],"string":"[\n {\n \"answer_id\": 396293,\n \"author\": \"Pixelsmith\",\n \"author_id\": 66368,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/66368\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      It wasn't quite as easy as @Pat J made it sound, especially if you want HTML formatting with your copy. I cribbed from this answer and came up with the following code for you. I've tested it and it works:

      \\n
          // If the user is logged in, display the full content\\n    if(is_user_logged_in()):\\n        the_content();\\n    else: // The user isn't logged in and should only see the first 300 words\\n        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\\n    endif;\\n
      \\n

      UPDATE

      \\n

      There are 2 errors in your code. One is the ; after the initial if statement, and the arrays don't match: $roles v $role.

      \\n

      The following code integrates the original answer (logged in/out) with your modifications (if is array):

      \\n
          if(is_user_logged_in()): \\n        if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): \\n            the_content();\\n        else: \\n            echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\\n        endif; \\n     else:\\n        echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) );\\n     endif;\\n
      \\n

      Good luck!

      \\n\"\n },\n {\n \"answer_id\": 396509,\n \"author\": \"Alexandro Giles\",\n \"author_id\": 206371,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206371\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      You can use the excerpt to accomplish this, nonetheless the excerpt by default filter all HTML tags. To fix this, we need to filter and add new logic to it.

      \\n

      This will work filteryng the excerpt to change according to your needs:

      \\n

      You have to add this function in your theme's functions.php

      \\n

      functions.php

      \\n
      function wpse_allowedtags() {\\n    //The Tags you put here will not be removed, therefore if you want to include strong HTML tag, you should add it here as shown:\\n        return '<strong>'; \\n    }\\n\\nif ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) : \\n\\n    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {\\n    $raw_excerpt = $wpse_excerpt;\\n        if ( '' == $wpse_excerpt ) {\\n\\n            $wpse_excerpt = get_the_content('');\\n            $wpse_excerpt = strip_shortcodes( $wpse_excerpt );\\n            $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);\\n            $wpse_excerpt = str_replace(']]>', ']]>', $wpse_excerpt);\\n            $wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */\\n\\n            /*Set the excerpt word count and only break after sentence is complete.\\n            You can set this to any number you want in this case we'll use 300 \\n            words. */\\n                $excerpt_word_count = 300;\\n                $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); \\n                $tokens = array();\\n                $excerptOutput = '';\\n                $count = 0;\\n\\n                // Divide the string into tokens; HTML tags, or words, followed by any whitespace in order to clean the not allowed HTML tags.\\n                preg_match_all('/(<[^>]+>|[^<>\\\\s]+)\\\\s*/u', $wpse_excerpt, $tokens);\\n\\n                foreach ($tokens[0] as $token) { \\n\\n                    if ($count >= $excerpt_length && preg_match('/[\\\\,\\\\;\\\\?\\\\.\\\\!]\\\\s*$/uS', $token)) { \\n                    // Limit reached, continue until , ; ? . or ! occur at the end\\n                        $excerptOutput .= trim($token);\\n                        break;\\n                    }\\n\\n                    // Add words to complete sentence\\n                    $count++;\\n\\n                    // Append what's left of the token\\n                    $excerptOutput .= $token;\\n                }\\n\\n            $wpse_excerpt = trim(force_balance_tags($excerptOutput));\\n\\n            if ( $count <  0) {   \\n                $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . ' » ' . sprintf(__( 'Reed more: %s  »', 'wpse' ), get_the_title()) . '</a>'; \\n               $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); \\n               $wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */\\n           }  \\n           $wpse_excerpt .= ' [...]';\\n\\n            return $wpse_excerpt;   \\n\\n        }\\n        return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);\\n    }\\n\\nendif; \\n\\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\\nadd_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt'); \\n
      \\n

      After that, you only need to call the_excerpt to non registered users in the desired template file of your theme:\\n(remember that it has been previously filtered to include 300 words)

      \\n
       // The user is logged in, display the full content\\n    if(is_user_logged_in()){\\n       the_content();\\n     }else{\\n        // show the_excerpt\\n        <?php echo get_the_excerpt() ?>\\n     }\\n        \\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/29"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396286","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213060/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396286\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213060/\"\n]"},"input":{"kind":"string","value":"Is it possible to show ONLY the first 300 words (or even 50 lines) of every blog post for anonymous users? Instead of show the whole article on the page? And after registration all the post would show.\n\nThanks!!!"},"output":{"kind":"string","value":"It wasn't quite as easy as @Pat J made it sound, especially if you want `HTML` formatting with your copy. I cribbed from [this answer](https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words) and came up with the following code for you. I've tested it and it works:\n\n```\n // If the user is logged in, display the full content\n if(is_user_logged_in()):\n the_content();\n else: // The user isn't logged in and should only see the first 300 words\n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n endif;\n\n```\n\n**UPDATE**\n\nThere are 2 errors in your code. One is the `;` after the initial `if` statement, and the `arrays` don't match: `$roles` v `$role`.\n\nThe following code integrates the original answer (logged in/out) with your modifications (if is array):\n\n```\n if(is_user_logged_in()): \n if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): \n the_content();\n else: \n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n endif; \n else:\n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) );\n endif;\n\n```\n\nGood luck!"}}},{"rowIdx":7657443,"cells":{"qid":{"kind":"number","value":396304,"string":"396,304"},"question":{"kind":"string","value":"

      At the moment I'm using Postman to hit the endpoints and I have a successful Basic Authentication but so far I'm unable to get all the registered users.\nMy request:

      \n
      https://example.com/wp-json/wp/v2/users\n
      \n

      returns only users that have posts even though I have inserted:

      \n
      add_filter( 'rest_user_query' , 'custom_rest_user_query' );\nfunction custom_rest_user_query( $prepared_args, $request = null ) {\n  unset($prepared_args['has_published_posts']);\n\n  return $prepared_args;\n}\n
      \n

      in my functions file.\nI have also tried applying a filter:

      \n
      https://example.com/wp-json/wp/v2/users?filter[per_page]=0\n
      \n

      But I still get the same result: Only users with posts.\nI have been banging my head on for days now...

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396306,"author":"billybadass","author_id":194672,"author_profile":"https://wordpress.stackexchange.com/users/194672","pm_score":0,"selected":false,"text":"

      WP has nice build in tools to work with db, my suggestion would be to register your endpoint and use for a callback function something like this:

      \n
      function getAllUsers(){\n    global $wpdb;\n    $query = $wpdb->get_results( " SELECT `ID` FROM `wp_users` " , OBJECT);\n    $ids = array();\n    foreach($query as $id){\n        array_push($ids, $id->ID);\n    }\n    return $ids;    \n}\n
      \n

      It will return all the ID's. Then you can use get_post_meta to gather meta info about the user. Of course consider protecting your endpoint since it hands over user information.

      \n"},{"answer_id":396317,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":2,"selected":true,"text":"

      The problem may be pagination

      \n

      The API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100.

      \n

      So your missing users may be on page 2 or 3 etc

      \n

      I strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination:

      \n

      https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/

      \n"}],"string":"[\n {\n \"answer_id\": 396306,\n \"author\": \"billybadass\",\n \"author_id\": 194672,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/194672\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      WP has nice build in tools to work with db, my suggestion would be to register your endpoint and use for a callback function something like this:

      \\n
      function getAllUsers(){\\n    global $wpdb;\\n    $query = $wpdb->get_results( " SELECT `ID` FROM `wp_users` " , OBJECT);\\n    $ids = array();\\n    foreach($query as $id){\\n        array_push($ids, $id->ID);\\n    }\\n    return $ids;    \\n}\\n
      \\n

      It will return all the ID's. Then you can use get_post_meta to gather meta info about the user. Of course consider protecting your endpoint since it hands over user information.

      \\n\"\n },\n {\n \"answer_id\": 396317,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

      The problem may be pagination

      \\n

      The API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100.

      \\n

      So your missing users may be on page 2 or 3 etc

      \\n

      I strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination:

      \\n

      https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/30"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396304","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213074/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396304\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213074/\"\n]"},"input":{"kind":"string","value":"At the moment I'm using Postman to hit the endpoints and I have a successful Basic Authentication but so far I'm unable to get all the registered users.\nMy request:\n\n```\nhttps://example.com/wp-json/wp/v2/users\n\n```\n\nreturns only users that have posts even though I have inserted:\n\n```\nadd_filter( 'rest_user_query' , 'custom_rest_user_query' );\nfunction custom_rest_user_query( $prepared_args, $request = null ) {\n unset($prepared_args['has_published_posts']);\n\n return $prepared_args;\n}\n\n```\n\nin my functions file.\nI have also tried applying a filter:\n\n```\nhttps://example.com/wp-json/wp/v2/users?filter[per_page]=0\n\n```\n\nBut I still get the same result: Only users with posts.\nI have been banging my head on for days now..."},"output":{"kind":"string","value":"**The problem may be pagination**\n\nThe API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100.\n\nSo your missing users may be on page 2 or 3 etc\n\nI strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination:\n\n"}}},{"rowIdx":7657444,"cells":{"qid":{"kind":"number","value":396325,"string":"396,325"},"question":{"kind":"string","value":"

      I tried hooking the upload_mimes hook in order to add support for ttf files to be uploaded, however this didn't immediately work (.ttf files were still blocked).

      \n

      The reason isn't entirely clear to me but I assume Wordpress's calculated MIME type for the file I'm trying to upload and the MIME type I'm adding to the upload_files hook don't match.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/30"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396325","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/176814/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396325\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/176814/\"\n]"},"input":{"kind":"string","value":"I tried hooking the `upload_mimes` hook in order to add support for ttf files to be uploaded, however this didn't immediately work (.ttf files were still blocked).\n\nThe reason isn't entirely clear to me but I assume Wordpress's calculated MIME type for the file I'm trying to upload and the MIME type I'm adding to the `upload_files` hook don't match."},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657445,"cells":{"qid":{"kind":"number","value":396337,"string":"396,337"},"question":{"kind":"string","value":"

      How do I allow a specific user or a specific role to view drafts and previews, but not allow them to edit posts or have any other admin capabilities? I can add a custom capability to a role, but don't know the logic for allowing them to view drafts and previews. Any thoughts?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/09/30"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396337","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/42925/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396337\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/42925/\"\n]"},"input":{"kind":"string","value":"How do I allow a specific user or a specific role to view drafts and previews, but not allow them to edit posts or have any other admin capabilities? I can add a custom capability to a role, but don't know the logic for allowing them to view drafts and previews. Any thoughts?"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657446,"cells":{"qid":{"kind":"number","value":396397,"string":"396,397"},"question":{"kind":"string","value":"

      Very new to PHP and I'm trying to do the following through a snippets plugin but keep getting critical errors:

      \n
        \n
      • Restrict all non-logged in users to home, about and pricing pages. If attempting to access other pages, redirect to "no-permission" message page.
      • \n
      • If user is logged in, allow them to only view posts on the front end if they are the post author. If attempted, redirect to "no-permission" page.
      • \n
      • Admin has full read access on front end.
      • \n
      \n

      I've tried with plugins but nothing quite gives me what I want,

      \n

      Any help is much appreciated, code below:

      \n
      add_action( 'template_redirect', 'redirect_non_permitted_users' );\n\nfunction redirect_non_permitted_users () {\n     $userID = get_user_id();\n     $authorID = get_the_author_meta(ID);\n\n    if(current_user_can('manage_options')){\n \n    }\n\n    elseif( $userID <> $authorID || ! is_user_logged_in() || ! is_front_page() || ! is_page('about') || ! is_page('pricing')){\n        wp_redirect('https://www.example.com/no-permission/'); \n    exit;\n    }   \n}\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/02"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396397","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213142/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396397\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213142/\"\n]"},"input":{"kind":"string","value":"Very new to PHP and I'm trying to do the following through a snippets plugin but keep getting critical errors:\n\n* Restrict all non-logged in users to home, about and pricing pages. If attempting to access other pages, redirect to \"no-permission\" message page.\n* If user is logged in, allow them to only view posts on the front end if they are the post author. If attempted, redirect to \"no-permission\" page.\n* Admin has full read access on front end.\n\nI've tried with plugins but nothing quite gives me what I want,\n\nAny help is much appreciated, code below:\n\n```\nadd_action( 'template_redirect', 'redirect_non_permitted_users' );\n\nfunction redirect_non_permitted_users () {\n $userID = get_user_id();\n $authorID = get_the_author_meta(ID);\n\n if(current_user_can('manage_options')){\n\n }\n\n elseif( $userID <> $authorID || ! is_user_logged_in() || ! is_front_page() || ! is_page('about') || ! is_page('pricing')){\n wp_redirect('https://www.example.com/no-permission/'); \n exit;\n } \n}\n\n```"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657447,"cells":{"qid":{"kind":"number","value":396411,"string":"396,411"},"question":{"kind":"string","value":"

      I am currently using the wp-members wordpress plugin. I just learned that they have no functionality to redirect the user to the last page viewed after login or registration .. which has a solution thank you

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/02"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396411","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212622/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396411\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212622/\"\n]"},"input":{"kind":"string","value":"I am currently using the wp-members wordpress plugin. I just learned that they have no functionality to redirect the user to the last page viewed after login or registration .. which has a solution thank you"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657448,"cells":{"qid":{"kind":"number","value":396416,"string":"396,416"},"question":{"kind":"string","value":"

      I have a website with several custom fields, however when using the following code to search for a post, it only searches for the title or for the content, excluding the custom fields associated with the post or entry.

      \n
      &lt;form method=&quot;get&quot; id=&quot;searchform&quot; action=&quot;&lt;?php bloginfo('url'); ?&gt;/&quot;&gt;\n  &lt;input type=&quot;text&quot; value=&quot;&lt;?php the_search_query(); ?&gt;&quot; name=&quot;s&quot; id=&quot;s&quot; placeholder=&quot;&lt;?php esc_attr_e( 'Buscar por título, actor, año...', 'twentyeleven' ); ?&gt;&quot; /&gt;\n  &lt;input type=&quot;submit&quot; class=&quot;submit&quot; name=&quot;submit&quot; id=&quot;boton&quot; value=&quot;&quot; /&gt;\n&lt;/form&gt;\n
      \n

      any way to include custom fields in the search?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396416","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/162329/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396416\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/162329/\"\n]"},"input":{"kind":"string","value":"I have a website with several custom fields, however when using the following code to search for a post, it only searches for the title or for the content, excluding the custom fields associated with the post or entry.\n\n```\n/\">\n \" name=\"s\" id=\"s\" placeholder=\"\" />\n \n\n\n```\n\nany way to include custom fields in the search?"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657449,"cells":{"qid":{"kind":"number","value":396485,"string":"396,485"},"question":{"kind":"string","value":"

      I am writing a custom (bespoke, for 1 client, not for publication and general consumption) plugin, that needs to access custom tables.

      \n

      In general with WP,I follow the principle of using the higher level APIs where possible, so rarely have to work with \\wpdb.\nNow that i do have a need, i am discovering how archaic it is!

      \n

      Looking through the source code, it seems I can be sure that it is using mysqli (since the plugin requires php 7.1, and we also control the server) so I thought why not use that for my custom tables logic?

      \n

      I wrote a tiny wrapper:

      \n
      &lt;?php\n\nnamespace PluginNamespaceHere\\DB;\n\nuse mysqli;\nuse wpdb;\n\n/**\n * A small wrapper class that contains, and provides direct access to, the $wpdb object,\n * as well as the underlying MYSQLI object, so we can do real prepared statements etc\n */\nclass DB\n{\n\n    /** @var wpdb */\n    public $wpdb;\n\n    /** @var mysqli */\n    public $mysqli;\n\n    /**\n     * @param wpdb $wpdb\n     */\n    public function __construct(wpdb $wpdb)\n    {\n        $this-&gt;wpdb = $wpdb;\n        //$wpdb is protected, but accessible via magic __get() wp-db.php line: 643\n        $this-&gt;mysqli = $wpdb-&gt;dbh;\n    }\n\n\n    /**\n     * Run an SQL query. If $params are provided, prepared statements are used. If $bind_types are provided, they will be\n     * used in the prepared statement, if not, all params will be treated as strings\n     *\n     * @param string $sql The SQL string, unprefixed table names should be wrapped in curly braces eg SELECT * FROM {posts}\n     * @param array $params Optional parameters for prepared statements\n     * @param string $bind_types Optional bind types for prepared statements, defaults to string\n     * @retun bool|mysqli_result\n     */\n    public function run($sql, $params=[], $bind_types='')\n    {\n        $sql = $this-&gt;prefixTableNamesInSqlString($sql);\n\n        if(!is_array($params) || empty($params)){\n            return $this-&gt;mysqli-&gt;query($sql);\n        }\n        if($bind_types == ''){\n            $bind_types = str_repeat(&quot;s&quot;, count($params));\n        }\n        $stmt = $this-&gt;mysqli-&gt;prepare($sql);\n        $stmt-&gt;bind_param($bind_types, ...$params);\n        $stmt-&gt;execute();\n        return $stmt-&gt;get_result();\n    }\n\n    /**\n     * Replaces curly brace table names with their actual, prefixed name\n     * Eg &quot;SELECT * from {table_name}&quot; =&gt; &quot;SELECT * from wp_table_name&quot;\n     * @param string $sql\n     * @return string\n     */\n    private function prefixTableNamesInSqlString($sql)\n    {\n        return str_replace([&quot;{&quot;, &quot;}&quot;], [$this-&gt;wpdb-&gt;prefix, &quot;&quot;], $sql);\n    }\n\n}\n
      \n

      This would allow me to use real prepared queries, and have nice readable code like:

      \n
      &lt;?php\n$sql = &quot;\n            SELECT DISTINCT c.ID AS course_id, c.post_title AS course_title\n            FROM {posts} c\n            JOIN {tmsc_course_product} cp\n            ON c.id = cp.course_id\n            WHERE cp.product_id IN(?,?)\n        &quot;;\n//Yes, i know DB::run() can return bool! Out of scope for this question\n$courses = $db-&gt;run($sql, [57,4761])-&gt;fetch_all(MYSQLI_ASSOC);\n\n
      \n

      My only concern is if this is going to have any knock on effects with wpdb and its dependents.\nThe wpdb class is not exactly easy to read, and appears holds a lot of state.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/05"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396485","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/120700/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396485\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/120700/\"\n]"},"input":{"kind":"string","value":"I am writing a custom (bespoke, for 1 client, not for publication and general consumption) plugin, that needs to access custom tables.\n\nIn general with WP,I follow the principle of using the higher level APIs where possible, so rarely have to work with \\wpdb.\nNow that i do have a need, i am discovering how archaic it is!\n\nLooking through the source code, it seems I can be sure that it is using mysqli (since the plugin requires php 7.1, and we also control the server) so I thought why not use that for my custom tables logic?\n\nI wrote a tiny wrapper:\n\n```\nwpdb = $wpdb;\n //$wpdb is protected, but accessible via magic __get() wp-db.php line: 643\n $this->mysqli = $wpdb->dbh;\n }\n\n /**\n * Run an SQL query. If $params are provided, prepared statements are used. If $bind_types are provided, they will be\n * used in the prepared statement, if not, all params will be treated as strings\n *\n * @param string $sql The SQL string, unprefixed table names should be wrapped in curly braces eg SELECT * FROM {posts}\n * @param array $params Optional parameters for prepared statements\n * @param string $bind_types Optional bind types for prepared statements, defaults to string\n * @retun bool|mysqli_result\n */\n public function run($sql, $params=[], $bind_types='')\n {\n $sql = $this->prefixTableNamesInSqlString($sql);\n\n if(!is_array($params) || empty($params)){\n return $this->mysqli->query($sql);\n }\n if($bind_types == ''){\n $bind_types = str_repeat(\"s\", count($params));\n }\n $stmt = $this->mysqli->prepare($sql);\n $stmt->bind_param($bind_types, ...$params);\n $stmt->execute();\n return $stmt->get_result();\n }\n\n /**\n * Replaces curly brace table names with their actual, prefixed name\n * Eg \"SELECT * from {table_name}\" => \"SELECT * from wp_table_name\"\n * @param string $sql\n * @return string\n */\n private function prefixTableNamesInSqlString($sql)\n {\n return str_replace([\"{\", \"}\"], [$this->wpdb->prefix, \"\"], $sql);\n }\n\n}\n\n```\n\nThis would allow me to use real prepared queries, and have nice readable code like:\n\n```\nrun($sql, [57,4761])->fetch_all(MYSQLI_ASSOC);\n\n```\n\nMy only concern is if this is going to have any knock on effects with wpdb and its dependents.\nThe wpdb class is not exactly easy to read, and appears holds a lot of state."},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657450,"cells":{"qid":{"kind":"number","value":396517,"string":"396,517"},"question":{"kind":"string","value":"

      I am following the official WordPress &quot;Create a Block Tutorial&quot; located here: https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/

      \n

      I used this as a starting point for the plugin: npx @wordpress/create-block

      \n

      I am using it in conjunction with Local by Flywheel for my dev environment. Mostly everything seems to be working except when I try to include other files in the block's CSS like a custom font file or an image. This is part of the tutorial: https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/block-code/

      \n

      Example:

      \n
      @font-face {\n    font-family: Gilbert;\n    src: url(./Gilbert-color.otf);\n    font-weight: bold;\n}\n.wp-block-create-block-tdblocks {\n    font-family: Gilbert;\n    font-size: 64px;\n    font-weight: bold;\n    background-image: url(./map_bg.png);\n    background-repeat: repeat;\n}\n
      \n

      So after I insert the recommended code and run npm run build, the css file generated by the build process leaves the links to these files relative to the current web page's URL and not a link to its file location in the proper plugin folder.

      \n

      Here is what it gives me for the image file for instance (which shows as a 404 error naturally):

      \n
      https://taylor-design-starter-theme.local/sample-page/images/map_bg.f0104819.png\n
      \n

      I'd expect it to give me this:

      \n
      https://taylor-design-starter-theme.local/wp-content/plugins/tdblocks/build/images/map_bg.f0104819.png\n
      \n

      I have tried adjusting the &quot;url&quot; value in the scss file to see if that would help. Like src: url(../map_bg.png); or src: url(map_bg.png); and that didn't seem to do anything.

      \n

      Am I missing something? Or is there a way to get it to use the plugin directory?

      \n

      Thank you.

      \n

      EDIT: Here is the CSS generated by the build process when I run npm run build

      \n
      @font-face{font-family:Gilbert;font-weight:700;src:url(fonts/Gilbert-color.02d3d364.otf)}.wp-block-create-block-tdblocks{background-image:url(images/map_bg.f0104819.png);background-repeat:repeat;font-family:sans-serif;font-size:64px;font-weight:700}\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/05"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396517","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213256/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396517\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213256/\"\n]"},"input":{"kind":"string","value":"I am following the official WordPress \"Create a Block Tutorial\" located here: \n\nI used this as a starting point for the plugin: `npx @wordpress/create-block`\n\nI am using it in conjunction with Local by Flywheel for my dev environment. Mostly everything seems to be working except when I try to include other files in the block's CSS like a custom font file or an image. This is part of the tutorial: \n\nExample:\n\n```\n@font-face {\n font-family: Gilbert;\n src: url(./Gilbert-color.otf);\n font-weight: bold;\n}\n.wp-block-create-block-tdblocks {\n font-family: Gilbert;\n font-size: 64px;\n font-weight: bold;\n background-image: url(./map_bg.png);\n background-repeat: repeat;\n}\n\n```\n\nSo after I insert the recommended code and run `npm run build`, the css file generated by the build process leaves the links to these files relative to the current web page's URL and not a link to its file location in the proper plugin folder.\n\nHere is what it gives me for the image file for instance (which shows as a 404 error naturally):\n\n```\nhttps://taylor-design-starter-theme.local/sample-page/images/map_bg.f0104819.png\n\n```\n\nI'd expect it to give me this:\n\n```\nhttps://taylor-design-starter-theme.local/wp-content/plugins/tdblocks/build/images/map_bg.f0104819.png\n\n```\n\nI have tried adjusting the \"url\" value in the scss file to see if that would help. Like `src: url(../map_bg.png);` or `src: url(map_bg.png);` and that didn't seem to do anything.\n\nAm I missing something? Or is there a way to get it to use the plugin directory?\n\nThank you.\n\nEDIT: Here is the CSS generated by the build process when I run `npm run build`\n\n```\n@font-face{font-family:Gilbert;font-weight:700;src:url(fonts/Gilbert-color.02d3d364.otf)}.wp-block-create-block-tdblocks{background-image:url(images/map_bg.f0104819.png);background-repeat:repeat;font-family:sans-serif;font-size:64px;font-weight:700}\n\n```"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657451,"cells":{"qid":{"kind":"number","value":396518,"string":"396,518"},"question":{"kind":"string","value":"

      Is there a way to check which files are part of vanilla Wordpress? I am working on a custom Wordpress project that has a lot of added parts to it and I was wondering if there was an easy way to check which files were added.

      \n

      Inside of root there's a folder website.com, among other things, and inside website.com there's a folder called public, among other things, and then inside folder we have the folders wp-admin, wp-content and wp-includes. So I am wondering if every other folders are not part of the vanilla Wordpress. Also, what folders should vanilla Wordpress have inside wp-admin, wp-content and wp-includes and can other non-Wordpress files use files inside those folders?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396326,"author":"mozboz","author_id":176814,"author_profile":"https://wordpress.stackexchange.com/users/176814","pm_score":3,"selected":true,"text":"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \n

      First massage the way Wordpress detects/reports TTF file types:

      \n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n
      \n

      Then hook upload_mimes for exactly this extension/mime-type:

      \n
      \nfunction allow_custom_mime_types( $mimes ) {\n \n    // New allowed mime types.\n    $mimes['ttf'] = 'font/ttf';     \n\n    return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n
      \n"},{"answer_id":396330,"author":"dig99","author_id":171719,"author_profile":"https://wordpress.stackexchange.com/users/171719","pm_score":1,"selected":false,"text":"

      If you're not in production or i.e. working in development env you can use:

      \n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \n

      in wp-config.php

      \n"}],"string":"[\n {\n \"answer_id\": 396326,\n \"author\": \"mozboz\",\n \"author_id\": 176814,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/176814\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

      This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension and then hooks upload_mimes for exactly our specified MIME type. Part of this answer taken from https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/

      \\n

      First massage the way Wordpress detects/reports TTF file types:

      \\n
      function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\\n\\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\\nreturn $data;\\n}\\n\\n$wp_file_type = wp_check_filetype( $filename, $mimes );\\n\\n// Check for the file type you want to enable, e.g. 'svg'.\\nif ( 'ttf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'ttf';\\n$data['type'] = 'font/ttf';\\n}\\n\\nif ( 'otf' === $wp_file_type['ext'] ) {\\n$data['ext'] = 'otf';\\n$data['type'] = 'font/otf';\\n}\\n\\nreturn $data;\\n}\\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\\n
      \\n

      Then hook upload_mimes for exactly this extension/mime-type:

      \\n
      \\nfunction allow_custom_mime_types( $mimes ) {\\n \\n    // New allowed mime types.\\n    $mimes['ttf'] = 'font/ttf';     \\n\\n    return $mimes;\\n}\\n\\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\\n
      \\n\"\n },\n {\n \"answer_id\": 396330,\n \"author\": \"dig99\",\n \"author_id\": 171719,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/171719\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      If you're not in production or i.e. working in development env you can use:

      \\n

      define('ALLOW_UNFILTERED_UPLOADS', true);

      \\n

      in wp-config.php

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/05"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396518","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212733/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396518\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212733/\"\n]"},"input":{"kind":"string","value":"Is there a way to check which files are part of vanilla Wordpress? I am working on a custom Wordpress project that has a lot of added parts to it and I was wondering if there was an easy way to check which files were added.\n\nInside of root there's a folder website.com, among other things, and inside website.com there's a folder called public, among other things, and then inside folder we have the folders wp-admin, wp-content and wp-includes. So I am wondering if every other folders are not part of the vanilla Wordpress. Also, what folders should vanilla Wordpress have inside wp-admin, wp-content and wp-includes and can other non-Wordpress files use files inside those folders?"},"output":{"kind":"string","value":"This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from \n\nFirst massage the way Wordpress detects/reports TTF file types:\n\n```\nfunction divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n\n```\n\nThen hook `upload_mimes` for exactly this extension/mime-type:\n\n```\n\nfunction allow_custom_mime_types( $mimes ) {\n\n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n\n```"}}},{"rowIdx":7657452,"cells":{"qid":{"kind":"number","value":396540,"string":"396,540"},"question":{"kind":"string","value":"

      On button click, I want user to download a file which is an apk file. On that same click, at the same time, I want to scroll to a div.

      \n

      Is it possible to add two actions in a button?\nNote: I'm using elementor.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396543,"author":"Praveen","author_id":97802,"author_profile":"https://wordpress.stackexchange.com/users/97802","pm_score":0,"selected":false,"text":"

      Try this code

      \n
      $('.download-btn').click(function(){\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n
      \n"},{"answer_id":396574,"author":"Sean Sr","author_id":206158,"author_profile":"https://wordpress.stackexchange.com/users/206158","pm_score":2,"selected":false,"text":"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n  link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n  e.preventDefault();\n  const href = this.getAttribute(&quot;href&quot;);\n  const offsetTop = document.querySelector(href).offsetTop;\n\n  scroll({\n    top: offsetTop,\n    behavior: &quot;smooth&quot;\n  });\n}\n&lt;/script&gt;\n
      \n"}],"string":"[\n {\n \"answer_id\": 396543,\n \"author\": \"Praveen\",\n \"author_id\": 97802,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/97802\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Try this code

      \\n
      $('.download-btn').click(function(){\\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\\n});\\n
      \\n\"\n },\n {\n \"answer_id\": 396574,\n \"author\": \"Sean Sr\",\n \"author_id\": 206158,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206158\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \\n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \\n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\\n\\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\\n\\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\\n\\n&lt;script&gt;\\nconst links = document.querySelectorAll(&quot;a&quot;);\\n\\nfor (const link of links) {\\n  link.addEventListener(&quot;click&quot;, clickHandler);\\n}\\n\\nfunction clickHandler(e) {\\n  e.preventDefault();\\n  const href = this.getAttribute(&quot;href&quot;);\\n  const offsetTop = document.querySelector(href).offsetTop;\\n\\n  scroll({\\n    top: offsetTop,\\n    behavior: &quot;smooth&quot;\\n  });\\n}\\n&lt;/script&gt;\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/06"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396540","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/182718/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396540\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/182718/\"\n]"},"input":{"kind":"string","value":"On button click, I want user to download a file which is an apk file. On that same click, at the same time, I want to scroll to a div.\n\nIs it possible to add two actions in a button?\nNote: I'm using elementor."},"output":{"kind":"string","value":"Demo: \n\nJust use an HTML or Code element in Elementor to paste in the code instead of a Button element.\n\n```\n

      Click to Download + Smooth Scroll

      \n\n

      Insert enough text here to have a scoll bar.

      \n\n

      Tadaa! Jumps to this div based on the id #smooth onClick.

      \n\n\n\n```"}}},{"rowIdx":7657453,"cells":{"qid":{"kind":"number","value":396542,"string":"396,542"},"question":{"kind":"string","value":"
      &lt;?php the_post_thumbnail( 'medium-thumbnail', array( 'loading' =&gt; false ), [ 'alt' =&gt; esc_html ( get_the_title() ) ] );  ?&gt;\n
      \n

      Get Diagnostics info on pagespeed

      \n

      Largest Contentful Paint image was not lazily loaded

      \n

      what I wrong?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396543,"author":"Praveen","author_id":97802,"author_profile":"https://wordpress.stackexchange.com/users/97802","pm_score":0,"selected":false,"text":"

      Try this code

      \n
      $('.download-btn').click(function(){\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n
      \n"},{"answer_id":396574,"author":"Sean Sr","author_id":206158,"author_profile":"https://wordpress.stackexchange.com/users/206158","pm_score":2,"selected":false,"text":"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n  link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n  e.preventDefault();\n  const href = this.getAttribute(&quot;href&quot;);\n  const offsetTop = document.querySelector(href).offsetTop;\n\n  scroll({\n    top: offsetTop,\n    behavior: &quot;smooth&quot;\n  });\n}\n&lt;/script&gt;\n
      \n"}],"string":"[\n {\n \"answer_id\": 396543,\n \"author\": \"Praveen\",\n \"author_id\": 97802,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/97802\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Try this code

      \\n
      $('.download-btn').click(function(){\\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\\n});\\n
      \\n\"\n },\n {\n \"answer_id\": 396574,\n \"author\": \"Sean Sr\",\n \"author_id\": 206158,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206158\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \\n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \\n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\\n\\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\\n\\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\\n\\n&lt;script&gt;\\nconst links = document.querySelectorAll(&quot;a&quot;);\\n\\nfor (const link of links) {\\n  link.addEventListener(&quot;click&quot;, clickHandler);\\n}\\n\\nfunction clickHandler(e) {\\n  e.preventDefault();\\n  const href = this.getAttribute(&quot;href&quot;);\\n  const offsetTop = document.querySelector(href).offsetTop;\\n\\n  scroll({\\n    top: offsetTop,\\n    behavior: &quot;smooth&quot;\\n  });\\n}\\n&lt;/script&gt;\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/06"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396542","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/194551/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396542\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/194551/\"\n]"},"input":{"kind":"string","value":"```\n false ), [ 'alt' => esc_html ( get_the_title() ) ] ); ?>\n\n```\n\nGet Diagnostics info on pagespeed\n\nLargest Contentful Paint image was not lazily loaded\n\nwhat I wrong?"},"output":{"kind":"string","value":"Demo: \n\nJust use an HTML or Code element in Elementor to paste in the code instead of a Button element.\n\n```\n

      Click to Download + Smooth Scroll

      \n\n

      Insert enough text here to have a scoll bar.

      \n\n

      Tadaa! Jumps to this div based on the id #smooth onClick.

      \n\n\n\n```"}}},{"rowIdx":7657454,"cells":{"qid":{"kind":"number","value":396598,"string":"396,598"},"question":{"kind":"string","value":"

      One of my sites is used as a personal diary with &gt;5000 videos uploaded within the media library.

      \n

      Each post uses the following shortcode, disabling pre-load and assigning a manual poster. This reduces server load and speed for the default preload='metadata', should the post contain lots of videos.\nThe posters are manually uploaded.

      \n
      [video preload=&quot;none&quot; mp4=&quot;/wp-content/Videos/001.mp4&quot; poster=&quot;/wp-content/Pictures/Posters/001.mp4.jpg&quot;][/video]\n
      \n

      This works great for posts, however; should I view videos via their tags through the archive, it displays via the default settings as found in /wp-includes/media.php\nwhich uses the standard preload='metadata'.

      \n

      My question:\n&quot;Is there a way to set the default 'poster' to &quot;/wp-content/Pictures/Posters/filename.mp4.jpg&quot;\nSo, taking the name of the video, prepending with &quot;/wp-content/Pictures/Posters/&quot; and then appending with &quot;.jpg&quot; ?

      \n

      Any help would be greatly appreciated.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396543,"author":"Praveen","author_id":97802,"author_profile":"https://wordpress.stackexchange.com/users/97802","pm_score":0,"selected":false,"text":"

      Try this code

      \n
      $('.download-btn').click(function(){\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n
      \n"},{"answer_id":396574,"author":"Sean Sr","author_id":206158,"author_profile":"https://wordpress.stackexchange.com/users/206158","pm_score":2,"selected":false,"text":"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n  link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n  e.preventDefault();\n  const href = this.getAttribute(&quot;href&quot;);\n  const offsetTop = document.querySelector(href).offsetTop;\n\n  scroll({\n    top: offsetTop,\n    behavior: &quot;smooth&quot;\n  });\n}\n&lt;/script&gt;\n
      \n"}],"string":"[\n {\n \"answer_id\": 396543,\n \"author\": \"Praveen\",\n \"author_id\": 97802,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/97802\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Try this code

      \\n
      $('.download-btn').click(function(){\\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\\n});\\n
      \\n\"\n },\n {\n \"answer_id\": 396574,\n \"author\": \"Sean Sr\",\n \"author_id\": 206158,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206158\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \\n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \\n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\\n\\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\\n\\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\\n\\n&lt;script&gt;\\nconst links = document.querySelectorAll(&quot;a&quot;);\\n\\nfor (const link of links) {\\n  link.addEventListener(&quot;click&quot;, clickHandler);\\n}\\n\\nfunction clickHandler(e) {\\n  e.preventDefault();\\n  const href = this.getAttribute(&quot;href&quot;);\\n  const offsetTop = document.querySelector(href).offsetTop;\\n\\n  scroll({\\n    top: offsetTop,\\n    behavior: &quot;smooth&quot;\\n  });\\n}\\n&lt;/script&gt;\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/07"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396598","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213345/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396598\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213345/\"\n]"},"input":{"kind":"string","value":"One of my sites is used as a personal diary with >5000 videos uploaded within the media library.\n\nEach post uses the following shortcode, disabling pre-load and assigning a manual poster. This reduces server load and speed for the default preload='metadata', should the post contain lots of videos.\nThe posters are manually uploaded.\n\n```\n[video preload=\"none\" mp4=\"/wp-content/Videos/001.mp4\" poster=\"/wp-content/Pictures/Posters/001.mp4.jpg\"][/video]\n\n```\n\nThis works great for posts, however; should I view videos via their tags through the archive, it displays via the default settings as found in /wp-includes/media.php\nwhich uses the standard preload='metadata'.\n\nMy question:\n\"Is there a way to set the default 'poster' to \"/wp-content/Pictures/Posters/*filename*.mp4.jpg\"\nSo, taking the name of the video, prepending with \"/wp-content/Pictures/Posters/\" and then appending with \".jpg\" ?\n\nAny help would be greatly appreciated."},"output":{"kind":"string","value":"Demo: \n\nJust use an HTML or Code element in Elementor to paste in the code instead of a Button element.\n\n```\n

      Click to Download + Smooth Scroll

      \n\n

      Insert enough text here to have a scoll bar.

      \n\n

      Tadaa! Jumps to this div based on the id #smooth onClick.

      \n\n\n\n```"}}},{"rowIdx":7657455,"cells":{"qid":{"kind":"number","value":396661,"string":"396,661"},"question":{"kind":"string","value":"
      \n

      Targets : Show Locations (sub-districts &amp; cities) on the customized shop page &amp; on tab additional information - Show on line 5

      \n

      I'm building a property site using wordpress and woocommerce.

      \n

      In my country has 7 islands, 34 provinces, 514 Cities, 7041 Districts, 82194 Sub-districts.

      \n

      Then I grouped the data and added it to :

      \n

      On category

      \n
        \n
      • Verified (parent)
      • \n
      • Sold (parent)
      • \n
      • Rent (parent)
      • \n
      • Island #1 (parent)\n
          \n
        • province #1 (child)\n
            \n
          • City #1(sub-child)
          • \n
          \n
        • \n
        \n
      • \n
      • Island #2 (parent)\n
          \n
        • province #2 (child)\n
            \n
          • City #2(sub-child)
          • \n
          \n
        • \n
        \n
      • \n
      • Island #7 (parent)\n
          \n
        • province #34 (child)\n
            \n
          • City #514(sub-child)
          • \n
          \n
        • \n
        \n
      • \n
      \n

      and on product attribute :

      \n

      pa_area : city (514)

      \n

      pa_kecamatan : districts (7041)

      \n

      pa_lokasi : sub-districts (82194)

      \n

      So, I can customize the shop page as desired/needed and looks like this.

      \n

      In the Additional Information tab, I also added the sub-district and the city looks like this.

      \n

      I also display links using permalinks, for example:

      \n

      https://mydomain/product-categories/island1/provinces3/cities8 (categories)

      \n

      https://mydomain/product-categories/island5/provinces1/cities12 (categories)

      \n

      https://mydomain/districts1492 (pa_attributtes)

      \n

      https://mydomain/districts5630 (pa_attributtes)

      \n

      https://mydomain/subdistricts11596 (pa_attributtes)

      \n

      https://mydomain/subdistricts52630 (pa_attributtes)

      \n

      So far everything seems fine.

      \n
      \n

      My mind changed when I created a demo site (with current product counts at 10k.)

      \n

      Loading slowly on entering/selecting attributes is starting to feel.
      \n(I know one of the causes is CPU, RAM/Hosting).

      \n

      This made me think whether display the city only in one place.
      \n(eg city in category or city in product attribute) can help reduce server load?

      \n

      Please correct me if I misunderstood this.

      \n

      But if it's true, i using the first way is to delete the city in the category and save the city in the product attribute.

      \n

      However this will cut the scope, for example :

      \n

      Previously :

      \n

      https://mydomain/product-categories/island1/provinces3/cities8 (categories)

      \n

      https://mydomain/product-categories/island5/provinces1/cities12 (categories)

      \n

      will be :

      \n

      https://mydomain/product-categories/island1/provinces3/ (categories)

      \n

      https://mydomain/product-categories/island5/provinces1/ (categories)

      \n

      To keep showing the same thing, i can just edit the permalink to:

      \n

      https://mydomain/product-categories/island1/provinces3/&amp;cities8 (categories &amp; pa_area)

      \n

      https://mydomain/product-categories/island5/provinces1/&amp;cities12 (categories &amp; pa_area)

      \n

      But is that way I'm already on the right track?

      \n
      \n

      Meanwhile, if I use the second method, namely removing the city from the product attribute, I have trouble displaying city information on the shop page and additional information tab.

      \n

      The achievement so far is to add the code snippet below with a view like this.

      \n

      When the product only has the category :

      \n
        \n
      • Island (parent)\n
          \n
        • Province (child)\n
            \n
          • City (subChild)
          • \n
          \n
        • \n
        \n
      • \n
      \n

      View works well (Rumah Cluster Pondok Aren).

      \n

      However, when the product has the category :

      \n
        \n
      • Verified (parent)
      • \n
      • Island (parent)\n
          \n
        • Province (child)\n
            \n
          • City (subChild)
          • \n
          \n
        • \n
        \n
      • \n
      \n

      What is displayed is the Verified category, not cities (Townhouse Premium Daerah Cileungsi).

      \n

      What have I missed?

      \n
      \nBesides that, I also don't know how to display these subchild categories on the additional information tab.
      \nI'm stuck here for days, so please help me out of this hassle...\n

      Thanks a lot

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396543,"author":"Praveen","author_id":97802,"author_profile":"https://wordpress.stackexchange.com/users/97802","pm_score":0,"selected":false,"text":"

      Try this code

      \n
      $('.download-btn').click(function(){\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n
      \n"},{"answer_id":396574,"author":"Sean Sr","author_id":206158,"author_profile":"https://wordpress.stackexchange.com/users/206158","pm_score":2,"selected":false,"text":"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n  link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n  e.preventDefault();\n  const href = this.getAttribute(&quot;href&quot;);\n  const offsetTop = document.querySelector(href).offsetTop;\n\n  scroll({\n    top: offsetTop,\n    behavior: &quot;smooth&quot;\n  });\n}\n&lt;/script&gt;\n
      \n"}],"string":"[\n {\n \"answer_id\": 396543,\n \"author\": \"Praveen\",\n \"author_id\": 97802,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/97802\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Try this code

      \\n
      $('.download-btn').click(function(){\\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\\n});\\n
      \\n\"\n },\n {\n \"answer_id\": 396574,\n \"author\": \"Sean Sr\",\n \"author_id\": 206158,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206158\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \\n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \\n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\\n\\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\\n\\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\\n\\n&lt;script&gt;\\nconst links = document.querySelectorAll(&quot;a&quot;);\\n\\nfor (const link of links) {\\n  link.addEventListener(&quot;click&quot;, clickHandler);\\n}\\n\\nfunction clickHandler(e) {\\n  e.preventDefault();\\n  const href = this.getAttribute(&quot;href&quot;);\\n  const offsetTop = document.querySelector(href).offsetTop;\\n\\n  scroll({\\n    top: offsetTop,\\n    behavior: &quot;smooth&quot;\\n  });\\n}\\n&lt;/script&gt;\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/09"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396661","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/210665/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396661\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/210665/\"\n]"},"input":{"kind":"string","value":"**Targets : Show Locations (sub-districts & cities) on the customized shop page & on tab additional information - Show on line 5**\n\nI'm building a property site using wordpress and woocommerce.\n\nIn my country has 7 islands, 34 provinces, 514 Cities, 7041 Districts, 82194 Sub-districts.\n\nThen I grouped the data and added it to :\n\nOn category\n\n* Verified (parent)\n* Sold (parent)\n* Rent (parent)\n* Island #1 (parent)\n\t+ province #1 (child)\n\t\t- City #1(sub-child)\n* Island #2 (parent)\n\t+ province #2 (child)\n\t\t- City #2(sub-child)\n* Island #7 (parent)\n\t+ province #34 (child)\n\t\t- City #514(sub-child)\n\nand on product attribute :\n\npa\\_area : city (514)\n\npa\\_kecamatan : districts (7041)\n\npa\\_lokasi : sub-districts (82194)\n\nSo, I can customize the shop page as desired/needed and [looks like this](http://prnt.sc/1w2v1b6).\n\nIn the Additional Information tab, I also added the sub-district and the city [looks like this](http://prnt.sc/1w2w4tj).\n\nI also display links using permalinks, for example:\n\nhttps://mydomain/product-categories/island1/provinces3/cities8 (categories)\n\nhttps://mydomain/product-categories/island5/provinces1/cities12 (categories)\n\nhttps://mydomain/districts1492 (pa\\_attributtes)\n\nhttps://mydomain/districts5630 (pa\\_attributtes)\n\nhttps://mydomain/subdistricts11596 (pa\\_attributtes)\n\nhttps://mydomain/subdistricts52630 (pa\\_attributtes)\n\nSo far everything seems fine.\n\n---\n\nMy mind changed when I created a demo site (with current product counts at 10k.)\n\nLoading slowly on entering/selecting attributes is starting to feel. \n\n(I know one of the causes is CPU, RAM/Hosting).\n\nThis made me think whether display the city only in one place. \n\n(eg city in category or city in product attribute) can help reduce server load?\n\nPlease correct me if I misunderstood this.\n\nBut if it's true, i using the first way is to delete the city in the category and save the city in the product attribute.\n\nHowever this will cut the scope, for example :\n\nPreviously :\n\nhttps://mydomain/product-categories/island1/provinces3/cities8 (categories)\n\nhttps://mydomain/product-categories/island5/provinces1/cities12 (categories)\n\nwill be :\n\nhttps://mydomain/product-categories/island1/provinces3/ (categories)\n\nhttps://mydomain/product-categories/island5/provinces1/ (categories)\n\nTo keep showing the same thing, i can just edit the permalink to:\n\nhttps://mydomain/product-categories/island1/provinces3/&cities8 (categories & pa\\_area)\n\nhttps://mydomain/product-categories/island5/provinces1/&cities12 (categories & pa\\_area)\n\nBut is that way I'm already on the right track?\n\n---\n\nMeanwhile, if I use the second method, namely removing the city from the product attribute, I have trouble displaying city information on the shop page and additional information tab.\n\nThe achievement so far is to add the code snippet below with a [view like this](http://prnt.sc/1w2z1ah).\n\nWhen the product only has the category :\n\n* Island (parent)\n\t+ Province (child)\n\t\t- City (subChild)\n\nView works well (Rumah Cluster Pondok Aren).\n\nHowever, when the product has the category :\n\n* Verified (parent)\n* Island (parent)\n\t+ Province (child)\n\t\t- City (subChild)\n\nWhat is displayed is the Verified category, not cities (Townhouse Premium Daerah Cileungsi).\n\nWhat have I missed?\n\n---\n\nBesides that, I also don't know how to display these subchild categories on the additional information tab. \n\nI'm stuck here for days, so please help me out of this hassle...\nThanks a lot"},"output":{"kind":"string","value":"Demo: \n\nJust use an HTML or Code element in Elementor to paste in the code instead of a Button element.\n\n```\n

      Click to Download + Smooth Scroll

      \n\n

      Insert enough text here to have a scoll bar.

      \n\n

      Tadaa! Jumps to this div based on the id #smooth onClick.

      \n\n\n\n```"}}},{"rowIdx":7657456,"cells":{"qid":{"kind":"number","value":396663,"string":"396,663"},"question":{"kind":"string","value":"

      Everything worked fine a week ago. Lets Encrypt certificate on the site is valid. I am currently getting the following error while creating a product:

      \n
      {&quot;code&quot;:&quot;woocommerce_product_image_upload_error&quot;,&quot;message&quot;:&quot;Error getting remote image https:\\/\\/mysite.com\\/wp-content\\/uploads\\/2021\\/10\\/60c739fd1-1.jpg. Error: cURL error 60: SSL certificate problem: certificate has expired&quot;,&quot;data&quot;:{&quot;status&quot;:400}}\n
      \n

      In this case, the picture is available by the URL.\nTried these solutions (https://wp-kama.com/note/error-making-request-wordpress[enter link description here]1) but doesn't help.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396543,"author":"Praveen","author_id":97802,"author_profile":"https://wordpress.stackexchange.com/users/97802","pm_score":0,"selected":false,"text":"

      Try this code

      \n
      $('.download-btn').click(function(){\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n
      \n"},{"answer_id":396574,"author":"Sean Sr","author_id":206158,"author_profile":"https://wordpress.stackexchange.com/users/206158","pm_score":2,"selected":false,"text":"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n  link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n  e.preventDefault();\n  const href = this.getAttribute(&quot;href&quot;);\n  const offsetTop = document.querySelector(href).offsetTop;\n\n  scroll({\n    top: offsetTop,\n    behavior: &quot;smooth&quot;\n  });\n}\n&lt;/script&gt;\n
      \n"}],"string":"[\n {\n \"answer_id\": 396543,\n \"author\": \"Praveen\",\n \"author_id\": 97802,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/97802\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Try this code

      \\n
      $('.download-btn').click(function(){\\n  $('html, body').animate({scrollTop : $('body').height() }, 800);\\n});\\n
      \\n\"\n },\n {\n \"answer_id\": 396574,\n \"author\": \"Sean Sr\",\n \"author_id\": 206158,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/206158\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      Demo: https://codepen.io/livehelp/pen/MWoNPqX?editors=1010

      \\n

      Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.

      \\n
      &lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\\n\\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\\n\\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\\n\\n&lt;script&gt;\\nconst links = document.querySelectorAll(&quot;a&quot;);\\n\\nfor (const link of links) {\\n  link.addEventListener(&quot;click&quot;, clickHandler);\\n}\\n\\nfunction clickHandler(e) {\\n  e.preventDefault();\\n  const href = this.getAttribute(&quot;href&quot;);\\n  const offsetTop = document.querySelector(href).offsetTop;\\n\\n  scroll({\\n    top: offsetTop,\\n    behavior: &quot;smooth&quot;\\n  });\\n}\\n&lt;/script&gt;\\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/09"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396663","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/89603/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396663\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/89603/\"\n]"},"input":{"kind":"string","value":"Everything worked fine a week ago. Lets Encrypt certificate on the site is valid. I am currently getting the following error while creating a product:\n\n```\n{\"code\":\"woocommerce_product_image_upload_error\",\"message\":\"Error getting remote image https:\\/\\/mysite.com\\/wp-content\\/uploads\\/2021\\/10\\/60c739fd1-1.jpg. Error: cURL error 60: SSL certificate problem: certificate has expired\",\"data\":{\"status\":400}}\n\n```\n\nIn this case, the picture is available by the URL.\nTried these solutions ([https://wp-kama.com/note/error-making-request-wordpress[enter](https://wp-kama.com/note/error-making-request-wordpress%5Benter) link description here][1](https://wp-kama.com/note/error-making-request-wordpress)) but doesn't help."},"output":{"kind":"string","value":"Demo: \n\nJust use an HTML or Code element in Elementor to paste in the code instead of a Button element.\n\n```\n

      Click to Download + Smooth Scroll

      \n\n

      Insert enough text here to have a scoll bar.

      \n\n

      Tadaa! Jumps to this div based on the id #smooth onClick.

      \n\n\n\n```"}}},{"rowIdx":7657457,"cells":{"qid":{"kind":"number","value":396768,"string":"396,768"},"question":{"kind":"string","value":"

      I registered a custom post type called wasb_message with show_in_rest set to true and rest_base set to 'messages' so the resource is reachable at endpoint https://mydomain/wp-json/wp/v2/messages (using the WP_REST_Posts_Controller class).\nThe custom post type has a custom meta field called wasb_status with an integer value, how can I add a custom parameter so when I do a get request to endpoint https://mydomain/wp-json/wp/v2/messages?status=2 I retrieve messages with wasb_status equal to 2 without register a new route?

      \n

      I read this code reference page and this old question but I can't get it working, using Postman to send get request I get:

      \n
      {\n    &quot;code&quot;: &quot;rest_invalid_param&quot;,\n    &quot;message&quot;: &quot;Parametro(i) non valido(i): status&quot;,\n    &quot;data&quot;: {\n        &quot;status&quot;: 400,\n        &quot;params&quot;: {\n            &quot;status&quot;: &quot;Stato non consentito.&quot;\n        },\n        &quot;details&quot;: {\n            &quot;status&quot;: {\n                &quot;code&quot;: &quot;rest_forbidden_status&quot;,\n                &quot;message&quot;: &quot;Stato non consentito.&quot;,\n                &quot;data&quot;: {\n                    &quot;status&quot;: 401\n                }\n            }\n        }\n    }\n}\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":396769,"author":"Tami","author_id":181119,"author_profile":"https://wordpress.stackexchange.com/users/181119","pm_score":0,"selected":false,"text":"

      As per the reply by Haris it should be something like this:

      \n
      function wasb_rest_parameter($args, $request) {\n    if( isset($request[&quot;wasb_status&quot;]) &amp;&amp; is_numeric($request[&quot;wasb_status&quot;]) ) {\n        $args['meta_key'] = 'wasb_status';\n        $args['meta_value'] = intval($request[&quot;wasb_status&quot;]);\n    }       \n \n    return $args;\n}\nadd_filter('rest_wasb_message_query', 'wasb_rest_parameter', 10, 2);\n
      \n

      Not yet tested. If it does not work, will update the answer.

      \n"},{"answer_id":396774,"author":"icolumbro","author_id":178523,"author_profile":"https://wordpress.stackexchange.com/users/178523","pm_score":1,"selected":false,"text":"

      I solved following this answer and writing:

      \n
      public function query_wasb_messages_by_status( $args, $request ) {\n\n        if ( ! is_null( $request-&gt;get_param( 'message_status' ) ) ) {\n            $args['meta_query'] = array(\n                '_wasb_message_status' =&gt; array(\n                    'key'     =&gt; '_wasb_message_status',\n                    'value'   =&gt; (int) $request-&gt;get_param( 'message_status' ),\n                    'compare' =&gt; '=',\n                    'type'    =&gt; 'numeric'\n                )\n            );\n        }\n\n        return $args;\n\n    }\nadd_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 );\n
      \n

      My problem is I used status as parameter name but status already exists for posts ('draft', 'published', etc...) so I changed the name to message_status...

      \n"}],"string":"[\n {\n \"answer_id\": 396769,\n \"author\": \"Tami\",\n \"author_id\": 181119,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/181119\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      As per the reply by Haris it should be something like this:

      \\n
      function wasb_rest_parameter($args, $request) {\\n    if( isset($request[&quot;wasb_status&quot;]) &amp;&amp; is_numeric($request[&quot;wasb_status&quot;]) ) {\\n        $args['meta_key'] = 'wasb_status';\\n        $args['meta_value'] = intval($request[&quot;wasb_status&quot;]);\\n    }       \\n \\n    return $args;\\n}\\nadd_filter('rest_wasb_message_query', 'wasb_rest_parameter', 10, 2);\\n
      \\n

      Not yet tested. If it does not work, will update the answer.

      \\n\"\n },\n {\n \"answer_id\": 396774,\n \"author\": \"icolumbro\",\n \"author_id\": 178523,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/178523\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      I solved following this answer and writing:

      \\n
      public function query_wasb_messages_by_status( $args, $request ) {\\n\\n        if ( ! is_null( $request-&gt;get_param( 'message_status' ) ) ) {\\n            $args['meta_query'] = array(\\n                '_wasb_message_status' =&gt; array(\\n                    'key'     =&gt; '_wasb_message_status',\\n                    'value'   =&gt; (int) $request-&gt;get_param( 'message_status' ),\\n                    'compare' =&gt; '=',\\n                    'type'    =&gt; 'numeric'\\n                )\\n            );\\n        }\\n\\n        return $args;\\n\\n    }\\nadd_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 );\\n
      \\n

      My problem is I used status as parameter name but status already exists for posts ('draft', 'published', etc...) so I changed the name to message_status...

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/12"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396768","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/178523/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396768\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/178523/\"\n]"},"input":{"kind":"string","value":"I registered a custom post type called `wasb_message` with `show_in_rest` set to `true` and `rest_base` set to `'messages'` so the resource is reachable at endpoint *https://mydomain/wp-json/wp/v2/messages* (using the `WP_REST_Posts_Controller` class).\nThe custom post type has a custom meta field called `wasb_status` with an integer value, how can I add a custom parameter so when I do a get request to endpoint *https://mydomain/wp-json/wp/v2/messages?status=2* I retrieve messages with `wasb_status` equal to 2 without register a new route?\n\nI read [this code reference page](https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/) and [this old question](https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route) but I can't get it working, using Postman to send get request I get:\n\n```\n{\n \"code\": \"rest_invalid_param\",\n \"message\": \"Parametro(i) non valido(i): status\",\n \"data\": {\n \"status\": 400,\n \"params\": {\n \"status\": \"Stato non consentito.\"\n },\n \"details\": {\n \"status\": {\n \"code\": \"rest_forbidden_status\",\n \"message\": \"Stato non consentito.\",\n \"data\": {\n \"status\": 401\n }\n }\n }\n }\n}\n\n```"},"output":{"kind":"string","value":"I solved following [this answer](https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route) and writing:\n\n```\npublic function query_wasb_messages_by_status( $args, $request ) {\n\n if ( ! is_null( $request->get_param( 'message_status' ) ) ) {\n $args['meta_query'] = array(\n '_wasb_message_status' => array(\n 'key' => '_wasb_message_status',\n 'value' => (int) $request->get_param( 'message_status' ),\n 'compare' => '=',\n 'type' => 'numeric'\n )\n );\n }\n\n return $args;\n\n }\nadd_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 );\n\n```\n\nMy problem is I used `status` as parameter name but `status` already exists for posts ('draft', 'published', etc...) so I changed the name to `message_status`..."}}},{"rowIdx":7657458,"cells":{"qid":{"kind":"number","value":396902,"string":"396,902"},"question":{"kind":"string","value":"

      I try to require_once() a file, if the condition of a specific tag is met, on a woocommerce single product page.

      \n

      I've added following to my functions.php

      \n
      if(has_term('xyz', 'product_tag')){\n    require_once WP_CONTENT_DIR . '/path/file.php';\n}\n
      \n

      It doesn't load my file, but if I take it out of my condition, it does load.

      \n

      What can I do to achieve this logic?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396904,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

      require_once is a function, try this way.

      \n
      if(has_term('xyz', 'product_tag')){\n    require_once( WP_CONTENT_DIR.'/path/file.php');\n}\n
      \n

      also require_once() in functions.php, dont know what to say. give feedback if the code above had work has intended.

      \n"},{"answer_id":396940,"author":"Andrea Somovigo","author_id":64435,"author_profile":"https://wordpress.stackexchange.com/users/64435","pm_score":2,"selected":true,"text":"

      has_term() is a template function therefore it does not work if you use it straight in functions.php which is loaded well before knowing if the current object is a product page.\nSo if you use it in functions.php you could do:

      \n
      add_action('template_redirect','my_inclusion_function');\nfunction my_inclusion_function(){\n  if(is_product() &amp;&amp; has_term('xyz', 'product_tag')){\n    require_once( WP_CONTENT_DIR.'/path/file.php');\n  }\n}\n
      \n

      is_product() checks if you are in a single product and then if the product has tag xyz

      \n

      If the inclusion has layout implications such as print additional information or so, then this approach is not ideal since the inclusion occurs at the very beginning of the content jsut after the &lt;body&gt; tag opening. In this case you can just modify the single-product.php template file (as suggested in the comment by tiago calado)

      \n

      Also you can use one of the available hooks in the single-product page check this useful resource and use it directly in functions.php. The advantage of this last approach is that you don't have to review the layout pages in case of future theme switch.

      \n"}],"string":"[\n {\n \"answer_id\": 396904,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      require_once is a function, try this way.

      \\n
      if(has_term('xyz', 'product_tag')){\\n    require_once( WP_CONTENT_DIR.'/path/file.php');\\n}\\n
      \\n

      also require_once() in functions.php, dont know what to say. give feedback if the code above had work has intended.

      \\n\"\n },\n {\n \"answer_id\": 396940,\n \"author\": \"Andrea Somovigo\",\n \"author_id\": 64435,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/64435\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

      has_term() is a template function therefore it does not work if you use it straight in functions.php which is loaded well before knowing if the current object is a product page.\\nSo if you use it in functions.php you could do:

      \\n
      add_action('template_redirect','my_inclusion_function');\\nfunction my_inclusion_function(){\\n  if(is_product() &amp;&amp; has_term('xyz', 'product_tag')){\\n    require_once( WP_CONTENT_DIR.'/path/file.php');\\n  }\\n}\\n
      \\n

      is_product() checks if you are in a single product and then if the product has tag xyz

      \\n

      If the inclusion has layout implications such as print additional information or so, then this approach is not ideal since the inclusion occurs at the very beginning of the content jsut after the &lt;body&gt; tag opening. In this case you can just modify the single-product.php template file (as suggested in the comment by tiago calado)

      \\n

      Also you can use one of the available hooks in the single-product page check this useful resource and use it directly in functions.php. The advantage of this last approach is that you don't have to review the layout pages in case of future theme switch.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/14"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396902","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213621/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396902\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213621/\"\n]"},"input":{"kind":"string","value":"I try to `require_once()` a file, if the condition of a specific tag is met, on a woocommerce single product page.\n\nI've added following to my `functions.php`\n\n```\nif(has_term('xyz', 'product_tag')){\n require_once WP_CONTENT_DIR . '/path/file.php';\n}\n\n```\n\nIt doesn't load my file, but if I take it out of my condition, it does load.\n\nWhat can I do to achieve this logic?"},"output":{"kind":"string","value":"`has_term()` is a template function therefore it does not work if you use it straight in functions.php which is loaded well before knowing if the current object is a product page.\nSo if you use it in `functions.php` you could do:\n\n```\nadd_action('template_redirect','my_inclusion_function');\nfunction my_inclusion_function(){\n if(is_product() && has_term('xyz', 'product_tag')){\n require_once( WP_CONTENT_DIR.'/path/file.php');\n }\n}\n\n```\n\n`is_product()` checks if you are in a single product and then if the product has tag xyz\n\nIf the inclusion has layout implications such as print additional information or so, then this approach is not ideal since the inclusion occurs at the very beginning of the content jsut after the `` tag opening. In this case you can just modify the single-product.php template file (as suggested in the comment by [tiago calado](https://wordpress.stackexchange.com/users/198152/tiago-calado))\n\nAlso you can use one of the available hooks in the single-product page check [this useful resource](https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/) and use it directly in functions.php. The advantage of this last approach is that you don't have to review the layout pages in case of future theme switch."}}},{"rowIdx":7657459,"cells":{"qid":{"kind":"number","value":396908,"string":"396,908"},"question":{"kind":"string","value":"

      Unless I type the URL of my site as example.com/wp-login.php, with URL typed as example.com, the front page is automatically directed to the following unknown site:

      \n
      https://elementonfor.live/?utm_campaign=pEv9cTd8QNHYzqqr5UNFx2COHvnp_JE3r8uVIhm3Qww1&amp;t=main9\n
      \n

      The above website is unknown, and it is not clear where it has come from. I have scanned my website for malware. The malware plugin I am using shows the website as clean. Not sure what I should do to resolve the issue.

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396911,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

      have you installed any new plugin recently. that can be a cause.\nif so try to deactivate them and check if the site still does that.\ndeactive all plugins not essential to home page. and check if it still does that. if so, activate one by one until you get the one is making that.

      \n

      this is just one probably cause.\nafter you make sure any plugin is doing this. and the problem goes on. now you are sure is not a plugin.\nlook on your functions.php and look for any function that can be making you to be redirect.\ncheck also if other pages load properly like exanple.com/wp-login or example.com/somepageYouKnowExistes if this only happens on your front page can be an issue with your font-page.php, or with elementor on that page once your are being redirect to a supposed elementor page.\nif any of this gives you a clue. there are many more ways to go on debuging manually.

      \n"},{"answer_id":396939,"author":"Reza","author_id":170049,"author_profile":"https://wordpress.stackexchange.com/users/170049","pm_score":1,"selected":false,"text":"

      Finally, I had to contact my web host. They cleared the server cache and everything is back to normal. Thanks to @tiago-calado and @Rup for their response.

      \n"}],"string":"[\n {\n \"answer_id\": 396911,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      have you installed any new plugin recently. that can be a cause.\\nif so try to deactivate them and check if the site still does that.\\ndeactive all plugins not essential to home page. and check if it still does that. if so, activate one by one until you get the one is making that.

      \\n

      this is just one probably cause.\\nafter you make sure any plugin is doing this. and the problem goes on. now you are sure is not a plugin.\\nlook on your functions.php and look for any function that can be making you to be redirect.\\ncheck also if other pages load properly like exanple.com/wp-login or example.com/somepageYouKnowExistes if this only happens on your front page can be an issue with your font-page.php, or with elementor on that page once your are being redirect to a supposed elementor page.\\nif any of this gives you a clue. there are many more ways to go on debuging manually.

      \\n\"\n },\n {\n \"answer_id\": 396939,\n \"author\": \"Reza\",\n \"author_id\": 170049,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/170049\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

      Finally, I had to contact my web host. They cleared the server cache and everything is back to normal. Thanks to @tiago-calado and @Rup for their response.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/14"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396908","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/170049/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396908\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/170049/\"\n]"},"input":{"kind":"string","value":"Unless I type the URL of my site as example.com/wp-login.php, with URL typed as example.com, the front page is automatically directed to the following unknown site:\n\n```\nhttps://elementonfor.live/?utm_campaign=pEv9cTd8QNHYzqqr5UNFx2COHvnp_JE3r8uVIhm3Qww1&t=main9\n\n```\n\nThe above website is unknown, and it is not clear where it has come from. I have scanned my website for malware. The malware plugin I am using shows the website as clean. Not sure what I should do to resolve the issue."},"output":{"kind":"string","value":"Finally, I had to contact my web host. They cleared the server cache and everything is back to normal. Thanks to @tiago-calado and @Rup for their response."}}},{"rowIdx":7657460,"cells":{"qid":{"kind":"number","value":396944,"string":"396,944"},"question":{"kind":"string","value":"

      hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr_fingerprint_default so please give me correct command line to run thanks in advance

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396945,"author":"WebElaine","author_id":102815,"author_profile":"https://wordpress.stackexchange.com/users/102815","pm_score":0,"selected":false,"text":"

      First, make sure you back up your database. :)

      \n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \n"},{"answer_id":396948,"author":"Andrea Somovigo","author_id":64435,"author_profile":"https://wordpress.stackexchange.com/users/64435","pm_score":3,"selected":true,"text":"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n
      \n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n
      \n"}],"string":"[\n {\n \"answer_id\": 396945,\n \"author\": \"WebElaine\",\n \"author_id\": 102815,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/102815\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      First, make sure you back up your database. :)

      \\n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \\n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \\n\"\n },\n {\n \"answer_id\": 396948,\n \"author\": \"Andrea Somovigo\",\n \"author_id\": 64435,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/64435\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\\n
      \\n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \\n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/15"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396944","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/175359/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396944\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/175359/\"\n]"},"input":{"kind":"string","value":"hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp\\_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr\\_fingerprint\\_default so please give me correct command line to run thanks in advance"},"output":{"kind":"string","value":"```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n\n```\n\n{PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result\n\n```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n\n```"}}},{"rowIdx":7657461,"cells":{"qid":{"kind":"number","value":396962,"string":"396,962"},"question":{"kind":"string","value":"

      I'm new to the Wordpress/PHP world. I want my page be able to communicate with an API that I build myself. So for this I have a form on my Wordpress Page using a HTML code widget which looks like this:

      \n
      &lt;html&gt;\n&lt;body&gt;\n    &lt;div&gt;\n        &lt;form id=&quot;myform&quot; action=&quot;submit_shortcode&quot;&gt;\n            &lt;input type=&quot;text&quot; id=&quot;input&quot; placeholder=&quot;Input&quot; required&gt;\n            &lt;input type=&quot;submit&quot; value=&quot;Enter&quot;&gt;\n        &lt;/form&gt;\n    &lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n
      \n

      And I have added this code to functions.php of the current theme:

      \n
      function get_shortcode($sc) {\n    $response = wp_remote_get('http://localhost:9000/shortcode/'.$sc);\n\n    if (is_array($response)) {\n        $body = $response['body'];\n        $data = json_decode($body);\n        echo $data;\n        if (! is_wp_error($data)) {\n            echo &quot;error&quot;;\n        }\n    }\n\n    return;\n}\n\nadd_action('submit_shortcode', 'get_shortcode');\n
      \n

      But I can't see how to integrate the function with the form. When I submit my form, it sends me to mypage/submit_shortcode. How can I trigger the function get_shortcode when submitting the form?

      \n

      PS: This &quot;shortcode&quot; has nothing to do with the Shortcode widget of Elementor

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396945,"author":"WebElaine","author_id":102815,"author_profile":"https://wordpress.stackexchange.com/users/102815","pm_score":0,"selected":false,"text":"

      First, make sure you back up your database. :)

      \n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \n"},{"answer_id":396948,"author":"Andrea Somovigo","author_id":64435,"author_profile":"https://wordpress.stackexchange.com/users/64435","pm_score":3,"selected":true,"text":"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n
      \n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n
      \n"}],"string":"[\n {\n \"answer_id\": 396945,\n \"author\": \"WebElaine\",\n \"author_id\": 102815,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/102815\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      First, make sure you back up your database. :)

      \\n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \\n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \\n\"\n },\n {\n \"answer_id\": 396948,\n \"author\": \"Andrea Somovigo\",\n \"author_id\": 64435,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/64435\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\\n
      \\n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \\n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/15"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/396962","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213571/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/396962\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213571/\"\n]"},"input":{"kind":"string","value":"I'm new to the Wordpress/PHP world. I want my page be able to communicate with an API that I build myself. So for this I have a form on my Wordpress Page using a HTML code widget which looks like this:\n\n```\n\n\n
      \n
      \n \n \n
      \n
      \n\n\n\n```\n\nAnd I have added this code to functions.php of the current theme:\n\n```\nfunction get_shortcode($sc) {\n $response = wp_remote_get('http://localhost:9000/shortcode/'.$sc);\n\n if (is_array($response)) {\n $body = $response['body'];\n $data = json_decode($body);\n echo $data;\n if (! is_wp_error($data)) {\n echo \"error\";\n }\n }\n\n return;\n}\n\nadd_action('submit_shortcode', 'get_shortcode');\n\n```\n\nBut I can't see how to integrate the function with the form. When I submit my form, it sends me to mypage/submit\\_shortcode. How can I trigger the function get\\_shortcode when submitting the form?\n\nPS: This \"shortcode\" has nothing to do with the Shortcode widget of Elementor"},"output":{"kind":"string","value":"```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n\n```\n\n{PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result\n\n```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n\n```"}}},{"rowIdx":7657462,"cells":{"qid":{"kind":"number","value":397015,"string":"397,015"},"question":{"kind":"string","value":"

      I recently migrated the site from a subdomain back to the main domain using WP All-in-One Migration Tool. The migration was successful and I can see the wp-admin panel just fine and even view the site while logged in.

      \n

      But... when logging out the visitors just see the white screen of death. I have tried every fix in the book on Google, any tips would be appreciated.

      \n

      Thanks!

      \n"},"answers":{"kind":"list like","value":[{"answer_id":396945,"author":"WebElaine","author_id":102815,"author_profile":"https://wordpress.stackexchange.com/users/102815","pm_score":0,"selected":false,"text":"

      First, make sure you back up your database. :)

      \n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \n"},{"answer_id":396948,"author":"Andrea Somovigo","author_id":64435,"author_profile":"https://wordpress.stackexchange.com/users/64435","pm_score":3,"selected":true,"text":"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n
      \n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n
      \n"}],"string":"[\n {\n \"answer_id\": 396945,\n \"author\": \"WebElaine\",\n \"author_id\": 102815,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/102815\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      First, make sure you back up your database. :)

      \\n

      If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be

      \\n

      DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'

      \\n\"\n },\n {\n \"answer_id\": 396948,\n \"author\": \"Andrea Somovigo\",\n \"author_id\": 64435,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/64435\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\\n
      \\n

      {PREFIX} is the string $table_prefix defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result

      \\n
      DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \\n
      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/18"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397015","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213737/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397015\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213737/\"\n]"},"input":{"kind":"string","value":"I recently migrated the site from a subdomain back to the main domain using WP All-in-One Migration Tool. The migration was successful and I can see the wp-admin panel just fine and even view the site while logged in.\n\nBut... when logging out the visitors just see the white screen of death. I have tried every fix in the book on Google, any tips would be appreciated.\n\nThanks!"},"output":{"kind":"string","value":"```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n\n```\n\n{PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result\n\n```\nDELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n\n```"}}},{"rowIdx":7657463,"cells":{"qid":{"kind":"number","value":397120,"string":"397,120"},"question":{"kind":"string","value":"

      Checking the editor-blocks.css file found in some themes, I see the following CSS classes added before some of the individual block classes:

      \n
      .edit-post-visual-editor\n.editor-block-list__layout\n.editor-block-list__block\n.block-library-list\n
      \n

      An example:

      \n
      .editor-block-list__block .wp-block-latest-comments {\n    margin-left: 0;\n    margin-right: 0;\n}\n
      \n

      And then others, don't have them:

      \n
      .wp-block-quote.is-large,\n.wp-block-quote.is-style-large {\n    font-size: 1.5rem;\n    margin: 0 0.8em 0.8em;\n    padding: 0;\n    border: 0;    \n}\n
      \n

      What's the use of these CSS classes? Which elements in the block editor do they target? Why do some of the block CSS classes have them added before and why others don't? Are they really necessary? Why some themes have an editor-blocks.css file and a blocks.css file and why others just the blocks.css one?

      \n

      Thanks in advance

      \n"},"answers":{"kind":"list like","value":[{"answer_id":397155,"author":"Kalimah","author_id":35871,"author_profile":"https://wordpress.stackexchange.com/users/35871","pm_score":0,"selected":false,"text":"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \n
       register_block_type( 'custom-plugin/custom-block', array(\n        'editor_script' =&gt; 'editor-script.js',\n        'editor_style'  =&gt; 'editor-style.css',\n        'style'         =&gt; 'frontend.css',\n    ) );\n
      \n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \n"},{"answer_id":397574,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":-1,"selected":false,"text":"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \n"},{"answer_id":402084,"author":"leemon","author_id":33049,"author_profile":"https://wordpress.stackexchange.com/users/33049","pm_score":1,"selected":true,"text":"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \n"}],"string":"[\n {\n \"answer_id\": 397155,\n \"author\": \"Kalimah\",\n \"author_id\": 35871,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/35871\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \\n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \\n
       register_block_type( 'custom-plugin/custom-block', array(\\n        'editor_script' =&gt; 'editor-script.js',\\n        'editor_style'  =&gt; 'editor-style.css',\\n        'style'         =&gt; 'frontend.css',\\n    ) );\\n
      \\n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \\n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \\n\"\n },\n {\n \"answer_id\": 397574,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \\n\"\n },\n {\n \"answer_id\": 402084,\n \"author\": \"leemon\",\n \"author_id\": 33049,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/33049\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \\n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \\n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \\n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \\n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/20"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397120","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/33049/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397120\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/33049/\"\n]"},"input":{"kind":"string","value":"Checking the `editor-blocks.css` file found in some themes, I see the following CSS classes added before some of the individual block classes:\n\n```\n.edit-post-visual-editor\n.editor-block-list__layout\n.editor-block-list__block\n.block-library-list\n\n```\n\nAn example:\n\n```\n.editor-block-list__block .wp-block-latest-comments {\n margin-left: 0;\n margin-right: 0;\n}\n\n```\n\nAnd then others, don't have them:\n\n```\n.wp-block-quote.is-large,\n.wp-block-quote.is-style-large {\n font-size: 1.5rem;\n margin: 0 0.8em 0.8em;\n padding: 0;\n border: 0; \n}\n\n```\n\nWhat's the use of these CSS classes? Which elements in the block editor do they target? Why do some of the block CSS classes have them added before and why others don't? Are they really necessary? Why some themes have an `editor-blocks.css` file and a `blocks.css` file and why others just the `blocks.css` one?\n\nThanks in advance"},"output":{"kind":"string","value":"In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.\n\nBoth `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes.\n\nI have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it.\n\nFinally, the `.edit-post-visual-editor` class targets the whole block editor.\n\nIn summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor."}}},{"rowIdx":7657464,"cells":{"qid":{"kind":"number","value":397145,"string":"397,145"},"question":{"kind":"string","value":"

      In this project, there are custom posts with a variety of titles. In each post with the title that is the name of a person (first name, last name), there is a custom field (custom_title) that can hold an alternate name (last name, first name).

      \n

      In order to display the names in a useful way in the custom archive page, the object is to check for a value in the custom_title field and if present update the post title with the custom title. After all of the applicable titles have been updated, the query must sort all of the posts by title, all the while recognizing the updated titles.

      \n

      Using the code below, the original titles of the name articles are updated with the custom titles, but the sort order doesn't change--it still sorts by the original title.

      \n

      Thanks for taking the time to help!

      \n
          function cchs_swap_title( $updatedTitle) \n    {\n        $customTitle = get_post_meta( get_the_ID(), 'custom_title', true);\n        if(!empty($customTitle))\n        {\n            $updatedTitle = $customTitle;\n        }\n        return $updatedTitle;\n    }\n    add_filter( 'the_title', 'cchs_swap_title');\n    \n    function cchs_archives_orderby( $the_query ) {\n        if(!is_admin() &amp;&amp; $the_query-&gt;is_main_query())\n        {\n            $the_query-&gt;set( 'orderby', 'title' );\n            $the_query-&gt;set( 'order', 'DESC' );\n            \n        }\n    }\n    add_action( 'pre_get_posts', 'cchs_archives_orderby', 99999 );      \n\n    $args = array(\n        'post_type'         =&gt; 'cchs_article',\n        'posts_per_page'    =&gt; -1\n    );\n    $the_query = new WP_Query( $args );\n\n    if ( $the_query-&gt;have_posts() ) : \n        while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n            get_template_part( 'template-parts/content', 'archive-cchs_article');\n        endwhile;\n        wp_reset_postdata();\n    else :\n        get_template_part( 'template-parts/content', 'none' );\n    endif;\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":397155,"author":"Kalimah","author_id":35871,"author_profile":"https://wordpress.stackexchange.com/users/35871","pm_score":0,"selected":false,"text":"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \n
       register_block_type( 'custom-plugin/custom-block', array(\n        'editor_script' =&gt; 'editor-script.js',\n        'editor_style'  =&gt; 'editor-style.css',\n        'style'         =&gt; 'frontend.css',\n    ) );\n
      \n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \n"},{"answer_id":397574,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":-1,"selected":false,"text":"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \n"},{"answer_id":402084,"author":"leemon","author_id":33049,"author_profile":"https://wordpress.stackexchange.com/users/33049","pm_score":1,"selected":true,"text":"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \n"}],"string":"[\n {\n \"answer_id\": 397155,\n \"author\": \"Kalimah\",\n \"author_id\": 35871,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/35871\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \\n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \\n
       register_block_type( 'custom-plugin/custom-block', array(\\n        'editor_script' =&gt; 'editor-script.js',\\n        'editor_style'  =&gt; 'editor-style.css',\\n        'style'         =&gt; 'frontend.css',\\n    ) );\\n
      \\n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \\n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \\n\"\n },\n {\n \"answer_id\": 397574,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \\n\"\n },\n {\n \"answer_id\": 402084,\n \"author\": \"leemon\",\n \"author_id\": 33049,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/33049\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \\n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \\n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \\n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \\n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/20"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397145","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213871/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397145\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213871/\"\n]"},"input":{"kind":"string","value":"In this project, there are custom posts with a variety of titles. In each post with the title that is the name of a person (first name, last name), there is a custom field (custom\\_title) that can hold an alternate name (last name, first name).\n\nIn order to display the names in a useful way in the custom archive page, the object is to check for a value in the custom\\_title field and if present update the post title with the custom title. After all of the applicable titles have been updated, the query must sort all of the posts by title, all the while recognizing the updated titles.\n\nUsing the code below, the original titles of the name articles are updated with the custom titles, but the sort order doesn't change--it still sorts by the original title.\n\nThanks for taking the time to help!\n\n```\n function cchs_swap_title( $updatedTitle) \n {\n $customTitle = get_post_meta( get_the_ID(), 'custom_title', true);\n if(!empty($customTitle))\n {\n $updatedTitle = $customTitle;\n }\n return $updatedTitle;\n }\n add_filter( 'the_title', 'cchs_swap_title');\n\n function cchs_archives_orderby( $the_query ) {\n if(!is_admin() && $the_query->is_main_query())\n {\n $the_query->set( 'orderby', 'title' );\n $the_query->set( 'order', 'DESC' );\n\n }\n }\n add_action( 'pre_get_posts', 'cchs_archives_orderby', 99999 ); \n\n $args = array(\n 'post_type' => 'cchs_article',\n 'posts_per_page' => -1\n );\n $the_query = new WP_Query( $args );\n\n if ( $the_query->have_posts() ) : \n while ( $the_query->have_posts() ) : $the_query->the_post();\n get_template_part( 'template-parts/content', 'archive-cchs_article');\n endwhile;\n wp_reset_postdata();\n else :\n get_template_part( 'template-parts/content', 'none' );\n endif;\n\n```"},"output":{"kind":"string","value":"In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.\n\nBoth `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes.\n\nI have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it.\n\nFinally, the `.edit-post-visual-editor` class targets the whole block editor.\n\nIn summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor."}}},{"rowIdx":7657465,"cells":{"qid":{"kind":"number","value":397316,"string":"397,316"},"question":{"kind":"string","value":"

      I want to change WooCommerce pagination links from:

      \n
        \n
      • example.com/category/page/3/ to:
      • \n
      • example.com/category/3/
      • \n
      \n

      I found many examples of how to change '/page/' to '/something/' but I want only the number of the current page. I also tried this:

      \n
      $wp_rewrite-&gt;pagination_base = ''; \n
      \n

      But then my url looks like this:

      \n

      example.com/category//3/

      \n

      And that's not good either. Is it even possible to remove 'pagination base' from url structure?

      \n"},"answers":{"kind":"list like","value":[{"answer_id":397155,"author":"Kalimah","author_id":35871,"author_profile":"https://wordpress.stackexchange.com/users/35871","pm_score":0,"selected":false,"text":"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \n
       register_block_type( 'custom-plugin/custom-block', array(\n        'editor_script' =&gt; 'editor-script.js',\n        'editor_style'  =&gt; 'editor-style.css',\n        'style'         =&gt; 'frontend.css',\n    ) );\n
      \n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \n"},{"answer_id":397574,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":-1,"selected":false,"text":"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \n"},{"answer_id":402084,"author":"leemon","author_id":33049,"author_profile":"https://wordpress.stackexchange.com/users/33049","pm_score":1,"selected":true,"text":"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \n"}],"string":"[\n {\n \"answer_id\": 397155,\n \"author\": \"Kalimah\",\n \"author_id\": 35871,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/35871\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \\n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \\n
       register_block_type( 'custom-plugin/custom-block', array(\\n        'editor_script' =&gt; 'editor-script.js',\\n        'editor_style'  =&gt; 'editor-style.css',\\n        'style'         =&gt; 'frontend.css',\\n    ) );\\n
      \\n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \\n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \\n\"\n },\n {\n \"answer_id\": 397574,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \\n\"\n },\n {\n \"answer_id\": 402084,\n \"author\": \"leemon\",\n \"author_id\": 33049,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/33049\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \\n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \\n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \\n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \\n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/25"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397316","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214037/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397316\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214037/\"\n]"},"input":{"kind":"string","value":"I want to change WooCommerce pagination links from:\n\n* example.com/category/page/3/ to:\n* example.com/category/3/\n\nI found many examples of how to change '/page/' to '/something/' but I want only the number of the current page. I also tried this:\n\n```php\n$wp_rewrite->pagination_base = ''; \n\n```\n\nBut then my url looks like this:\n\n`example.com/category//3/`\n\nAnd that's not good either. Is it even possible to remove 'pagination base' from url structure?"},"output":{"kind":"string","value":"In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.\n\nBoth `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes.\n\nI have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it.\n\nFinally, the `.edit-post-visual-editor` class targets the whole block editor.\n\nIn summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor."}}},{"rowIdx":7657466,"cells":{"qid":{"kind":"number","value":397380,"string":"397,380"},"question":{"kind":"string","value":"

      I'm performing an wpdb-&gt;insert(). When a field includes a special the insert is not done and I get the error

      \n
      \n

      Error in Wordpress database for query SHOW FULL COLUMNS FROM wp_my_table

      \n
      \n

      If I don't use special characters the insert is done correctly.

      \n

      Apparently, the column collations are correct, but something is wrong. I saw this post answers but as I said my collations seem to be correct.

      \n

      This is my table definition:

      \n
      SHOW CREATE TABLE wp_my_table;\n\nCREATE TABLE `wp_my_table` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `c_name` varchar(50) COLLATE utf8mb4_unicode_520_ci NOT NULL,\n  `creation_date` datetime DEFAULT NULL,\n  PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;\n
      \n

      And this is the insert statement:

      \n
      $wpdb-&gt;insert('wp_my_table', \n             ['c_name'        =&gt; $_POST['c_name'],\n              'creation_date' =&gt; date('Y-m-d H:i:s')\n            ]); \n
      \n

      Adding esc_sql or esc_html didn't help.

      \n

      Actually, error is not in the query or insert itself, but in $_POST['c_name'], because if I call with a hard coded string, the query works properly:

      \n
      $wpdb-&gt;insert('wp_my_table', \n             ['c_name'        =&gt; '1º áá',\n              'creation_date' =&gt; date('Y-m-d H:i:s')\n            ]); \n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":397155,"author":"Kalimah","author_id":35871,"author_profile":"https://wordpress.stackexchange.com/users/35871","pm_score":0,"selected":false,"text":"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \n
       register_block_type( 'custom-plugin/custom-block', array(\n        'editor_script' =&gt; 'editor-script.js',\n        'editor_style'  =&gt; 'editor-style.css',\n        'style'         =&gt; 'frontend.css',\n    ) );\n
      \n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \n"},{"answer_id":397574,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":-1,"selected":false,"text":"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \n"},{"answer_id":402084,"author":"leemon","author_id":33049,"author_profile":"https://wordpress.stackexchange.com/users/33049","pm_score":1,"selected":true,"text":"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \n"}],"string":"[\n {\n \"answer_id\": 397155,\n \"author\": \"Kalimah\",\n \"author_id\": 35871,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/35871\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Searching the editor source code: https://github.com/WordPress/gutenberg does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)

      \\n

      register_block_type is used to add the block date in WordPress. Typically with these arguments:

      \\n
       register_block_type( 'custom-plugin/custom-block', array(\\n        'editor_script' =&gt; 'editor-script.js',\\n        'editor_style'  =&gt; 'editor-style.css',\\n        'style'         =&gt; 'frontend.css',\\n    ) );\\n
      \\n

      editor_script and editor_style add files to editor admin. style is meant to add CSS to frontend.

      \\n

      What documentation does not mention is that style is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.

      \\n\"\n },\n {\n \"answer_id\": 397574,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

      The editor-block-list__block class in only rendered in the Gutenberg editor, while the wp-block-[blockname] class is rendered on both the front end and the editor. So classes prepended with editor-block-list__block are targeting the backend only.

      \\n\"\n },\n {\n \"answer_id\": 402084,\n \"author\": \"leemon\",\n \"author_id\": 33049,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/33049\",\n \"pm_score\": 1,\n \"selected\": true,\n \"text\": \"

      In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.

      \\n

      Both .editor-block-list__layout and .editor-block-list__block classes are deprecated since WordPress 5.4 and have been renamed to .block-editor-block-list__layout and .block-editor-block-list__block, respectively. The .block-editor-block-list__layout class targets all the blocks found in the post content and .block-editor-block-list__block class targets individual block types in the post content, so the latter is equivalent to using the specific .wp-block-*** classes.

      \\n

      I have not seen the .block-library-list class used anywhere in the block editor, so I assume it makes no sense targeting it.

      \\n

      Finally, the .edit-post-visual-editor class targets the whole block editor.

      \\n

      In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the .wp-block-*** classes to style individual block types in the block editor.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/10/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397380","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/17141/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397380\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/17141/\"\n]"},"input":{"kind":"string","value":"I'm performing an `wpdb->insert()`. When a field includes a special the insert is not done and I get the error\n\n> \n> Error in Wordpress database for query SHOW FULL COLUMNS FROM `wp_my_table`\n> \n> \n> \n\nIf I don't use special characters the insert is done correctly.\n\nApparently, the column collations are correct, but something is wrong. I saw this [post answers](https://wordpress.stackexchange.com/questions/246503/wpdb-insert-with-special-characters) but as I said my collations seem to be correct.\n\nThis is my table definition:\n\n```\nSHOW CREATE TABLE wp_my_table;\n\nCREATE TABLE `wp_my_table` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `c_name` varchar(50) COLLATE utf8mb4_unicode_520_ci NOT NULL,\n `creation_date` datetime DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;\n\n```\n\nAnd this is the insert statement:\n\n```\n$wpdb->insert('wp_my_table', \n ['c_name' => $_POST['c_name'],\n 'creation_date' => date('Y-m-d H:i:s')\n ]); \n\n```\n\nAdding `esc_sql` or `esc_html` didn't help.\n\nActually, error is not in the query or insert itself, but in $\\_POST['c\\_name'], because if I call with a hard coded string, the query works properly:\n\n```\n$wpdb->insert('wp_my_table', \n ['c_name' => '1º áá',\n 'creation_date' => date('Y-m-d H:i:s')\n ]); \n\n```"},"output":{"kind":"string","value":"In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.\n\nBoth `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes.\n\nI have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it.\n\nFinally, the `.edit-post-visual-editor` class targets the whole block editor.\n\nIn summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor."}}},{"rowIdx":7657467,"cells":{"qid":{"kind":"number","value":397571,"string":"397,571"},"question":{"kind":"string","value":"

      brand new to WordPress and StackExchange so excuse my poor etiquette. I am making a custom WordPress theme for a class, and somewhere along the line made an error so tiny neither me nor my professor could find it, but it's specifically caused my entire CSS page to not load whatsoever. Through troubleshooting, we figured out it's probably an issue somewhere in the .php files. Does anybody see anything that could be causing such a huge problem? I regret asking so cluelessly for help, but we're stumped!

      \n

      index.html

      \n
      \n\n&lt;?php get_header(); ?&gt;\n&lt;?php get_sidebar(); ?&gt;\n  &lt;div id=&quot;content1&quot;&gt;\n    &lt;article&gt;\n      &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;\n        &lt;h1 id=&quot;post-&lt;?php the_ID(); ?&gt;&quot;&gt;&lt;a href=&quot;&lt;?php the_permalink() ?&gt;&quot; rel=&quot;bookmark&quot; title=&quot;Permanent link to &lt;?php the_title(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n        &lt;?php the_content(); ?&gt;\n        &lt;?php wp_link_pages(); ?&gt;\n      &lt;?php endwhile; ?&gt;\n    &lt;?php endif; ?&gt;\n  &lt;/article&gt;\n&lt;/div&gt;\n&lt;?php get_footer(); ?&gt;\n\n---\n\n
      \n

      header.php

      \n
      \n&lt;html&gt;\n&lt;head&gt;\n  &lt;title&gt; Portfolio&lt;/title&gt;\n  &lt;!-- &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;\n  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;\n  &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Raleway:wght@300&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;\n  &lt;meta name=&quot;description&quot; content=&quot;Our first page&quot;&gt;\n  &lt;meta name=&quot;keywords&quot; content=&quot;html tutorial template&quot;&gt; --&gt;\n  &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n  &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n\n&lt;body &lt;?php body_class(); ?&gt;&gt;\n
      \n

      footer.php, which doesn't have anything especially important

      \n
      &lt;footer&gt;&lt;/footer&gt;\n&lt;/div&gt; &lt;!-- close wrapper --&gt;\n&lt;?php wp_footer(); ?&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n
      \n"},"answers":{"kind":"list like","value":[{"answer_id":397572,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":2,"selected":false,"text":"
      &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
      \n

      Because you're using relative URLs.

      \n

      When you are on example.com it will load example.com/style.css

      \n

      When you are on example.com/test it will load example.com/test/style.css etc etc

      \n

      As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

      \n
      \n

      Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

      \n"},{"answer_id":397576,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":2,"selected":false,"text":"

      As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

      \n

      So in your contexts, that would be:

      \n
      &lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n
      \n

      get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

      \n

      But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

      \n
      function my_custom_enqueue_function(){\n    wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n
      \n

      There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

      \n"},{"answer_id":397578,"author":"Majid A.","author_id":214325,"author_profile":"https://wordpress.stackexchange.com/users/214325","pm_score":0,"selected":false,"text":"

      Check this:

      \n
      &lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
      \n

      If your style.css file on the theme's root directory.

      \n"}],"string":"[\n {\n \"answer_id\": 397572,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"
      &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
      \\n

      Because you're using relative URLs.

      \\n

      When you are on example.com it will load example.com/style.css

      \\n

      When you are on example.com/test it will load example.com/test/style.css etc etc

      \\n

      As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

      \\n
      \\n

      Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

      \\n\"\n },\n {\n \"answer_id\": 397576,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

      As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

      \\n

      So in your contexts, that would be:

      \\n
      &lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\\n
      \\n

      get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

      \\n

      But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

      \\n
      function my_custom_enqueue_function(){\\n    wp_enqueue_style('my-style', get_stylesheet_uri());\\n}\\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\\n
      \\n

      There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

      \\n\"\n },\n {\n \"answer_id\": 397578,\n \"author\": \"Majid A.\",\n \"author_id\": 214325,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214325\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

      Check this:

      \\n
      &lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
      \\n

      If your style.css file on the theme's root directory.

      \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/01"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397571","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214321/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397571\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214321/\"\n]"},"input":{"kind":"string","value":"brand new to WordPress and StackExchange so excuse my poor etiquette. I am making a custom WordPress theme for a class, and somewhere along the line made an error so tiny neither me nor my professor could find it, but it's specifically caused my entire CSS page to not load whatsoever. Through troubleshooting, we figured out it's probably an issue somewhere in the .php files. Does anybody see anything that could be causing such a huge problem? I regret asking so cluelessly for help, but we're stumped!\n\n**index.html**\n\n```\n\n\n\n \n\n\n---\n\n```\n\n**header.php**\n\n```\n\n\n\n Portfolio\n \n \n \n\n\n>\n\n```\n\n**footer.php**, which doesn't have anything especially important\n\n```\n
      \n
\n\n\n\n\n```"},"output":{"kind":"string","value":"```\n\n\n```\n\n***Because you're using relative URLs.***\n\nWhen you are on `example.com` it will load `example.com/style.css`\n\nWhen you are on `example.com/test` it will load `example.com/test/style.css` etc etc\n\nAs you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead.\n\n---\n\nInstead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag."}}},{"rowIdx":7657468,"cells":{"qid":{"kind":"number","value":397644,"string":"397,644"},"question":{"kind":"string","value":"

I ask if it is possible to wrap a specific sidebar within a &lt;div class=&quot;customdiv&quot;&gt;&lt;/div&gt;.\nAre there any instructions to add in the function.php file?\nThank you.

\n

Like this:

\n
I've created this sidebar (which contains widgets):\n    // ATTIVITA - widgets   \n        register_sidebar(\n        array (\n            'name' =&gt; __( 'ATTIVITA prenotabili', 'your-theme-domain' ),\n            'id' =&gt; '&lt;div id=&quot;testimonial-slider&quot;&gt;',\n            'description' =&gt; __( 'ATTIVITA prenotabili', 'your-theme-domain' ),\n            'before_widget' =&gt; '&lt;div class=&quot;widget-content&quot;&gt;',\n            'after_widget' =&gt; '&lt;/div&gt;',\n            'before_title' =&gt; '&lt;h3 class=&quot;widget-title&quot;&gt;',\n            'after_title' =&gt; '&lt;/h3&gt;',\n        )\n    );\n//fine\n
\n

I would like to wrap it into a \nDo you think could it be possible?\nMany thanks.

\n"},"answers":{"kind":"list like","value":[{"answer_id":397572,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":2,"selected":false,"text":"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

Because you're using relative URLs.

\n

When you are on example.com it will load example.com/style.css

\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\n
\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\n"},{"answer_id":397576,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":2,"selected":false,"text":"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\n

So in your contexts, that would be:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\n
function my_custom_enqueue_function(){\n    wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n
\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\n"},{"answer_id":397578,"author":"Majid A.","author_id":214325,"author_profile":"https://wordpress.stackexchange.com/users/214325","pm_score":0,"selected":false,"text":"

Check this:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

If your style.css file on the theme's root directory.

\n"}],"string":"[\n {\n \"answer_id\": 397572,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

Because you're using relative URLs.

\\n

When you are on example.com it will load example.com/style.css

\\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\\n
\\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\\n\"\n },\n {\n \"answer_id\": 397576,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\\n

So in your contexts, that would be:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\\n
function my_custom_enqueue_function(){\\n    wp_enqueue_style('my-style', get_stylesheet_uri());\\n}\\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\\n
\\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\\n\"\n },\n {\n \"answer_id\": 397578,\n \"author\": \"Majid A.\",\n \"author_id\": 214325,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214325\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Check this:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

If your style.css file on the theme's root directory.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397644","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214375/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397644\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214375/\"\n]"},"input":{"kind":"string","value":"I ask if it is possible to wrap a specific sidebar within a `
`.\nAre there any instructions to add in the function.php file?\nThank you.\n\nLike this:\n\n```\nI've created this sidebar (which contains widgets):\n // ATTIVITA - widgets \n register_sidebar(\n array (\n 'name' => __( 'ATTIVITA prenotabili', 'your-theme-domain' ),\n 'id' => '
',\n 'description' => __( 'ATTIVITA prenotabili', 'your-theme-domain' ),\n 'before_widget' => '
',\n 'after_widget' => '
',\n 'before_title' => '

',\n 'after_title' => '

',\n )\n );\n//fine\n\n```\n\nI would like to wrap it into a \nDo you think could it be possible?\nMany thanks."},"output":{"kind":"string","value":"```\n\n\n```\n\n***Because you're using relative URLs.***\n\nWhen you are on `example.com` it will load `example.com/style.css`\n\nWhen you are on `example.com/test` it will load `example.com/test/style.css` etc etc\n\nAs you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead.\n\n---\n\nInstead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag."}}},{"rowIdx":7657469,"cells":{"qid":{"kind":"number","value":397668,"string":"397,668"},"question":{"kind":"string","value":"

I am having a bit of a weird glitch happening to me and I am not sure how I have produced it or whether it is the norm.

\n

I am developing my own plugin and when a football/soccer team is typed into a box it will check if its in the database already or not.

\n

Here are my lines of code

\n
add_action( 'admin_footer', 'fws_teamcheck_javascript' );\nfunction fws_teamcheck_javascript() { ?&gt;\n&lt;script type=&quot;text/javascript&quot;&gt;\n    jQuery(document).on('focusout', '.name', function () {\n        var name = this.value;\n        //alert(name);\n        jQuery.ajax({\n            type: 'POST',\n            url: ajaxurl,\n            data: {&quot;action&quot;: &quot;fws_check_name&quot;, &quot;name&quot;: name},\n            success: function (data) {\n                alert(data);\n                if(data=='true') {\n                    $(&quot;.name&quot;).css(&quot;border&quot;, &quot;solid 1px red&quot;);\n                }\n                if(data=='false') {\n                    $(&quot;.name&quot;).css(&quot;border&quot;, &quot;solid 1px green&quot;);\n                }\n            }\n        });\n    });\n&lt;/script&gt;\n&lt;?\n}\n\nfunction fws_check_name(){\n    global $wpdb;\n    $dbtable = $wpdb-&gt;prefix . 'fws_team_data';\n    $name = $_POST['name'];\n    $data = $wpdb-&gt;get_results($wpdb-&gt;prepare(&quot;SELECT * FROM $dbtable WHERE name = $name&quot;));\n    if($data) { echo 'true'; }else{ echo 'false'; }\n    \n}\nadd_action( 'wp_ajax_fws_check_name', 'fws_check_name' );\nadd_action( 'wp_ajax_nopriv_fws_check_name', 'fws_check_name' );\n
\n

When i move away from the input it will bring up the alert as either true0 or false0 is there a reason why it is adding the 0 at the end?

\n

Thanks for your input.

\n"},"answers":{"kind":"list like","value":[{"answer_id":397572,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":2,"selected":false,"text":"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

Because you're using relative URLs.

\n

When you are on example.com it will load example.com/style.css

\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\n
\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\n"},{"answer_id":397576,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":2,"selected":false,"text":"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\n

So in your contexts, that would be:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\n
function my_custom_enqueue_function(){\n    wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n
\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\n"},{"answer_id":397578,"author":"Majid A.","author_id":214325,"author_profile":"https://wordpress.stackexchange.com/users/214325","pm_score":0,"selected":false,"text":"

Check this:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

If your style.css file on the theme's root directory.

\n"}],"string":"[\n {\n \"answer_id\": 397572,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

Because you're using relative URLs.

\\n

When you are on example.com it will load example.com/style.css

\\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\\n
\\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\\n\"\n },\n {\n \"answer_id\": 397576,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\\n

So in your contexts, that would be:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\\n
function my_custom_enqueue_function(){\\n    wp_enqueue_style('my-style', get_stylesheet_uri());\\n}\\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\\n
\\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\\n\"\n },\n {\n \"answer_id\": 397578,\n \"author\": \"Majid A.\",\n \"author_id\": 214325,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214325\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Check this:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

If your style.css file on the theme's root directory.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/03"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397668","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214284/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397668\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214284/\"\n]"},"input":{"kind":"string","value":"I am having a bit of a weird glitch happening to me and I am not sure how I have produced it or whether it is the norm.\n\nI am developing my own plugin and when a football/soccer team is typed into a box it will check if its in the database already or not.\n\nHere are my lines of code\n\n```\nadd_action( 'admin_footer', 'fws_teamcheck_javascript' );\nfunction fws_teamcheck_javascript() { ?>\n\nprefix . 'fws_team_data';\n $name = $_POST['name'];\n $data = $wpdb->get_results($wpdb->prepare(\"SELECT * FROM $dbtable WHERE name = $name\"));\n if($data) { echo 'true'; }else{ echo 'false'; }\n\n}\nadd_action( 'wp_ajax_fws_check_name', 'fws_check_name' );\nadd_action( 'wp_ajax_nopriv_fws_check_name', 'fws_check_name' );\n\n```\n\nWhen i move away from the input it will bring up the alert as either `true0` or `false0` is there a reason why it is adding the 0 at the end?\n\nThanks for your input."},"output":{"kind":"string","value":"```\n\n\n```\n\n***Because you're using relative URLs.***\n\nWhen you are on `example.com` it will load `example.com/style.css`\n\nWhen you are on `example.com/test` it will load `example.com/test/style.css` etc etc\n\nAs you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead.\n\n---\n\nInstead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag."}}},{"rowIdx":7657470,"cells":{"qid":{"kind":"number","value":397814,"string":"397,814"},"question":{"kind":"string","value":"

I have 4 roles in my platform : administrator, author, editor, external

\n

I need to restrict WordPress media library access to the user’s own uploads only for one users role (external) on my platform. The External user role can only see/select his own media.

\n

All others roles still have access to all medias in the library.

\n

I found the below snippets but it works for all the users :

\n
&lt;?php // Limit access to media library (users can only see/select own media) //\n   add_filter( 'ajax_query_attachments_args', 'wpsnippet_show_current_user_attachments' );\n   function wpsnippet_show_current_user_attachments( $query ) {\n      $user_id = get_current_user_id();\n      if ( $user_id &amp;&amp; !current_user_can('activate_plugins') &amp;&amp; !current_user_can('edit_others_posts')) {\n         $query['author'] = $user_id;\n      }\n      return $query;\n   }\n?&gt;\n
\n

Thanks in advance for your reply.

\n"},"answers":{"kind":"list like","value":[{"answer_id":397572,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":2,"selected":false,"text":"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

Because you're using relative URLs.

\n

When you are on example.com it will load example.com/style.css

\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\n
\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\n"},{"answer_id":397576,"author":"StudioAl","author_id":37377,"author_profile":"https://wordpress.stackexchange.com/users/37377","pm_score":2,"selected":false,"text":"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\n

So in your contexts, that would be:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\n
function my_custom_enqueue_function(){\n    wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n
\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\n"},{"answer_id":397578,"author":"Majid A.","author_id":214325,"author_profile":"https://wordpress.stackexchange.com/users/214325","pm_score":0,"selected":false,"text":"

Check this:

\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n
\n

If your style.css file on the theme's root directory.

\n"}],"string":"[\n {\n \"answer_id\": 397572,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"
&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

Because you're using relative URLs.

\\n

When you are on example.com it will load example.com/style.css

\\n

When you are on example.com/test it will load example.com/test/style.css etc etc

\\n

As you move around the site, it will change where it's looking. None of your pages ever referenced your style.css, it's probably returning an empty 404 page instead.

\\n
\\n

Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.

\\n\"\n },\n {\n \"answer_id\": 397576,\n \"author\": \"StudioAl\",\n \"author_id\": 37377,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/37377\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

As stated, href=&quot;style.css&quot; is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.

\\n

So in your contexts, that would be:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

get_stylesheet_uri() will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it style.css.

\\n

But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your header.php file, you'd enqueue in your functions.php file like this:

\\n
function my_custom_enqueue_function(){\\n    wp_enqueue_style('my-style', get_stylesheet_uri());\\n}\\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\\n
\\n

There are more attributes, not in that example, to the wp_enqueue_style() function that make it even more useful, so it's worth looking up and getting to know.

\\n\"\n },\n {\n \"answer_id\": 397578,\n \"author\": \"Majid A.\",\n \"author_id\": 214325,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214325\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

Check this:

\\n
&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\\n
\\n

If your style.css file on the theme's root directory.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/07"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397814","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/119785/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397814\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/119785/\"\n]"},"input":{"kind":"string","value":"I have 4 roles in my platform : administrator, author, editor, external\n\nI need to restrict WordPress media library access to the user’s own uploads only for one users role (**external**) on my platform. **The External user role can only see/select his own media**.\n\nAll others roles still have access to all medias in the library.\n\nI found the below snippets but it works for all the users :\n\n```\n\n\n```\n\nThanks in advance for your reply."},"output":{"kind":"string","value":"```\n\n\n```\n\n***Because you're using relative URLs.***\n\nWhen you are on `example.com` it will load `example.com/style.css`\n\nWhen you are on `example.com/test` it will load `example.com/test/style.css` etc etc\n\nAs you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead.\n\n---\n\nInstead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag."}}},{"rowIdx":7657471,"cells":{"qid":{"kind":"number","value":397860,"string":"397,860"},"question":{"kind":"string","value":"

Not sure the best way to describe this, but basically I am defining a variable ($cat) which chooses a taxonomy based on a number defined just before the query is called, but as the number is defined AFTER the args I can't figure out how to get it to work. I know I could just duplicate the whole query for each taxonomy I want, but I was hoping there was a less character-heavy way to do this.

\n

Current code:

\n
//cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage)\nif ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; }\nif ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; }\nif ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; }\nif ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; }\nif ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; }\nif ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; }\nif ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; }\nif ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; }\nif ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; }\nif ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; }\nif ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; }\nif ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; }\nif ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; }\n//that 'get_option' outputs as the plain ID of the taxonomy\n\n//args &amp; query\n$args_cat = array( \n   'post_type' =&gt; $post_types,\n   'posts_per_page' =&gt; 3,\n   'fields' =&gt; 'ids',\n   'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n   'tax_query' =&gt; array( \n      'relation' =&gt; 'AND',\n      array(\n         'taxonomy' =&gt; 'sector',\n         'field' =&gt; 'id',\n         'terms' =&gt; $sector\n      )\n   )\n);\n$cat_query = new WP_Query( $args_cat );\n\n//choosing the category and hoping to run the query with it (not working)\n$cat = 1;\nwhile ( $cat_query-&gt;have_posts() ) { \n   $cat_query-&gt;the_post();\n   get_template_part( 'template-parts/posts/content', get_post_type() );\n   wp_reset_postdata();\n}\n
\n

So it's like I'm wanting it to go back up to the top of the page and choose the cat based on the number, then run the query with that option, but I just can't figure it out. Running it as-is returns 'terms' =&gt; NULL. Do I need a reset or a return or something?

\n

Any help greatly appreciated.

\n

By the way, I know I could do it like this for each tax/query:

\n
$sector = get_option('b4_settings_homepage_category_1')[0];\n$args_cat = array( \n   'post_type' =&gt; $post_types,\n   'posts_per_page' =&gt; 3,\n   'fields' =&gt; 'ids',\n   'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n   'tax_query' =&gt; array(\n      'relation' =&gt; 'AND',\n      array( \n         'taxonomy' =&gt; 'sector',\n         'field' =&gt; 'id',\n         'terms' =&gt; $sector\n      )\n   )\n);\n$cat_query = new WP_Query( $args_cat );\nwhile ( $cat_query-&gt;have_posts() ) {\n$cat_query-&gt;the_post(); \netc etc\n
\n

But I really don't want to have that query replicated a bunch of times if it can be avoided...

\n"},"answers":{"kind":"list like","value":[{"answer_id":397864,"author":"Peter Petrov","author_id":124071,"author_profile":"https://wordpress.stackexchange.com/users/124071","pm_score":0,"selected":false,"text":"

To reduce code repetition, you could introduce a function. The below code example is a reworked version of the code you provided, but it uses a function. If you want to use this for category 2, simply call the function with the argument 2.

\n

Please note, that you'll need to declare the variables you're using at the beginning of the function. Also - the get_option function, could return more than just an array, which would cause a notice.

\n
$cat_query = prefix_get_wp_query(1);\nwhile ( $cat_query-&gt;have_posts() ) {\n    $cat_query-&gt;the_post();\n    get_template_part( 'template-parts/posts/content', get_post_type() );\n    wp_reset_postdata();\n}\n\nfunction prefix_get_wp_query( $cat ) {\n    // declare $post_types, $feat_ids, $latest_ids and $trend_ids below this line\n\n    //cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage)\n    if ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; }\n    if ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; }\n    if ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; }\n    if ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; }\n    if ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; }\n    if ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; }\n    if ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; }\n    if ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; }\n    if ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; }\n    if ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; }\n    if ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; }\n    if ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; }\n    if ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; }\n    //that 'get_option' outputs as the plain ID of the taxonomy\n\n    //args &amp; query\n    $args_cat = array(\n        'post_type'      =&gt; $post_types,\n        'posts_per_page' =&gt; 3,\n        'fields'         =&gt; 'ids',\n        'post__not_in'   =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n        'tax_query'      =&gt; array(\n            'relation' =&gt; 'AND',\n            array(\n                'taxonomy' =&gt; 'sector',\n                'field'    =&gt; 'id',\n                'terms'    =&gt; $sector\n            )\n        )\n    );\n\n    return new WP_Query( $args_cat );\n}\n
\n"},{"answer_id":397990,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

if your second code works correctly, just do this

\n
$option = &quot;b4_settings_homepage_category_&quot;.$cat;\n$sector = get_option($option)[0];\n
\n

this will make your option with the cat variable, for example b4_settings_homepage_category_7 , is the same as the if statment but more elegant. also your first code probably isnt working just because the $cat variable should be before the if statments, not after.

\n

so the inteire code should be:

\n
$cat = 7;\n$option = &quot;b4_settings_homepage_category_&quot;.$cat;\n$sector = get_option($option)[0];\n$args_cat = array(\n   'post_type' =&gt; $post_types,\n   'posts_per_page' =&gt; 3,\n   'fields' =&gt; 'ids',\n   'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n   'tax_query' =&gt; array(\n      'relation' =&gt; 'AND',\n      array(\n         'taxonomy' =&gt; 'sector',\n         'field' =&gt; 'id',\n         'terms' =&gt; $sector\n      )\n   )\n);\n$cat_query = new WP_Query( $args_cat );\nwhile ( $cat_query-&gt;have_posts() ) {\n    $cat_query-&gt;the_post();\n    // etc etc\n}\n
\n"},{"answer_id":398002,"author":"ukijake","author_id":214570,"author_profile":"https://wordpress.stackexchange.com/users/214570","pm_score":2,"selected":true,"text":"

Combining Petar's function and Tiago's shortened option syntax, this works:

\n

In template:

\n
//once, in header:\n$i = 0;\n\n//anytime I want to run the query:\n$i++;\n$cat_query = prefix_get_wp_query($i);\n while ( $cat_query-&gt;have_posts() ) {\n  $cat_query-&gt;the_post();\n  get_template_part( 'template-parts/posts/content', get_post_type() );\n  wp_reset_postdata();\n}\n
\n

In functions:

\n
function prefix_get_wp_query( $i ) {\n if ( $i &gt; 0 ) { \n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n  $sector = get_option($cat)[0];\n }\n $cat_args = [\n  'post_type'      =&gt; $post_types,\n  'posts_per_page' =&gt; 3,\n  'fields'         =&gt; 'ids',\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n  'tax_query'      =&gt; [\n   'relation' =&gt; 'AND',\n    [ 'taxonomy' =&gt; 'sector',\n      'field'    =&gt; 'id',\n      'terms'    =&gt; $sector\n    ]\n   ]\n  ];\n  return new WP_Query( $cat_args );\n}\n
\n

Thanks very much!!

\n"},{"answer_id":398006,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

your right answer could find an issue, when $i is less or equal to zero will trow an error, that $sector is being used by the first time, so one way to prevent that is

\n
function prefix_get_wp_query( $i ) {\n if ( $i &gt; 0 ) { \n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n  $sector = get_option($cat)[0];\n  $cat_args = [\n  'post_type'      =&gt; $post_types,\n  'posts_per_page' =&gt; 3,\n  'fields'         =&gt; 'ids',\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n  'tax_query'      =&gt; [\n   'relation' =&gt; 'AND',\n    [ 'taxonomy' =&gt; 'sector',\n      'field'    =&gt; 'id',\n      'terms'    =&gt; $sector\n    ]\n   ]\n  ];\n  return new WP_Query( $cat_args );\n } else {\n  return 0;\n }\n}\n
\n

if you know it will always be greater than 0, the if can be simply removed

\n
function prefix_get_wp_query( $i ) {\n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n  $sector = get_option($cat)[0];\n  $cat_args = [\n  'post_type'      =&gt; $post_types,\n  'posts_per_page' =&gt; 3,\n  'fields'         =&gt; 'ids',\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n  'tax_query'      =&gt; [\n   'relation' =&gt; 'AND',\n    [ 'taxonomy' =&gt; 'sector',\n      'field'    =&gt; 'id',\n      'terms'    =&gt; $sector\n    ]\n   ]\n  ];\n  return new WP_Query( $cat_args );\n}\n
\n"}],"string":"[\n {\n \"answer_id\": 397864,\n \"author\": \"Peter Petrov\",\n \"author_id\": 124071,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/124071\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

To reduce code repetition, you could introduce a function. The below code example is a reworked version of the code you provided, but it uses a function. If you want to use this for category 2, simply call the function with the argument 2.

\\n

Please note, that you'll need to declare the variables you're using at the beginning of the function. Also - the get_option function, could return more than just an array, which would cause a notice.

\\n
$cat_query = prefix_get_wp_query(1);\\nwhile ( $cat_query-&gt;have_posts() ) {\\n    $cat_query-&gt;the_post();\\n    get_template_part( 'template-parts/posts/content', get_post_type() );\\n    wp_reset_postdata();\\n}\\n\\nfunction prefix_get_wp_query( $cat ) {\\n    // declare $post_types, $feat_ids, $latest_ids and $trend_ids below this line\\n\\n    //cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage)\\n    if ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; }\\n    if ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; }\\n    if ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; }\\n    if ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; }\\n    if ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; }\\n    if ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; }\\n    if ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; }\\n    if ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; }\\n    if ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; }\\n    if ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; }\\n    if ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; }\\n    if ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; }\\n    if ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; }\\n    //that 'get_option' outputs as the plain ID of the taxonomy\\n\\n    //args &amp; query\\n    $args_cat = array(\\n        'post_type'      =&gt; $post_types,\\n        'posts_per_page' =&gt; 3,\\n        'fields'         =&gt; 'ids',\\n        'post__not_in'   =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\\n        'tax_query'      =&gt; array(\\n            'relation' =&gt; 'AND',\\n            array(\\n                'taxonomy' =&gt; 'sector',\\n                'field'    =&gt; 'id',\\n                'terms'    =&gt; $sector\\n            )\\n        )\\n    );\\n\\n    return new WP_Query( $args_cat );\\n}\\n
\\n\"\n },\n {\n \"answer_id\": 397990,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

if your second code works correctly, just do this

\\n
$option = &quot;b4_settings_homepage_category_&quot;.$cat;\\n$sector = get_option($option)[0];\\n
\\n

this will make your option with the cat variable, for example b4_settings_homepage_category_7 , is the same as the if statment but more elegant. also your first code probably isnt working just because the $cat variable should be before the if statments, not after.

\\n

so the inteire code should be:

\\n
$cat = 7;\\n$option = &quot;b4_settings_homepage_category_&quot;.$cat;\\n$sector = get_option($option)[0];\\n$args_cat = array(\\n   'post_type' =&gt; $post_types,\\n   'posts_per_page' =&gt; 3,\\n   'fields' =&gt; 'ids',\\n   'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\\n   'tax_query' =&gt; array(\\n      'relation' =&gt; 'AND',\\n      array(\\n         'taxonomy' =&gt; 'sector',\\n         'field' =&gt; 'id',\\n         'terms' =&gt; $sector\\n      )\\n   )\\n);\\n$cat_query = new WP_Query( $args_cat );\\nwhile ( $cat_query-&gt;have_posts() ) {\\n    $cat_query-&gt;the_post();\\n    // etc etc\\n}\\n
\\n\"\n },\n {\n \"answer_id\": 398002,\n \"author\": \"ukijake\",\n \"author_id\": 214570,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214570\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

Combining Petar's function and Tiago's shortened option syntax, this works:

\\n

In template:

\\n
//once, in header:\\n$i = 0;\\n\\n//anytime I want to run the query:\\n$i++;\\n$cat_query = prefix_get_wp_query($i);\\n while ( $cat_query-&gt;have_posts() ) {\\n  $cat_query-&gt;the_post();\\n  get_template_part( 'template-parts/posts/content', get_post_type() );\\n  wp_reset_postdata();\\n}\\n
\\n

In functions:

\\n
function prefix_get_wp_query( $i ) {\\n if ( $i &gt; 0 ) { \\n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\\n  $sector = get_option($cat)[0];\\n }\\n $cat_args = [\\n  'post_type'      =&gt; $post_types,\\n  'posts_per_page' =&gt; 3,\\n  'fields'         =&gt; 'ids',\\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\\n  'tax_query'      =&gt; [\\n   'relation' =&gt; 'AND',\\n    [ 'taxonomy' =&gt; 'sector',\\n      'field'    =&gt; 'id',\\n      'terms'    =&gt; $sector\\n    ]\\n   ]\\n  ];\\n  return new WP_Query( $cat_args );\\n}\\n
\\n

Thanks very much!!

\\n\"\n },\n {\n \"answer_id\": 398006,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

your right answer could find an issue, when $i is less or equal to zero will trow an error, that $sector is being used by the first time, so one way to prevent that is

\\n
function prefix_get_wp_query( $i ) {\\n if ( $i &gt; 0 ) { \\n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\\n  $sector = get_option($cat)[0];\\n  $cat_args = [\\n  'post_type'      =&gt; $post_types,\\n  'posts_per_page' =&gt; 3,\\n  'fields'         =&gt; 'ids',\\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\\n  'tax_query'      =&gt; [\\n   'relation' =&gt; 'AND',\\n    [ 'taxonomy' =&gt; 'sector',\\n      'field'    =&gt; 'id',\\n      'terms'    =&gt; $sector\\n    ]\\n   ]\\n  ];\\n  return new WP_Query( $cat_args );\\n } else {\\n  return 0;\\n }\\n}\\n
\\n

if you know it will always be greater than 0, the if can be simply removed

\\n
function prefix_get_wp_query( $i ) {\\n  $cat = &quot;b4_settings_homepage_category_&quot;.$i;\\n  $sector = get_option($cat)[0];\\n  $cat_args = [\\n  'post_type'      =&gt; $post_types,\\n  'posts_per_page' =&gt; 3,\\n  'fields'         =&gt; 'ids',\\n  'post__not_in'   =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\\n  'tax_query'      =&gt; [\\n   'relation' =&gt; 'AND',\\n    [ 'taxonomy' =&gt; 'sector',\\n      'field'    =&gt; 'id',\\n      'terms'    =&gt; $sector\\n    ]\\n   ]\\n  ];\\n  return new WP_Query( $cat_args );\\n}\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/08"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397860","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214570/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397860\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214570/\"\n]"},"input":{"kind":"string","value":"Not sure the best way to describe this, but basically I am defining a variable ($cat) which chooses a taxonomy based on a number defined just before the query is called, but as the number is defined AFTER the args I can't figure out how to get it to work. I know I could just duplicate the whole query for each taxonomy I want, but I was hoping there was a less character-heavy way to do this.\n\nCurrent code:\n\n```\n//cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage)\nif ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; }\nif ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; }\nif ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; }\nif ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; }\nif ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; }\nif ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; }\nif ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; }\nif ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; }\nif ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; }\nif ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; }\nif ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; }\nif ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; }\nif ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; }\n//that 'get_option' outputs as the plain ID of the taxonomy\n\n//args & query\n$args_cat = array( \n 'post_type' => $post_types,\n 'posts_per_page' => 3,\n 'fields' => 'ids',\n 'post__not_in' => array( $feat_ids, $latest_ids, $trend_ids ),\n 'tax_query' => array( \n 'relation' => 'AND',\n array(\n 'taxonomy' => 'sector',\n 'field' => 'id',\n 'terms' => $sector\n )\n )\n);\n$cat_query = new WP_Query( $args_cat );\n\n//choosing the category and hoping to run the query with it (not working)\n$cat = 1;\nwhile ( $cat_query->have_posts() ) { \n $cat_query->the_post();\n get_template_part( 'template-parts/posts/content', get_post_type() );\n wp_reset_postdata();\n}\n\n```\n\nSo it's like I'm wanting it to go back up to the top of the page and choose the cat based on the number, then run the query with that option, but I just can't figure it out. Running it as-is returns 'terms' => NULL. Do I need a reset or a return or something?\n\nAny help greatly appreciated.\n\nBy the way, I know I could do it like this for each tax/query:\n\n```\n$sector = get_option('b4_settings_homepage_category_1')[0];\n$args_cat = array( \n 'post_type' => $post_types,\n 'posts_per_page' => 3,\n 'fields' => 'ids',\n 'post__not_in' => array( $feat_ids, $latest_ids, $trend_ids ),\n 'tax_query' => array(\n 'relation' => 'AND',\n array( \n 'taxonomy' => 'sector',\n 'field' => 'id',\n 'terms' => $sector\n )\n )\n);\n$cat_query = new WP_Query( $args_cat );\nwhile ( $cat_query->have_posts() ) {\n$cat_query->the_post(); \netc etc\n\n```\n\nBut I really don't want to have that query replicated a bunch of times if it can be avoided..."},"output":{"kind":"string","value":"Combining Petar's function and Tiago's shortened option syntax, this works:\n\nIn template:\n\n```\n//once, in header:\n$i = 0;\n\n//anytime I want to run the query:\n$i++;\n$cat_query = prefix_get_wp_query($i);\n while ( $cat_query->have_posts() ) {\n $cat_query->the_post();\n get_template_part( 'template-parts/posts/content', get_post_type() );\n wp_reset_postdata();\n}\n\n```\n\nIn functions:\n\n```\nfunction prefix_get_wp_query( $i ) {\n if ( $i > 0 ) { \n $cat = \"b4_settings_homepage_category_\".$i;\n $sector = get_option($cat)[0];\n }\n $cat_args = [\n 'post_type' => $post_types,\n 'posts_per_page' => 3,\n 'fields' => 'ids',\n 'post__not_in' => [ $feat_ids, $latest_ids, $trend_ids ],\n 'tax_query' => [\n 'relation' => 'AND',\n [ 'taxonomy' => 'sector',\n 'field' => 'id',\n 'terms' => $sector\n ]\n ]\n ];\n return new WP_Query( $cat_args );\n}\n\n```\n\nThanks very much!!"}}},{"rowIdx":7657472,"cells":{"qid":{"kind":"number","value":397862,"string":"397,862"},"question":{"kind":"string","value":"

When WordPress is installed, it sends a notification

\n
New WordPress Site\nYour new WordPress site has been successfully set up at:\n...\n
\n

I would like to change the text of the e-mail but am not successfull.\nHere is what I tried:

\n

I added the following code to the main file of a plugin which I add before the installation

\n
function changed_install_mail($installed_email, $user, $blog_title, $blog_url, $password ) {\n    $installed_email['subject'] = 'test';\n    return $installed_email;\n}\nadd_filter( 'wp_installed_email', 'changed_install_mail', 10, 5 );\n
\n

I tried to play around with the priority, but the filter never gets added.\nBut other code in this plugin file is executed.

\n

This filter gets applied in upgrade.php

\n
$installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password );\n\n\n
\n

Maybe it's the wrong time or wrong location I'm trying it?

\n"},"answers":{"kind":"list like","value":[{"answer_id":397988,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php

\n"},{"answer_id":398046,"author":"parvaneh","author_id":132518,"author_profile":"https://wordpress.stackexchange.com/users/132518","pm_score":3,"selected":true,"text":"

I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\nhttps://wordpress.org/support/article/must-use-plugins/\nThis did the trick.

\n"}],"string":"[\n {\n \"answer_id\": 397988,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php

\\n\"\n },\n {\n \"answer_id\": 398046,\n \"author\": \"parvaneh\",\n \"author_id\": 132518,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/132518\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

I found a solution:\\nmu-plugins.\\nMy code isn't executed in this early state, but that's what mu-plugins are for.\\nhttps://wordpress.org/support/article/must-use-plugins/\\nThis did the trick.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/08"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397862","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/132518/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397862\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/132518/\"\n]"},"input":{"kind":"string","value":"When WordPress is installed, it sends a notification\n\n```\nNew WordPress Site\nYour new WordPress site has been successfully set up at:\n...\n\n```\n\nI would like to change the text of the e-mail but am not successfull.\nHere is what I tried:\n\nI added the following code to the main file of a plugin which I add before the installation\n\n```\nfunction changed_install_mail($installed_email, $user, $blog_title, $blog_url, $password ) {\n $installed_email['subject'] = 'test';\n return $installed_email;\n}\nadd_filter( 'wp_installed_email', 'changed_install_mail', 10, 5 );\n\n```\n\nI tried to play around with the priority, but the filter never gets added.\nBut other code in this plugin file is executed.\n\nThis filter gets applied in upgrade.php\n\n```\n$installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password );\n\n```\n\nMaybe it's the wrong time or wrong location I'm trying it?"},"output":{"kind":"string","value":"I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\n\nThis did the trick."}}},{"rowIdx":7657473,"cells":{"qid":{"kind":"number","value":397873,"string":"397,873"},"question":{"kind":"string","value":"

I'm taking a Udemy class to learn how to make Wordpress plugins and themes. The video I'm on is having me override the default search widget with a custom one via searchform.php. From what I've gathered, this file should automatically be loaded with the rest of the theme as long as I have followed these steps:

\n

/theme_dir/functions.php

\n
/* Some other code */\ninclude ( get_theme_file_path('/includes/widgets.php') );\nadd_action(&quot;widgets_init&quot;, 'ju_widgets');\n
\n

/theme_dir/includes/widgets.php

\n
function ju_widgets() {\n    register_sidebar([\n        'name'          =&gt; __('My First Theme Sidebar', 'udemy'),\n        'id'            =&gt; 'ju_sidebar',\n        'description'   =&gt; __('Sidebar for the theme Udemy', 'udemy'),\n        'before_widget' =&gt; '&lt;div id=&quot;%1$s&quot; class=&quot;widget clearfix %2$s&quot;&gt;',\n        'after_widget'  =&gt; '&lt;/div&gt;',\n        'before_title'  =&gt; '&lt;h4&gt;',\n        'after_title'   =&gt; '&lt;/h4&gt;',\n    ]);\n}\n
\n

/theme_dir/sidebar.php

\n
&lt;div class=&quot;sidebar nobottommargin col_last&quot;&gt;\n    &lt;div class=&quot;sidebar-widgets-wrap&quot;&gt;\n        &lt;?php\n            if (is_active_sidebar('ju_sidebar')) {\n                dynamic_sidebar('ju_sidebar');\n            }\n        ?&gt;\n    &lt;/div&gt;\n&lt;/div&gt;\n
\n

/theme_dir/searchform.php

\n
&lt;?php $unique_id = esc_attr( uniqid( 'search-form-' ) ); ?&gt;\n\n&lt;form role=&quot;search&quot; method=&quot;get&quot; class=&quot;search-form&quot;\n      action=&quot;&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;&quot;&gt;\n    &lt;div class=&quot;input-group&quot;&gt;\n        &lt;input type=&quot;search&quot; id=&quot;&lt;?php echo $unique_id; ?&gt;&quot;\n               class=&quot;form-control&quot; name=&quot;s&quot;\n               value=&quot;&lt;?php the_search_query(); ?&gt;&quot;\n               placeholder=&quot;&lt;?php _e( 'Search', 'udemy' ); ?&gt;&quot;/&gt;\n        &lt;span class=&quot;input-group-btn&quot;&gt;\n            &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot;&gt;&lt;i class=&quot;icon-search&quot;&gt;&lt;/i&gt;&lt;/button&gt;\n        &lt;/span&gt;\n    &lt;/div&gt;\n&lt;/form&gt;\n
\n

/theme_dir/index.php

\n
&lt;!-- some theme html --&gt;\n\n&lt;?php get_sidebar(); ?&gt;\n\n&lt;!-- other theme html --&gt;\n\n
\n

No matter what I change in the searchform.php file, it doesn't replace the default search widget.

\n"},"answers":{"kind":"list like","value":[{"answer_id":397988,"author":"tiago calado","author_id":198152,"author_profile":"https://wordpress.stackexchange.com/users/198152","pm_score":0,"selected":false,"text":"

just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php

\n"},{"answer_id":398046,"author":"parvaneh","author_id":132518,"author_profile":"https://wordpress.stackexchange.com/users/132518","pm_score":3,"selected":true,"text":"

I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\nhttps://wordpress.org/support/article/must-use-plugins/\nThis did the trick.

\n"}],"string":"[\n {\n \"answer_id\": 397988,\n \"author\": \"tiago calado\",\n \"author_id\": 198152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/198152\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php

\\n\"\n },\n {\n \"answer_id\": 398046,\n \"author\": \"parvaneh\",\n \"author_id\": 132518,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/132518\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

I found a solution:\\nmu-plugins.\\nMy code isn't executed in this early state, but that's what mu-plugins are for.\\nhttps://wordpress.org/support/article/must-use-plugins/\\nThis did the trick.

\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/08"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397873","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214581/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397873\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214581/\"\n]"},"input":{"kind":"string","value":"I'm taking a Udemy class to learn how to make Wordpress plugins and themes. The video I'm on is having me override the default search widget with a custom one via searchform.php. From what I've gathered, this file should automatically be loaded with the rest of the theme as long as I have followed these steps:\n\n/theme\\_dir/functions.php\n\n```\n/* Some other code */\ninclude ( get_theme_file_path('/includes/widgets.php') );\nadd_action(\"widgets_init\", 'ju_widgets');\n\n```\n\n/theme\\_dir/includes/widgets.php\n\n```\nfunction ju_widgets() {\n register_sidebar([\n 'name' => __('My First Theme Sidebar', 'udemy'),\n 'id' => 'ju_sidebar',\n 'description' => __('Sidebar for the theme Udemy', 'udemy'),\n 'before_widget' => '
',\n 'after_widget' => '
',\n 'before_title' => '

',\n 'after_title' => '

',\n ]);\n}\n\n```\n\n/theme\\_dir/sidebar.php\n\n```\n
\n
\n \n
\n
\n\n```\n\n/theme\\_dir/searchform.php\n\n```\n\n\n
\">\n
\n \"\n class=\"form-control\" name=\"s\"\n value=\"\"\n placeholder=\"\"/>\n \n \n \n
\n
\n\n```\n\n/theme\\_dir/index.php\n\n```\n\n\n\n\n\n\n```\n\nNo matter what I change in the searchform.php file, it doesn't replace the default search widget."},"output":{"kind":"string","value":"I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\n\nThis did the trick."}}},{"rowIdx":7657474,"cells":{"qid":{"kind":"number","value":397957,"string":"397,957"},"question":{"kind":"string","value":"

I have a Quiz block that contains Questions blocks that have Answer blocks. Both Quiz and Question use InnerBlocks to allow questions or answers to be dragged around, edited and saved.

\n

When I save the Quiz, how can I get the index of each question in question/save.js and the index of each question and answer in each answer/save.js.

\n

I would like this so I can give all checkbox unique ids, like

\n
&lt;input id=&quot;q1-a3&quot; /&gt;\n
\n

And label the questions things like &quot;Question 1.&quot;

\n

Quiz/save.js

\n
return (\n  &lt;div {...blockProps}&gt;\n    &lt;InnerBlocks.Content /&gt;\n  &lt;/div&gt;\n);\n
\n

Question/save.js

\n
return (\n  &lt;div {...blockProps}&gt;\n    &lt;h3&gt;Question {numToWords(1)}&lt;/h3&gt;\n    &lt;ul class=&quot;quiz--answers&quot;&gt;\n      &lt;InnerBlocks.Content /&gt;\n    &lt;/ul&gt;\n  &lt;/div&gt;\n);\n
\n

Answer/save.js

\n
return (\n  &lt;li {...blockProps}&gt;\n    &lt;input id=&quot;checkbox-2&quot; type=&quot;checkbox&quot; value=&quot;checkbox-2&quot; /&gt;\n    &lt;label class=&quot;checkbox&quot; for=&quot;checkbox-2&quot;&gt;\n      {JSON.stringify(attributes)}\n      {attributes.text}\n      &lt;span class=&quot;quiz--answer-content&quot;&gt;{attributes.explanation}&lt;/span&gt;\n    &lt;/label&gt;\n  &lt;/li&gt;\n);\n
\n

I have tried using getBlockIndex( clientId ) to try to get the index of each block, however I'm not sure where to use this as it always returns -1. It also only seems that clientId is available in the edit function, and I think I want it in the save function unless I go about adding it to the block attributes.

\n"},"answers":{"kind":"list like","value":[{"answer_id":397966,"author":"shadi","author_id":124857,"author_profile":"https://wordpress.stackexchange.com/users/124857","pm_score":0,"selected":false,"text":"

try saving the values in html data attributes. then get them using getAttribute(&quot;data-index&quot;)

\n
data-index=&quot;number&quot;\n
\n

usually in save.js you can't use useStates and useEffects. you have to make another file that uses vanilla js to do the logic. save.js is saved as a pure html elements.

\n"},{"answer_id":398017,"author":"Djave","author_id":27866,"author_profile":"https://wordpress.stackexchange.com/users/27866","pm_score":0,"selected":false,"text":"

The Quiz block was the top level block. So in its Edit function, I created a subscribe method. I was able to select the editor and get the current block:

\n
// Subscribe to all changes of the Gutenberg blocks\nwp.data.subscribe(() =&gt; {\n  const quiz = wp.data.select(&quot;core/editor&quot;).getBlock(clientId);\n  triggerUpdate(quiz);\n});\n
\n

The subscribe method is covered briefly here:

\n

https://www.youtube.com/watch?v=OQczO6VOMkY

\n

This subscribe() happened to be called thousands of times as the page was edited, so I was unable to work out a better way of working with it than to manually &quot;debounce&quot; it:

\n
// Debounce that change, so it wouldn't trigger thousands of times\nlet timeouts = [];\n\nconst triggerUpdate = (quiz) =&gt; {\n  while (timeouts.length) {\n    clearTimeout(timeouts.shift());\n  }\n\n  const timeout = setTimeout(() =&gt; {\n    // ... the code to get the index of each block\n  }, 1000);\n  timeouts.push(timeout);\n};\n
\n

Now I had a function triggering every time I updated the post, I just needed to actually get the indexes. This was easily done by using .innerBlocks, once on the quiz (which I'd already got by using wp.data.select(&quot;core/editor&quot;).getBlock(clientId)) and then once on each question.

\n

With that, I could loop through each block and update its attributes using updateBlockAttributes

\n
// Loop through all nested blocks and update relevant attributes\nquiz.innerBlocks.forEach((question, q) =&gt; {\n  let qid = &quot;q&quot; + (q + 1); // qid = &quot;q1&quot;, &quot;q2&quot; etc\n  if (question.attributes.qid != qid) {\n    const update = {\n      qid,\n      questionTitle: &quot;Question &quot; + numToWords(parseInt(q + 1)),\n    };\n    console.log(update);\n    dispatch(&quot;core/editor&quot;).updateBlockAttributes(\n      question.clientId,\n      update\n    );\n  }\n  question.innerBlocks.forEach((answer, a) =&gt; {\n    let aid = qid + &quot;a&quot; + (a + 1); // aid = &quot;q1a2&quot; etc\n    if (answer.attributes.qid != qid) {\n      dispatch(&quot;core/editor&quot;).updateBlockAttributes(answer.clientId, {\n        aid,\n      });\n    }\n  });\n});\n
\n"},{"answer_id":404854,"author":"Mat Lipe","author_id":129914,"author_profile":"https://wordpress.stackexchange.com/users/129914","pm_score":2,"selected":true,"text":"

You may now retrieve the index of a inner block via the core/block-editor data module. You may pair it with the useSelect hook to keep the indexes up to date on changes.

\n

Something like this. Intentionally verbose for clarity.

\n
import {useSelect} from '@wordpress/data';\n\nconst Answer = ( blockProps ) =&gt; {\n    const {index} = useSelect( select =&gt; {\n        const {getBlockIndex} = select( 'core/block-editor' );\n        return {\n            index: getBlockIndex( blockProps.clientId );\n        }\n    } );\n\n    return ( &lt;li {...blockProps}&gt;\n        &lt;input id=&quot;checkbox-2&quot; type=&quot;checkbox&quot; value=&quot;checkbox-2&quot; /&gt;\n        &lt;label className=&quot;checkbox&quot; htmlFor=&quot;checkbox-2&quot;&gt;\n            {JSON.stringify( blockProps.attributes )}\n            {index}\n            &lt;span className=&quot;quiz--answer-content&quot;&gt;{blockProps.attributes.explanation}&lt;/span&gt;\n        &lt;/label&gt;\n    &lt;/li&gt; );\n}\n\n
\n"}],"string":"[\n {\n \"answer_id\": 397966,\n \"author\": \"shadi\",\n \"author_id\": 124857,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/124857\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

try saving the values in html data attributes. then get them using getAttribute(&quot;data-index&quot;)

\\n
data-index=&quot;number&quot;\\n
\\n

usually in save.js you can't use useStates and useEffects. you have to make another file that uses vanilla js to do the logic. save.js is saved as a pure html elements.

\\n\"\n },\n {\n \"answer_id\": 398017,\n \"author\": \"Djave\",\n \"author_id\": 27866,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/27866\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

The Quiz block was the top level block. So in its Edit function, I created a subscribe method. I was able to select the editor and get the current block:

\\n
// Subscribe to all changes of the Gutenberg blocks\\nwp.data.subscribe(() =&gt; {\\n  const quiz = wp.data.select(&quot;core/editor&quot;).getBlock(clientId);\\n  triggerUpdate(quiz);\\n});\\n
\\n

The subscribe method is covered briefly here:

\\n

https://www.youtube.com/watch?v=OQczO6VOMkY

\\n

This subscribe() happened to be called thousands of times as the page was edited, so I was unable to work out a better way of working with it than to manually &quot;debounce&quot; it:

\\n
// Debounce that change, so it wouldn't trigger thousands of times\\nlet timeouts = [];\\n\\nconst triggerUpdate = (quiz) =&gt; {\\n  while (timeouts.length) {\\n    clearTimeout(timeouts.shift());\\n  }\\n\\n  const timeout = setTimeout(() =&gt; {\\n    // ... the code to get the index of each block\\n  }, 1000);\\n  timeouts.push(timeout);\\n};\\n
\\n

Now I had a function triggering every time I updated the post, I just needed to actually get the indexes. This was easily done by using .innerBlocks, once on the quiz (which I'd already got by using wp.data.select(&quot;core/editor&quot;).getBlock(clientId)) and then once on each question.

\\n

With that, I could loop through each block and update its attributes using updateBlockAttributes

\\n
// Loop through all nested blocks and update relevant attributes\\nquiz.innerBlocks.forEach((question, q) =&gt; {\\n  let qid = &quot;q&quot; + (q + 1); // qid = &quot;q1&quot;, &quot;q2&quot; etc\\n  if (question.attributes.qid != qid) {\\n    const update = {\\n      qid,\\n      questionTitle: &quot;Question &quot; + numToWords(parseInt(q + 1)),\\n    };\\n    console.log(update);\\n    dispatch(&quot;core/editor&quot;).updateBlockAttributes(\\n      question.clientId,\\n      update\\n    );\\n  }\\n  question.innerBlocks.forEach((answer, a) =&gt; {\\n    let aid = qid + &quot;a&quot; + (a + 1); // aid = &quot;q1a2&quot; etc\\n    if (answer.attributes.qid != qid) {\\n      dispatch(&quot;core/editor&quot;).updateBlockAttributes(answer.clientId, {\\n        aid,\\n      });\\n    }\\n  });\\n});\\n
\\n\"\n },\n {\n \"answer_id\": 404854,\n \"author\": \"Mat Lipe\",\n \"author_id\": 129914,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/129914\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

You may now retrieve the index of a inner block via the core/block-editor data module. You may pair it with the useSelect hook to keep the indexes up to date on changes.

\\n

Something like this. Intentionally verbose for clarity.

\\n
import {useSelect} from '@wordpress/data';\\n\\nconst Answer = ( blockProps ) =&gt; {\\n    const {index} = useSelect( select =&gt; {\\n        const {getBlockIndex} = select( 'core/block-editor' );\\n        return {\\n            index: getBlockIndex( blockProps.clientId );\\n        }\\n    } );\\n\\n    return ( &lt;li {...blockProps}&gt;\\n        &lt;input id=&quot;checkbox-2&quot; type=&quot;checkbox&quot; value=&quot;checkbox-2&quot; /&gt;\\n        &lt;label className=&quot;checkbox&quot; htmlFor=&quot;checkbox-2&quot;&gt;\\n            {JSON.stringify( blockProps.attributes )}\\n            {index}\\n            &lt;span className=&quot;quiz--answer-content&quot;&gt;{blockProps.attributes.explanation}&lt;/span&gt;\\n        &lt;/label&gt;\\n    &lt;/li&gt; );\\n}\\n\\n
\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/10"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397957","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/27866/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397957\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/27866/\"\n]"},"input":{"kind":"string","value":"I have a `Quiz` block that contains `Question`s blocks that have `Answer` blocks. Both `Quiz` and `Question` use `InnerBlocks` to allow questions or answers to be dragged around, edited and saved.\n\nWhen I save the Quiz, how can I get the index of each question in `question/save.js` and the index of each question and answer in each `answer/save.js`.\n\nI would like this so I can give all checkbox unique ids, like\n\n```\n\n\n```\n\nAnd label the questions things like \"Question 1.\"\n\nQuiz/save.js\n\n```\nreturn (\n
\n \n
\n);\n\n```\n\nQuestion/save.js\n\n```\nreturn (\n
\n

Question {numToWords(1)}

\n
    \n \n
\n
\n);\n\n```\n\nAnswer/save.js\n\n```\nreturn (\n
  • \n \n \n
  • \n);\n\n```\n\nI have tried using `getBlockIndex( clientId )` to try to get the index of each block, however I'm not sure where to use this as it always returns -1. It also only seems that `clientId` is available in the edit function, and I think I want it in the save function unless I go about adding it to the block attributes."},"output":{"kind":"string","value":"You may now retrieve the index of a inner block via the `core/block-editor` data module. You may pair it with the `useSelect` hook to keep the indexes up to date on changes.\n\nSomething like this. *Intentionally verbose for clarity.*\n\n```\nimport {useSelect} from '@wordpress/data';\n\nconst Answer = ( blockProps ) => {\n const {index} = useSelect( select => {\n const {getBlockIndex} = select( 'core/block-editor' );\n return {\n index: getBlockIndex( blockProps.clientId );\n }\n } );\n\n return (
  • \n \n \n
  • );\n}\n\n```"}}},{"rowIdx":7657475,"cells":{"qid":{"kind":"number","value":397962,"string":"397,962"},"question":{"kind":"string","value":"

    I have a custom field for view counts that are stored as numbers. I added a Views column, and made it sortable, but they are not sorting properly.

    \n

    The results when I click on the Views column are something like this:

    \n
    Views\n=====\n1900\n10992\n10004\n280\n18\n4015\n...\n
    \n

    Here is my code:

    \n
    /**\n * Add view counts to admin columns\n */\nadd_filter( 'manage_posts_columns', 'eri_posts_column_views' );\nfunction eri_posts_column_views( $columns ) {\n    $columns['post_views'] = 'Views';\n    return $columns;\n}\nadd_action( 'manage_posts_custom_column', 'eri_posts_custom_column_views' );\nfunction eri_posts_custom_column_views( $column ) {\n    if ( $column === 'post_views') {\n        $post_id = get_the_ID();\n        $meta_key = 'eri_post_view_count';\n        $count = 0;\n        if (get_post_meta( $post_id, $meta_key, true ) &amp;&amp; get_post_meta( $post_id, $meta_key, true ) != '') {\n            $count = get_post_meta( $post_id, $meta_key, true );\n        }\n        echo $count;\n    }\n}\n\n\n/**\n * Make admin columns sortable\n */\nadd_filter('manage_edit-post_sortable_columns', 'eri_view_count_sortable_column');\nfunction eri_view_count_sortable_column($columns){\n    $columns['post_views'] = 'post_views';\n    return $columns;\n}\nadd_action( 'pre_get_posts', 'eri_view_count_custom_orderby' );\nfunction eri_view_count_custom_orderby( $query ) {\n    if( ! is_admin() )\n        return;\n\n    $orderby = $query-&gt;get( 'orderby');\n\n    if( 'post_views' == $orderby ) {\n      $query-&gt;set('meta_key','eri_post_view_count');\n      $query-&gt;set('orderby','meta_value_num');\n    }\n}\n
    \n

    I've tried changing meta_value_num to meta_value... not working.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":397999,"author":"ZealousWeb","author_id":70780,"author_profile":"https://wordpress.stackexchange.com/users/70780","pm_score":-1,"selected":false,"text":"

    Can you please set query as per below code?

    \n
    $query-&gt;set('orderby','meta_value meta_value_num');\n
    \n

    or below:

    \n
    $query-&gt;set('orderby','meta_value');\n
    \n"},{"answer_id":398016,"author":"Michael","author_id":42925,"author_profile":"https://wordpress.stackexchange.com/users/42925","pm_score":0,"selected":false,"text":"

    I figured it out after adding the same code to a different site I run. It was working fine on that site with the same theme and mostly the same plugins. I narrowed it down to another function I made (thankfully it wasn't another plugin). The other function was sorting something on the front end, so all I had to do was add if (!is_admin()) to that function. So the moral of the story is, I screwed up in a completely different area. :(

    \n"}],"string":"[\n {\n \"answer_id\": 397999,\n \"author\": \"ZealousWeb\",\n \"author_id\": 70780,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/70780\",\n \"pm_score\": -1,\n \"selected\": false,\n \"text\": \"

    Can you please set query as per below code?

    \\n
    $query-&gt;set('orderby','meta_value meta_value_num');\\n
    \\n

    or below:

    \\n
    $query-&gt;set('orderby','meta_value');\\n
    \\n\"\n },\n {\n \"answer_id\": 398016,\n \"author\": \"Michael\",\n \"author_id\": 42925,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/42925\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    I figured it out after adding the same code to a different site I run. It was working fine on that site with the same theme and mostly the same plugins. I narrowed it down to another function I made (thankfully it wasn't another plugin). The other function was sorting something on the front end, so all I had to do was add if (!is_admin()) to that function. So the moral of the story is, I screwed up in a completely different area. :(

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/10"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397962","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/42925/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397962\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/42925/\"\n]"},"input":{"kind":"string","value":"I have a custom field for view counts that are stored as numbers. I added a Views column, and made it sortable, but they are not sorting properly.\n\nThe results when I click on the Views column are something like this:\n\n```\nViews\n=====\n1900\n10992\n10004\n280\n18\n4015\n...\n\n```\n\nHere is my code:\n\n```\n/**\n * Add view counts to admin columns\n */\nadd_filter( 'manage_posts_columns', 'eri_posts_column_views' );\nfunction eri_posts_column_views( $columns ) {\n $columns['post_views'] = 'Views';\n return $columns;\n}\nadd_action( 'manage_posts_custom_column', 'eri_posts_custom_column_views' );\nfunction eri_posts_custom_column_views( $column ) {\n if ( $column === 'post_views') {\n $post_id = get_the_ID();\n $meta_key = 'eri_post_view_count';\n $count = 0;\n if (get_post_meta( $post_id, $meta_key, true ) && get_post_meta( $post_id, $meta_key, true ) != '') {\n $count = get_post_meta( $post_id, $meta_key, true );\n }\n echo $count;\n }\n}\n\n/**\n * Make admin columns sortable\n */\nadd_filter('manage_edit-post_sortable_columns', 'eri_view_count_sortable_column');\nfunction eri_view_count_sortable_column($columns){\n $columns['post_views'] = 'post_views';\n return $columns;\n}\nadd_action( 'pre_get_posts', 'eri_view_count_custom_orderby' );\nfunction eri_view_count_custom_orderby( $query ) {\n if( ! is_admin() )\n return;\n\n $orderby = $query->get( 'orderby');\n\n if( 'post_views' == $orderby ) {\n $query->set('meta_key','eri_post_view_count');\n $query->set('orderby','meta_value_num');\n }\n}\n\n```\n\nI've tried changing `meta_value_num` to `meta_value`... not working."},"output":{"kind":"string","value":"I figured it out after adding the same code to a different site I run. It was working fine on that site with the same theme and mostly the same plugins. I narrowed it down to another function I made (thankfully it wasn't another plugin). The other function was sorting something on the front end, so all I had to do was add `if (!is_admin())` to that function. So the moral of the story is, I screwed up in a completely different area. :("}}},{"rowIdx":7657476,"cells":{"qid":{"kind":"number","value":397974,"string":"397,974"},"question":{"kind":"string","value":"

    I have a client who wants to review and revise their Tags and tagging strategy, but they want to start with a spreadsheet of ALL tags, including those that have no posts assigned to them.

    \n

    SO I created a template that outputs the Tags to an HTML Table, that I can then import into Excel and upload to Google Sheets so their team can collaborate on it.

    \n

    The template works great, but the query does not include the empty Tags, even though I have &quot;hide_empty&quot; set to 0 (tried both 'false' and '0' with the same results).

    \n

    I can't use get_terms because that query includes terms added by plugins that are not at all related to Posts nor post_tags, even though when I tried get_terms I added the 'taxonomy' =&gt; post_tag, it still gave me about 400 additional terms that are not Post Tags (they are mostly for CPTs and the like, not Posts).

    \n

    If I use get_tags, I get a clean list of just Post Tags, but it isn't giving me the ones with 0 Posts assigned.

    \n

    Can someone please help me troubleshoot this code?

    \n

    Here is the HTML and query from my Template:

    \n
        &lt;table id=&quot;download&quot;&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Tag Name&lt;/th&gt;\n      &lt;th&gt;Post Count&lt;/th&gt;\n    &lt;/tr&gt;\n    &lt;?php\n    global $wp_query;\n    $tags = get_tags( $args );\n    $args = array(\n      'hide_empty' =&gt; 0,\n    );\n    if ( $tags ) :\n      foreach ( $tags as $tag ) : ?&gt;\n    &lt;tr&gt;\n        &lt;td&gt;&lt;?php echo esc_html( $tag-&gt;name ); ?&gt;&lt;/td&gt;\n        &lt;td&gt;&lt;?php echo $tag-&gt;count; ?&gt;&lt;/td&gt;\n    &lt;/tr&gt;\n    &lt;?php endforeach; endif; ?&gt;\n    &lt;/table&gt;\n
    \n

    I know there are quite a lot of Tags in their list that have 0 Posts assigned, I can see them in the WP back end, just can't figure out how to export the entire list to something someone can work with in Excel/Google Sheets....

    \n"},"answers":{"kind":"list like","value":[{"answer_id":397975,"author":"shanebp","author_id":16575,"author_profile":"https://wordpress.stackexchange.com/users/16575","pm_score":0,"selected":false,"text":"

    Try:

    \n
    $args = array( 'hide_empty' =&gt; false );\n$tags = get_tags( $args );\n
    \n

    More info re possible args.

    \n

    For csv export, you probably want to use get_the_tags

    \n"},{"answer_id":398020,"author":"Trisha","author_id":56458,"author_profile":"https://wordpress.stackexchange.com/users/56458","pm_score":-1,"selected":true,"text":"

    Well this was an odd fix, and one that in theory shouldn't have been necessary, however, what finally worked (to show ALL Tags including those with empty counts) was to specify the taxonomy =&gt; 'post_tag' EVEN THOUGH that is the 'default' parameter and shouldn't need to have been added to $args.

    \n

    Sigh.

    \n

    My final query that works:

    \n
    global $wp_query;\n$tags = get_tags( array(\n  'taxonomy' =&gt; 'post_tag',\n  'hide_empty' =&gt; false,\n  )\n);\nif ( $tags ) :\n  foreach ( $tags as $tag ) :\n
    \n"}],"string":"[\n {\n \"answer_id\": 397975,\n \"author\": \"shanebp\",\n \"author_id\": 16575,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/16575\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Try:

    \\n
    $args = array( 'hide_empty' =&gt; false );\\n$tags = get_tags( $args );\\n
    \\n

    More info re possible args.

    \\n

    For csv export, you probably want to use get_the_tags

    \\n\"\n },\n {\n \"answer_id\": 398020,\n \"author\": \"Trisha\",\n \"author_id\": 56458,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/56458\",\n \"pm_score\": -1,\n \"selected\": true,\n \"text\": \"

    Well this was an odd fix, and one that in theory shouldn't have been necessary, however, what finally worked (to show ALL Tags including those with empty counts) was to specify the taxonomy =&gt; 'post_tag' EVEN THOUGH that is the 'default' parameter and shouldn't need to have been added to $args.

    \\n

    Sigh.

    \\n

    My final query that works:

    \\n
    global $wp_query;\\n$tags = get_tags( array(\\n  'taxonomy' =&gt; 'post_tag',\\n  'hide_empty' =&gt; false,\\n  )\\n);\\nif ( $tags ) :\\n  foreach ( $tags as $tag ) :\\n
    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/10"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/397974","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/56458/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/397974\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/56458/\"\n]"},"input":{"kind":"string","value":"I have a client who wants to review and revise their Tags and tagging strategy, but they want to start with a spreadsheet of ALL tags, including those that have no posts assigned to them.\n\nSO I created a template that outputs the Tags to an HTML Table, that I can then import into Excel and upload to Google Sheets so their team can collaborate on it.\n\nThe template works great, but the query does not include the empty Tags, even though I have \"hide\\_empty\" set to 0 (tried both 'false' and '0' with the same results).\n\nI can't use get\\_terms because that query includes terms added by plugins that are not at all related to Posts nor post\\_tags, even though when I tried get\\_terms I added the 'taxonomy' => post\\_tag, it still gave me about 400 additional terms that are not Post Tags (they are mostly for CPTs and the like, not Posts).\n\nIf I use get\\_tags, I get a clean list of *just* Post Tags, but it isn't giving me the ones with 0 Posts assigned.\n\nCan someone please help me troubleshoot this code?\n\nHere is the HTML and query from my Template:\n\n```\n \n \n \n \n \n 0,\n );\n if ( $tags ) :\n foreach ( $tags as $tag ) : ?>\n \n \n \n \n \n
    Tag NamePost Count
    name ); ?>count; ?>
    \n\n```\n\nI know there are quite a lot of Tags in their list that have 0 Posts assigned, I can see them in the WP back end, just can't figure out how to export the entire list to something someone can work with in Excel/Google Sheets...."},"output":{"kind":"string","value":"Well this was an odd fix, and one that in theory shouldn't have been necessary, however, what finally worked (to show ALL Tags including those with empty counts) was to specify the taxonomy => 'post\\_tag' EVEN THOUGH that is the 'default' parameter and shouldn't need to have been added to $args.\n\nSigh.\n\nMy final query that works:\n\n```\nglobal $wp_query;\n$tags = get_tags( array(\n 'taxonomy' => 'post_tag',\n 'hide_empty' => false,\n )\n);\nif ( $tags ) :\n foreach ( $tags as $tag ) :\n\n```"}}},{"rowIdx":7657477,"cells":{"qid":{"kind":"number","value":398024,"string":"398,024"},"question":{"kind":"string","value":"

    I am working on a multisite install where one specific site needs to have access restricted to only users who are logged in AND have a specific user meta set (key=&quot;cr_access&quot;, val=&quot;Yes&quot;). If the user is not logged in, or that meta key is not set to &quot;Yes&quot;, then they should be redirected to the specified url.

    \n

    The redirect works properly, however it seems to be getting cached. If a user tries to visit a page before logging in, then logs in and tries again, it is still redirecting them to the set url. If I purge the page and object caches, then the user is able to visit the pages. How can I prevent this from getting cached in the first place?

    \n

    Here is my code:

    \n
    function hwnycr_redirect(){\n\n//only redirect for blog id 10, non-admin, and exclude home/login pages\nif (!is_front_page() &amp;&amp; !current_user_can( 'edit_posts' ) &amp;&amp; get_current_blog_id() == 10 &amp;&amp; get_the_ID() &lt;&gt; 13) {\n\n    if(!is_user_logged_in()) {\n\n      wp_redirect('https://example.com');\n      exit();\n\n    } else {\n\n      $current_user = wp_get_current_user();\n      $cr_access = get_user_meta($current_user-&gt;ID, 'cr_access', true);\n\n      if ($cr_access !== &quot;Yes&quot;) {\n\n        wp_redirect('https://example.com');\n        exit();\n\n      }\n\n    }\n  }\n}\n\nadd_action( 'template_redirect', 'hwnycr_redirect',1);\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":401005,"author":"Squivo","author_id":217626,"author_profile":"https://wordpress.stackexchange.com/users/217626","pm_score":0,"selected":false,"text":"

    Been banging my head against the wall on this one for months. The workaround is to set all the of redirected posts under a common slug and have WPEngine force all urls under that slug ( category ) to never cache.

    \n"},{"answer_id":404855,"author":"badcrocodile","author_id":104931,"author_profile":"https://wordpress.stackexchange.com/users/104931","pm_score":1,"selected":false,"text":"

    You should try adding nocache_headers() before you wp_redirect(). It's meant for this exact thing. From the docs:

    \n
    \n

    Set the headers to prevent caching for the different browsers.

    \n
    \n

    Your scenario was mentioned and addressed in a user contributed note in the WP Code Reference. That's where I picked this technique up from.

    \n"}],"string":"[\n {\n \"answer_id\": 401005,\n \"author\": \"Squivo\",\n \"author_id\": 217626,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/217626\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Been banging my head against the wall on this one for months. The workaround is to set all the of redirected posts under a common slug and have WPEngine force all urls under that slug ( category ) to never cache.

    \\n\"\n },\n {\n \"answer_id\": 404855,\n \"author\": \"badcrocodile\",\n \"author_id\": 104931,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/104931\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    You should try adding nocache_headers() before you wp_redirect(). It's meant for this exact thing. From the docs:

    \\n
    \\n

    Set the headers to prevent caching for the different browsers.

    \\n
    \\n

    Your scenario was mentioned and addressed in a user contributed note in the WP Code Reference. That's where I picked this technique up from.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/11"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398024","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/155285/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398024\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/155285/\"\n]"},"input":{"kind":"string","value":"I am working on a multisite install where one specific site needs to have access restricted to only users who are logged in AND have a specific user meta set (key=\"cr\\_access\", val=\"Yes\"). If the user is not logged in, or that meta key is not set to \"Yes\", then they should be redirected to the specified url.\n\nThe redirect works properly, however it seems to be getting cached. If a user tries to visit a page before logging in, then logs in and tries again, it is still redirecting them to the set url. If I purge the page and object caches, then the user is able to visit the pages. How can I prevent this from getting cached in the first place?\n\nHere is my code:\n\n```\nfunction hwnycr_redirect(){\n\n//only redirect for blog id 10, non-admin, and exclude home/login pages\nif (!is_front_page() && !current_user_can( 'edit_posts' ) && get_current_blog_id() == 10 && get_the_ID() <> 13) {\n\n if(!is_user_logged_in()) {\n\n wp_redirect('https://example.com');\n exit();\n\n } else {\n\n $current_user = wp_get_current_user();\n $cr_access = get_user_meta($current_user->ID, 'cr_access', true);\n\n if ($cr_access !== \"Yes\") {\n\n wp_redirect('https://example.com');\n exit();\n\n }\n\n }\n }\n}\n\nadd_action( 'template_redirect', 'hwnycr_redirect',1);\n\n```"},"output":{"kind":"string","value":"You should try adding `nocache_headers()` before you `wp_redirect()`. It's meant for this exact thing. [From the docs](https://developer.wordpress.org/reference/functions/nocache_headers/):\n\n> \n> Set the headers to prevent caching for the different browsers.\n> \n> \n> \n\nYour scenario was mentioned and addressed in a [user contributed note](https://developer.wordpress.org/reference/functions/wp_redirect/#comment-3973) in the WP Code Reference. That's where I picked this technique up from."}}},{"rowIdx":7657478,"cells":{"qid":{"kind":"number","value":398071,"string":"398,071"},"question":{"kind":"string","value":"

    I have a plugin with import

    \n
    import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor';\n
    \n

    but it's not working with newest Gutenberg plugin 11.9, because this useInnerBlocksProps is no longer experimental

    \n

    so I can use

    \n
    import { useInnerBlocksProps } from '@wordpress/block-editor';\n
    \n

    but then it will not work for older versions, or WordPress installation without Gutenberg plugin.

    \n

    What's the correct way to make it compatible with both scenarios? How to import __experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398086,"author":"KubiQ","author_id":128483,"author_profile":"https://wordpress.stackexchange.com/users/128483","pm_score":2,"selected":true,"text":"

    Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;)

    \n
    import {\n    __experimentalUseInnerBlocksProps,\n    useInnerBlocksProps,\n} from '@wordpress/block-editor';\n\nif( typeof useInnerBlocksProps == 'undefined' ){\n    var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps;\n}else{\n    var compatibleUseInnerBlocksProps = useInnerBlocksProps;\n}\n
    \n
      \n
    • so basically I can import both (experimental and no-experimental) without any error
    • \n
    • then I can just do simple type test if the new one is already supported
    • \n
    • if it's supported I will remember it in compatibleUseInnerBlocksProps variable
    • \n
    • otherwise I will remember old experimental
    • \n
    • then I need to replace all other occurrences of useInnerBlocksProps with compatibleUseInnerBlocksProps in my code
    • \n
    \n"},{"answer_id":407691,"author":"Gchtr","author_id":22506,"author_profile":"https://wordpress.stackexchange.com/users/22506","pm_score":0,"selected":false,"text":"

    I used the logic from the accepted answer, which works great.

    \n

    But I implemented it a little differently. I import useInnerBlocksProps as nonExperimentalUseInnerBlocksProps. This way, I can keep using useInnerBlocksProps where I use it in the code. This will make it easier to remove support for __experimentalUseInnerBlocksProps in the future.

    \n
    import {\n  useInnerBlocksProps as nonExperimentalUseInnerBlocksProps,\n  __experimentalUseInnerBlocksProps,\n} from '@wordpress/block-editor';\n\nconst useInnerBlocksProps =\n  typeof nonExperimentalUseInnerBlocksProps == 'undefined'\n    ? __experimentalUseInnerBlocksProps\n    : nonExperimentalUseInnerBlocksProps;\n
    \n"}],"string":"[\n {\n \"answer_id\": 398086,\n \"author\": \"KubiQ\",\n \"author_id\": 128483,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/128483\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

    Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;)

    \\n
    import {\\n    __experimentalUseInnerBlocksProps,\\n    useInnerBlocksProps,\\n} from '@wordpress/block-editor';\\n\\nif( typeof useInnerBlocksProps == 'undefined' ){\\n    var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps;\\n}else{\\n    var compatibleUseInnerBlocksProps = useInnerBlocksProps;\\n}\\n
    \\n
      \\n
    • so basically I can import both (experimental and no-experimental) without any error
    • \\n
    • then I can just do simple type test if the new one is already supported
    • \\n
    • if it's supported I will remember it in compatibleUseInnerBlocksProps variable
    • \\n
    • otherwise I will remember old experimental
    • \\n
    • then I need to replace all other occurrences of useInnerBlocksProps with compatibleUseInnerBlocksProps in my code
    • \\n
    \\n\"\n },\n {\n \"answer_id\": 407691,\n \"author\": \"Gchtr\",\n \"author_id\": 22506,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/22506\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    I used the logic from the accepted answer, which works great.

    \\n

    But I implemented it a little differently. I import useInnerBlocksProps as nonExperimentalUseInnerBlocksProps. This way, I can keep using useInnerBlocksProps where I use it in the code. This will make it easier to remove support for __experimentalUseInnerBlocksProps in the future.

    \\n
    import {\\n  useInnerBlocksProps as nonExperimentalUseInnerBlocksProps,\\n  __experimentalUseInnerBlocksProps,\\n} from '@wordpress/block-editor';\\n\\nconst useInnerBlocksProps =\\n  typeof nonExperimentalUseInnerBlocksProps == 'undefined'\\n    ? __experimentalUseInnerBlocksProps\\n    : nonExperimentalUseInnerBlocksProps;\\n
    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/12"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398071","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/128483/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398071\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/128483/\"\n]"},"input":{"kind":"string","value":"I have a plugin with import\n\n```\nimport { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor';\n\n```\n\nbut it's not working with newest Gutenberg plugin 11.9, because this `useInnerBlocksProps` is no longer *experimental*\n\nso I can use\n\n```\nimport { useInnerBlocksProps } from '@wordpress/block-editor';\n\n```\n\nbut then it will not work for older versions, or WordPress installation without Gutenberg plugin.\n\nWhat's the correct way to make it compatible with both scenarios? How to import \\_\\_experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?"},"output":{"kind":"string","value":"Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;)\n\n```\nimport {\n __experimentalUseInnerBlocksProps,\n useInnerBlocksProps,\n} from '@wordpress/block-editor';\n\nif( typeof useInnerBlocksProps == 'undefined' ){\n var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps;\n}else{\n var compatibleUseInnerBlocksProps = useInnerBlocksProps;\n}\n\n```\n\n* so basically I can import both (experimental and no-experimental) without any error\n* then I can just do simple type test if the new one is already supported\n* if it's supported I will remember it in `compatibleUseInnerBlocksProps` variable\n* otherwise I will remember old *experimental*\n* then I need to replace all other occurrences of `useInnerBlocksProps` with `compatibleUseInnerBlocksProps` in my code"}}},{"rowIdx":7657479,"cells":{"qid":{"kind":"number","value":398210,"string":"398,210"},"question":{"kind":"string","value":"

    As referenced in this issue ( https://github.com/WordPress/gutenberg/issues/33374) I want my custom block's innerblocks to have the default layout and alignment controls Like the layout toggle for the Group block, but baked in.

    \n

    It was answered, but I can't figure out the code:

    \n
    \n

    you can do it by providing a layout to inner blocks, that said, the feature is still experimental at the moment, you should be able to pass __experimentalLayout ={ { contentSize: '800px', wideSize: '1000px' } } to your inner blocks, you can also pass __experimentalLayout ={ { inherit: true } } to your inner blocks as well to inherit whatever layout is defined.

    \n
    \n

    My code

    \n
    export default function Edit() {\n    return (\n        &lt;div {...useBlockProps()}&gt;\n            &lt;InnerBlocks /&gt;\n        &lt;/div&gt;\n    );\n}\n
    \n

    This doesn't work

    \n
    export default function Edit() {\n    return (\n        &lt;div {...useBlockProps()}&gt;\n            &lt;InnerBlocks __experimentalLayout ={ { inherit: true } } /&gt;\n        &lt;/div&gt;\n    );\n}\n
    \n

    Does it go in supports in block.json?

    \n

    What I'm trying to do

    \n

    This issue explains the custom block I'm trying to make. Very simple! But I need innerblocks to have alignment control and you lose that on innerblocks when you use theme.json. https://github.com/WordPress/gutenberg/issues/36465

    \n

    Updated code

    \n

    I added this to the block.json, which adds the toggle for default layout, but the innerblocks still don't have full/wide alignment control. Not sure how to do that, but halfway there.

    \n
        &quot;supports&quot;: {\n    &quot;__experimentalLayout&quot;: {\n      &quot;contentSize&quot;: &quot;800px&quot;,\n      &quot;wideSize&quot;: &quot;1000px&quot;,\n            &quot;inherit&quot;: true\n    }\n    },\n
    \n

    Updated code from stokeman's answer

    \n

    block.json

    \n
    {\n    &quot;apiVersion&quot;: 2,\n    &quot;name&quot;: &quot;mbp/details&quot;,\n    &quot;version&quot;: &quot;0.1.0&quot;,\n    &quot;title&quot;: &quot;Details&quot;,\n    &quot;category&quot;: &quot;design&quot;,\n    &quot;icon&quot;: &quot;heart&quot;,\n    &quot;supports&quot;: {\n        &quot;align&quot;: [&quot;full&quot;],\n        &quot;__experimentalLayout&quot;: {\n        &quot;allowSwitching&quot;: false,\n        &quot;default&quot;: {\n                &quot;inherit&quot;: true\n        }\n}\n    },\n        &quot;attributes&quot;: {\n    &quot;align&quot;: {\n            &quot;type&quot;: &quot;string&quot;,\n            &quot;default&quot;: &quot;full&quot;\n        }\n    },\n    &quot;textdomain&quot;: &quot;mobilebevpros&quot;,\n    &quot;editorScript&quot;: &quot;file:../../../../build/details.js&quot;\n}\n
    \n

    edit.js

    \n
    import { __ } from &quot;@wordpress/i18n&quot;;\nimport {\n    useBlockProps,\n    useSetting,\n    InnerBlocks,\n} from &quot;@wordpress/block-editor&quot;;\n\nexport default function Edit() {\n    const defaultLayout = useSetting(&quot;layout&quot;) || {};\n    return (\n        &lt;div {...useBlockProps()}&gt;\n            &lt;InnerBlocks __experimentalLayout={defaultLayout} /&gt;\n        &lt;/div&gt;\n    );\n}\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":398252,"author":"stokesman","author_id":214758,"author_profile":"https://wordpress.stackexchange.com/users/214758","pm_score":2,"selected":false,"text":"

    You're pretty close. Specifying layout details in block.json should nest inside a &quot;default&quot; property. Doing so will have the Layout panel display accordingly but there's more to it than that.

    \n

    If you want the default layout for the block, there is no need to add contentSize or wideSize. Here is the layout config I'd recommend (within the block json supports property):

    \n
            &quot;__experimentalLayout&quot;: {\n            &quot;allowSwitching&quot;: false,\n            &quot;default&quot;: {\n                &quot;inherit&quot;: true\n            }\n        }\n
    \n

    That will make the Layout panel in the block’s sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs.

    \n

    Even though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component:

    \n
    import {\n    useBlockProps, // already in use from example\n    useSetting     // new bit\n} from '@wordpress/block-editor';\n\nexport default function Edit() {\n    const defaultLayout = useSetting( 'layout' ) || {};\n    return (\n        &lt;div {...useBlockProps()}&gt;\n            &lt;InnerBlocks __experimentalLayout={ defaultLayout } /&gt;\n        &lt;/div&gt;\n    );\n}\n
    \n

    Besides that the block must be registered on the server but I take it that's already being done.

    \n

    I'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site.

    \n"},{"answer_id":398849,"author":"stokesman","author_id":214758,"author_profile":"https://wordpress.stackexchange.com/users/214758","pm_score":0,"selected":false,"text":"

    Based on what I understand of what you're trying to do, I think it might be best accomplished by registering a block variation for the Group block. It can preset the padding and inheritance of the default layout and has options that can make it appear as its own separate block. This example creates one that will show up in the inserter as &quot;Dat Section&quot; and has some preset padding and a custom class:

    \n
    wp.blocks.registerBlockVariation(\n    'core/group',\n    {\n        name:'dat-section',\n        title: 'Dat Section',\n        isActive: (blockAttributes, vAttributes) =&gt;\n            blockAttributes.className\n                .includes(vAttributes.className),\n        attributes: {\n            className: 'dat-section',\n            layout: {\n                inherit: true,\n            },\n            style:{\n               spacing:{\n                   padding: { top: '25px', bottom:'55px' }\n               }\n            }\n        },\n    }\n);\n
    \n

    There are more options too. You can set a different icon and description or specify innerBlocks to have it insert with some blocks nested already.

    \n"}],"string":"[\n {\n \"answer_id\": 398252,\n \"author\": \"stokesman\",\n \"author_id\": 214758,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214758\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

    You're pretty close. Specifying layout details in block.json should nest inside a &quot;default&quot; property. Doing so will have the Layout panel display accordingly but there's more to it than that.

    \\n

    If you want the default layout for the block, there is no need to add contentSize or wideSize. Here is the layout config I'd recommend (within the block json supports property):

    \\n
            &quot;__experimentalLayout&quot;: {\\n            &quot;allowSwitching&quot;: false,\\n            &quot;default&quot;: {\\n                &quot;inherit&quot;: true\\n            }\\n        }\\n
    \\n

    That will make the Layout panel in the block’s sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs.

    \\n

    Even though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component:

    \\n
    import {\\n    useBlockProps, // already in use from example\\n    useSetting     // new bit\\n} from '@wordpress/block-editor';\\n\\nexport default function Edit() {\\n    const defaultLayout = useSetting( 'layout' ) || {};\\n    return (\\n        &lt;div {...useBlockProps()}&gt;\\n            &lt;InnerBlocks __experimentalLayout={ defaultLayout } /&gt;\\n        &lt;/div&gt;\\n    );\\n}\\n
    \\n

    Besides that the block must be registered on the server but I take it that's already being done.

    \\n

    I'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site.

    \\n\"\n },\n {\n \"answer_id\": 398849,\n \"author\": \"stokesman\",\n \"author_id\": 214758,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214758\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Based on what I understand of what you're trying to do, I think it might be best accomplished by registering a block variation for the Group block. It can preset the padding and inheritance of the default layout and has options that can make it appear as its own separate block. This example creates one that will show up in the inserter as &quot;Dat Section&quot; and has some preset padding and a custom class:

    \\n
    wp.blocks.registerBlockVariation(\\n    'core/group',\\n    {\\n        name:'dat-section',\\n        title: 'Dat Section',\\n        isActive: (blockAttributes, vAttributes) =&gt;\\n            blockAttributes.className\\n                .includes(vAttributes.className),\\n        attributes: {\\n            className: 'dat-section',\\n            layout: {\\n                inherit: true,\\n            },\\n            style:{\\n               spacing:{\\n                   padding: { top: '25px', bottom:'55px' }\\n               }\\n            }\\n        },\\n    }\\n);\\n
    \\n

    There are more options too. You can set a different icon and description or specify innerBlocks to have it insert with some blocks nested already.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/16"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398210","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/120585/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398210\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/120585/\"\n]"},"input":{"kind":"string","value":"As referenced in this issue ( ) I want my custom block's innerblocks to have the default layout and alignment controls Like the layout toggle for the Group block, but baked in.\n\nIt was answered, but I can't figure out the code:\n\n> \n> you can do it by providing a layout to inner blocks, that said, the feature is still experimental at the moment, you should be able to pass \\_\\_experimentalLayout ={ { contentSize: '800px', wideSize: '1000px' } } to your inner blocks, you can also pass \\_\\_experimentalLayout ={ { inherit: true } } to your inner blocks as well to inherit whatever layout is defined.\n> \n> \n> \n\nMy code\n=======\n\n```\nexport default function Edit() {\n return (\n
    \n \n
    \n );\n}\n\n```\n\nThis doesn't work\n\n```\nexport default function Edit() {\n return (\n
    \n \n
    \n );\n}\n\n```\n\nDoes it go in supports in block.json?\n\nWhat I'm trying to do\n=====================\n\nThis issue explains the custom block I'm trying to make. Very simple! But I need innerblocks to have alignment control and you lose that on innerblocks when you use theme.json. \n\nUpdated code\n============\n\nI added this to the block.json, which adds the toggle for default layout, but the innerblocks still don't have full/wide alignment control. Not sure how to do that, but halfway there.\n\n```\n \"supports\": {\n \"__experimentalLayout\": {\n \"contentSize\": \"800px\",\n \"wideSize\": \"1000px\",\n \"inherit\": true\n }\n },\n\n```\n\nUpdated code from stokeman's answer\n-----------------------------------\n\nblock.json\n\n```\n{\n \"apiVersion\": 2,\n \"name\": \"mbp/details\",\n \"version\": \"0.1.0\",\n \"title\": \"Details\",\n \"category\": \"design\",\n \"icon\": \"heart\",\n \"supports\": {\n \"align\": [\"full\"],\n \"__experimentalLayout\": {\n \"allowSwitching\": false,\n \"default\": {\n \"inherit\": true\n }\n}\n },\n \"attributes\": {\n \"align\": {\n \"type\": \"string\",\n \"default\": \"full\"\n }\n },\n \"textdomain\": \"mobilebevpros\",\n \"editorScript\": \"file:../../../../build/details.js\"\n}\n\n```\n\nedit.js\n\n```\nimport { __ } from \"@wordpress/i18n\";\nimport {\n useBlockProps,\n useSetting,\n InnerBlocks,\n} from \"@wordpress/block-editor\";\n\nexport default function Edit() {\n const defaultLayout = useSetting(\"layout\") || {};\n return (\n
    \n \n
    \n );\n}\n\n```"},"output":{"kind":"string","value":"You're pretty close. Specifying layout details in block.json should nest inside a `\"default\"` property. Doing so will have the Layout panel display accordingly but there's more to it than that.\n\nIf you want the default layout for the block, there is no need to add `contentSize` or `wideSize`. Here is the layout config I'd recommend (within the block json `supports` property):\n\n```js\n \"__experimentalLayout\": {\n \"allowSwitching\": false,\n \"default\": {\n \"inherit\": true\n }\n }\n\n```\n\nThat will make the Layout panel in the block’s sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs.\n\nEven though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component:\n\n```js\nimport {\n useBlockProps, // already in use from example\n useSetting // new bit\n} from '@wordpress/block-editor';\n\nexport default function Edit() {\n const defaultLayout = useSetting( 'layout' ) || {};\n return (\n
    \n \n
    \n );\n}\n\n```\n\nBesides that the block must be registered on the server but I take it that's already being done.\n\nI'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site."}}},{"rowIdx":7657480,"cells":{"qid":{"kind":"number","value":398340,"string":"398,340"},"question":{"kind":"string","value":"

    I have some legacy meta fields in my post that I would like to display in my block. I found a documentation for settings meta fields but not how to display them. So I tried this:

    \n
    export default function save( { attributes } ) {\n\n    const blockProps = useBlockProps.save();\n\n    const postType = useSelect(\n        ( select ) =&gt; select( 'core/editor' ).getCurrentPostType(),\n        []\n    );\n\n    const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );\n\n    const game_meta = meta[ '_shortscore_game' ];\n\n    return (\n        &lt;p { ...blockProps } &gt;\n            &lt;h2&gt;&lt;game_meta/&gt;&lt;/h2&gt;\n        &lt;/p&gt;\n    );\n}\n
    \n

    I get this error:

    \n
    \n

    Invalid hook call. Hooks can only be called inside of the body of a\nfunction component. This could happen for one of the following\nreasons: 1. You might have mismatching versions of React and the\nrenderer (such as React DOM) 2. You might be breaking the Rules of\nHooks 3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to\ndebug and fix this problem.

    \n
    \n

    What is the problem? It happens because of

    \n
    const postType = useSelect(\n    ( select ) =&gt; select( 'core/editor' ).getCurrentPostType(),\n    []\n);\n
    \n

    But why? It works the same in the edit function.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398361,"author":"stokesman","author_id":214758,"author_profile":"https://wordpress.stackexchange.com/users/214758","pm_score":3,"selected":true,"text":"

    From the docs:\nhttps://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save

    \n
    \n

    Note: The save function should be a pure function that depends only on the attributes used to invoke it.\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it select( store ).selector( ... ).\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (read more about Validation).\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:

    \n
    \n
    \n
      \n
    • Use dynamic blocks and dynamically retrieve the required information on the server.
    • \n
    • Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.
    • \n
    \n
    \n"},{"answer_id":405312,"author":"Mr2P","author_id":16299,"author_profile":"https://wordpress.stackexchange.com/users/16299","pm_score":0,"selected":false,"text":"

    There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here Meta Field Block. The requirement is your meta field has to enable the show_in_rest option.

    \n"}],"string":"[\n {\n \"answer_id\": 398361,\n \"author\": \"stokesman\",\n \"author_id\": 214758,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214758\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

    From the docs:\\nhttps://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save

    \\n
    \\n

    Note: The save function should be a pure function that depends only on the attributes used to invoke it.\\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it select( store ).selector( ... ).\\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (read more about Validation).\\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:

    \\n
    \\n
    \\n
      \\n
    • Use dynamic blocks and dynamically retrieve the required information on the server.
    • \\n
    • Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.
    • \\n
    \\n
    \\n\"\n },\n {\n \"answer_id\": 405312,\n \"author\": \"Mr2P\",\n \"author_id\": 16299,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/16299\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here Meta Field Block. The requirement is your meta field has to enable the show_in_rest option.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/19"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398340","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/33797/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398340\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/33797/\"\n]"},"input":{"kind":"string","value":"I have some legacy meta fields in my post that I would like to display in my block. I found a documentation for settings meta fields but not how to display them. So I tried this:\n\n```\nexport default function save( { attributes } ) {\n\n const blockProps = useBlockProps.save();\n\n const postType = useSelect(\n ( select ) => select( 'core/editor' ).getCurrentPostType(),\n []\n );\n\n const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );\n\n const game_meta = meta[ '_shortscore_game' ];\n\n return (\n

    \n

    \n

    \n );\n}\n\n```\n\nI get this error:\n\n> \n> Invalid hook call. Hooks can only be called inside of the body of a\n> function component. This could happen for one of the following\n> reasons: 1. You might have mismatching versions of React and the\n> renderer (such as React DOM) 2. You might be breaking the Rules of\n> Hooks 3. You might have more than one copy of React in the same app\n> See for tips about how to\n> debug and fix this problem.\n> \n> \n> \n\nWhat is the problem? It happens because of\n\n```\nconst postType = useSelect(\n ( select ) => select( 'core/editor' ).getCurrentPostType(),\n []\n);\n\n```\n\nBut why? It works the same in the edit function."},"output":{"kind":"string","value":"From the docs:\n\n\n> \n> Note: The save function should be a pure function that depends only on the attributes used to invoke it.\n> It can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it `select( store ).selector( ... )`.\n> This is because if the external information changes, the block may be flagged as invalid when the post is later edited ([read more about Validation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation)).\n> If there is a need to have other information as part of the save, developers can consider one of these two alternatives:\n> \n> \n> \n\n> \n> * Use [dynamic blocks](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/) and dynamically retrieve the required information on the server.\n> * Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.\n> \n> \n>"}}},{"rowIdx":7657481,"cells":{"qid":{"kind":"number","value":398364,"string":"398,364"},"question":{"kind":"string","value":"

    I have for example this posts in WP:

    \n
    Name   ID  Date \nJohnA  6  01012020\nJohnB  7  01022020\nKateA  7  05052021\nSamA   4  01022020\nSamA   4  01022022\n
    \n

    How I can order by date, but also put posts with ID before others for every user logged in (also ordered by date ) ? Other words - how to sort with conditional logic, using variable for example current user ID in it, so each user will see own posts before other one's.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398361,"author":"stokesman","author_id":214758,"author_profile":"https://wordpress.stackexchange.com/users/214758","pm_score":3,"selected":true,"text":"

    From the docs:\nhttps://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save

    \n
    \n

    Note: The save function should be a pure function that depends only on the attributes used to invoke it.\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it select( store ).selector( ... ).\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (read more about Validation).\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:

    \n
    \n
    \n
      \n
    • Use dynamic blocks and dynamically retrieve the required information on the server.
    • \n
    • Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.
    • \n
    \n
    \n"},{"answer_id":405312,"author":"Mr2P","author_id":16299,"author_profile":"https://wordpress.stackexchange.com/users/16299","pm_score":0,"selected":false,"text":"

    There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here Meta Field Block. The requirement is your meta field has to enable the show_in_rest option.

    \n"}],"string":"[\n {\n \"answer_id\": 398361,\n \"author\": \"stokesman\",\n \"author_id\": 214758,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/214758\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

    From the docs:\\nhttps://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save

    \\n
    \\n

    Note: The save function should be a pure function that depends only on the attributes used to invoke it.\\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it select( store ).selector( ... ).\\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (read more about Validation).\\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:

    \\n
    \\n
    \\n
      \\n
    • Use dynamic blocks and dynamically retrieve the required information on the server.
    • \\n
    • Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.
    • \\n
    \\n
    \\n\"\n },\n {\n \"answer_id\": 405312,\n \"author\": \"Mr2P\",\n \"author_id\": 16299,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/16299\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here Meta Field Block. The requirement is your meta field has to enable the show_in_rest option.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/20"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398364","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/81810/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398364\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/81810/\"\n]"},"input":{"kind":"string","value":"I have for example this posts in WP:\n\n```\nName ID Date \nJohnA 6 01012020\nJohnB 7 01022020\nKateA 7 05052021\nSamA 4 01022020\nSamA 4 01022022\n\n```\n\nHow I can order by date, but also put posts with ID before others for every user logged in (also ordered by date ) ? Other words - how to sort with conditional logic, using variable for example current user ID in it, so each user will see own posts before other one's."},"output":{"kind":"string","value":"From the docs:\n\n\n> \n> Note: The save function should be a pure function that depends only on the attributes used to invoke it.\n> It can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it `select( store ).selector( ... )`.\n> This is because if the external information changes, the block may be flagged as invalid when the post is later edited ([read more about Validation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation)).\n> If there is a need to have other information as part of the save, developers can consider one of these two alternatives:\n> \n> \n> \n\n> \n> * Use [dynamic blocks](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/) and dynamically retrieve the required information on the server.\n> * Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.\n> \n> \n>"}}},{"rowIdx":7657482,"cells":{"qid":{"kind":"number","value":398461,"string":"398,461"},"question":{"kind":"string","value":"

    I have a specific requirement that my referral link be as simple as possible to type in manually (customer base is very low skilled) while simultaneously referring to an employee number who was responsible for the referral.

    \n

    So, the referral links need to look like:

    \n
    www.domain.com/referral/1555\n
    \n

    Where &quot;1555&quot; is the employee ref number who sent this referral link, and it's the employee ref number that I'll be taking out of the URL.\nI'm using PHP snippets to deal with loading that data and handling it, but I need to land on the &quot;referral&quot; page inorder for that php snippet to fire.

    \n

    How do I dictate to WP that any URL slug starting with &quot;referral&quot;, regarldes of what comes after, goes to my referral page and keeps the URL intact? The best I can do right now is land on the referral page but the URL gets reset to merely

    \n
    www.domain.com/referral\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":398844,"author":"keepkalm","author_id":26744,"author_profile":"https://wordpress.stackexchange.com/users/26744","pm_score":0,"selected":false,"text":"

    You just need the Redirection Plugin and a little regex. There are good options on how to match the URLs in the plugin settings.

    \n"},{"answer_id":398867,"author":"Aboelabbas","author_id":119142,"author_profile":"https://wordpress.stackexchange.com/users/119142","pm_score":1,"selected":false,"text":"

    Supposing you have a page created with the slug &quot;referral&quot;, you can add another segment to the page URL containing the employee ref number like this:

    \n

    1- Register a new query variable e.g &quot;employee_ref&quot;

    \n
    add_filter('query_vars', function ($query_vars){\n    $query_vars[] = 'employee_ref';\n    return $query_vars;\n});\n
    \n

    2- Using add_rewrite_rule function, add a new rule for the 'employee_ref' to be equal to the last numeric segment of the page URL:

    \n
    add_action('init', function (){\n    add_rewrite_rule(\n        '^referral/([0-9]+)/?$',\n        'index.php?pagename=referral&amp;employee_ref=$matches[1]',\n        'top'\n    );\n});\n
    \n

    3- Go to permalinks setting page on your WordPress dashboard and hit the &quot;Save Changes&quot; button to flush the rewrite rules--a mandatory step--.

    \n

    4- The referral link now will look like &quot;https://yourdomain.com/referral/345/&quot;, where &quot;345&quot; is the employee ref number and you can catch it in PHP using:

    \n
    get_query_var('employee_ref');\n
    \n

    The code used in the first two steps can be placed inside your theme's functions.php or a plugin file.

    \n"}],"string":"[\n {\n \"answer_id\": 398844,\n \"author\": \"keepkalm\",\n \"author_id\": 26744,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/26744\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    You just need the Redirection Plugin and a little regex. There are good options on how to match the URLs in the plugin settings.

    \\n\"\n },\n {\n \"answer_id\": 398867,\n \"author\": \"Aboelabbas\",\n \"author_id\": 119142,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/119142\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Supposing you have a page created with the slug &quot;referral&quot;, you can add another segment to the page URL containing the employee ref number like this:

    \\n

    1- Register a new query variable e.g &quot;employee_ref&quot;

    \\n
    add_filter('query_vars', function ($query_vars){\\n    $query_vars[] = 'employee_ref';\\n    return $query_vars;\\n});\\n
    \\n

    2- Using add_rewrite_rule function, add a new rule for the 'employee_ref' to be equal to the last numeric segment of the page URL:

    \\n
    add_action('init', function (){\\n    add_rewrite_rule(\\n        '^referral/([0-9]+)/?$',\\n        'index.php?pagename=referral&amp;employee_ref=$matches[1]',\\n        'top'\\n    );\\n});\\n
    \\n

    3- Go to permalinks setting page on your WordPress dashboard and hit the &quot;Save Changes&quot; button to flush the rewrite rules--a mandatory step--.

    \\n

    4- The referral link now will look like &quot;https://yourdomain.com/referral/345/&quot;, where &quot;345&quot; is the employee ref number and you can catch it in PHP using:

    \\n
    get_query_var('employee_ref');\\n
    \\n

    The code used in the first two steps can be placed inside your theme's functions.php or a plugin file.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/23"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398461","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/215164/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398461\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/215164/\"\n]"},"input":{"kind":"string","value":"I have a specific requirement that my referral link be as simple as possible to type in manually (customer base is very low skilled) while simultaneously referring to an employee number who was responsible for the referral.\n\nSo, the referral links need to look like:\n\n```\nwww.domain.com/referral/1555\n\n```\n\nWhere \"1555\" is the employee ref number who sent this referral link, and it's the employee ref number that I'll be taking out of the URL.\nI'm using PHP snippets to deal with loading that data and handling it, but I need to land on the \"referral\" page inorder for that php snippet to fire.\n\nHow do I dictate to WP that any URL slug starting with \"referral\", regarldes of what comes after, goes to my referral page and keeps the URL intact? The best I can do right now is land on the referral page but the URL gets reset to merely\n\n```\nwww.domain.com/referral\n\n```"},"output":{"kind":"string","value":"Supposing you have a ***page created with the slug \"referral\"***, you can add another segment to the page URL containing the employee ref number like this:\n\n1- Register a new query variable e.g \"employee\\_ref\"\n\n```\nadd_filter('query_vars', function ($query_vars){\n $query_vars[] = 'employee_ref';\n return $query_vars;\n});\n\n```\n\n2- Using [add\\_rewrite\\_rule](https://developer.wordpress.org/reference/functions/add_rewrite_rule/) function, add a new rule for the 'employee\\_ref' to be equal to the last numeric segment of the page URL:\n\n```\nadd_action('init', function (){\n add_rewrite_rule(\n '^referral/([0-9]+)/?$',\n 'index.php?pagename=referral&employee_ref=$matches[1]',\n 'top'\n );\n});\n\n```\n\n3- Go to permalinks setting page on your WordPress dashboard and hit the \"Save Changes\" button to flush the rewrite rules--***a mandatory step***--.\n\n4- The referral link now will look like \"https://yourdomain.com/referral/345/\", where \"345\" is the employee ref number and you can catch it in PHP using:\n\n```\nget_query_var('employee_ref');\n\n```\n\nThe code used in the first two steps can be placed inside your theme's functions.php or a plugin file."}}},{"rowIdx":7657483,"cells":{"qid":{"kind":"number","value":398497,"string":"398,497"},"question":{"kind":"string","value":"

    This is an unusual one (I think).

    \n

    We run a news site, and sometimes when editing posts (using the classic editor, not the new block one) we find that a paragraph in the post we are editing has somehow become wrapped in a bunch of spans containing bootstrap css classes.

    \n

    i.e. the paragraph becomes this

    \n
    &lt;p&gt;&lt;span style=&quot;color: var(--bs-body-color); font-family: var(--bs-body-font-family); font-size: var(--bs-body-font-size); text-align: var(--bs-body-text-align); background-color: var(--bs-body-bg);&quot;&gt;\n{CONTENT}\n&lt;/span&gt;&lt;/p&gt;`\n
    \n

    When it was originally just a normal &lt;p&gt;{CONTENT}&lt;/p&gt;.

    \n

    What we've discovered so far:

    \n
      \n
    • The markup seems to be added when a post is saved
    • \n
    • It isn't just a case of cut-and-paste - the editor can just typing into the article
    • \n
    • The editor doesn't have to be editing the paragraph which changes
    • \n
    • Searching the server for &quot;body-font-family&quot; doesn't return results in php or js files
    • \n
    • Searching the client (i.e. browser including any externally loaded files) for &quot;body-font-family&quot; also doesn't return any results
    • \n
    • Multiple editors running multiple browsers have seen this so it's not a plug-in in the browser
    • \n
    • It doesn't happen all the time
    • \n
    • We can spot no pattern between the posts and paragraphs which have these tags added
    • \n
    \n

    Any/all suggestions are very welcome!

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398808,"author":"Lovor","author_id":135704,"author_profile":"https://wordpress.stackexchange.com/users/135704","pm_score":0,"selected":false,"text":"
      \n
    1. In developer tools, find if bootstrap css is added. Look in list of loaded css files. Copy the name of css.
    2. \n
    3. Search entire wp-content for that css name to find where it is enqueued.
    4. \n
    5. Now, when you located plugin or theme part, search within this directory for a hook the_content.
    6. \n
    7. It is probably this hook, which is hooked to callback function, in which by using regular expressions this extra HTML is added.
    8. \n
    \n"},{"answer_id":399018,"author":"cjbj","author_id":75495,"author_profile":"https://wordpress.stackexchange.com/users/75495","pm_score":1,"selected":false,"text":"

    Without checking your install it's a bit of a guessing game, but I'd say your TinyMCE editor has a bootstrap plugin installed (there are several). Perhaps the developer tried to remove it, but only removed the buttons in the editor. Any case, it might be active without you noticing, with the plugin's jquery interfering with WordPress, leading to erratic behaviour.

    \n

    Also, the plugin may not be on your own server, but loaded from a cdn. Have you checked the editor page html for strings like 'bootstrap'?

    \n
    \n

    Completely different option: some plugin is messing with your content by adding itself to the save_post hook. But this looks less likely to me, because I can't see why a plugin would do this.

    \n"}],"string":"[\n {\n \"answer_id\": 398808,\n \"author\": \"Lovor\",\n \"author_id\": 135704,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/135704\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"
      \\n
    1. In developer tools, find if bootstrap css is added. Look in list of loaded css files. Copy the name of css.
    2. \\n
    3. Search entire wp-content for that css name to find where it is enqueued.
    4. \\n
    5. Now, when you located plugin or theme part, search within this directory for a hook the_content.
    6. \\n
    7. It is probably this hook, which is hooked to callback function, in which by using regular expressions this extra HTML is added.
    8. \\n
    \\n\"\n },\n {\n \"answer_id\": 399018,\n \"author\": \"cjbj\",\n \"author_id\": 75495,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/75495\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Without checking your install it's a bit of a guessing game, but I'd say your TinyMCE editor has a bootstrap plugin installed (there are several). Perhaps the developer tried to remove it, but only removed the buttons in the editor. Any case, it might be active without you noticing, with the plugin's jquery interfering with WordPress, leading to erratic behaviour.

    \\n

    Also, the plugin may not be on your own server, but loaded from a cdn. Have you checked the editor page html for strings like 'bootstrap'?

    \\n
    \\n

    Completely different option: some plugin is messing with your content by adding itself to the save_post hook. But this looks less likely to me, because I can't see why a plugin would do this.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/24"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398497","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/213900/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398497\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/213900/\"\n]"},"input":{"kind":"string","value":"This is an unusual one (I think).\n\nWe run a news site, and sometimes when editing posts (using the classic editor, not the new block one) we find that a paragraph in the post we are editing has somehow become wrapped in a bunch of spans containing bootstrap css classes.\n\ni.e. the paragraph becomes this\n\n```\n

    \n{CONTENT}\n

    `\n\n```\n\nWhen it was originally just a normal `

    {CONTENT}

    `.\n\nWhat we've discovered so far:\n\n* The markup seems to be added when a post is saved\n* It isn't just a case of cut-and-paste - the editor can just typing into the article\n* The editor doesn't have to be editing the paragraph which changes\n* Searching the server for \"body-font-family\" doesn't return results in php or js files\n* Searching the client (i.e. browser including any externally loaded files) for \"body-font-family\" also doesn't return any results\n* Multiple editors running multiple browsers have seen this so it's not a plug-in in the browser\n* It doesn't happen all the time\n* We can spot no pattern between the posts and paragraphs which have these tags added\n\nAny/all suggestions are very welcome!"},"output":{"kind":"string","value":"Without checking your install it's a bit of a guessing game, but I'd say your TinyMCE editor has a bootstrap plugin installed (there are several). Perhaps the developer tried to remove it, but only removed the buttons in the editor. Any case, it might be active without you noticing, with the plugin's jquery interfering with WordPress, leading to erratic behaviour.\n\nAlso, the plugin may not be on your own server, but loaded from a cdn. Have you checked the editor page html for strings like 'bootstrap'?\n\n---\n\nCompletely different option: some plugin is messing with your content by adding itself to the [`save_post`](https://developer.wordpress.org/reference/hooks/save_post/) hook. But this looks less likely to me, because I can't see why a plugin would do this."}}},{"rowIdx":7657484,"cells":{"qid":{"kind":"number","value":398602,"string":"398,602"},"question":{"kind":"string","value":"

    I created my first WordPress website using Elementor and an all-in-one theme called Webify.

    \n

    Since I am new to WordPress and to website design, I've imported a demo website that comes with the Webify theme and I am editing based on that import.

    \n

    I noticed that some pages on my site have this top 'stripe' with a background image and some text on the page name and location.

    \n

    For example, the blog page has this horizontal stripe, with a red background image, and the text Blog on the left-hand side and Home / Blog on the right-hand side:

    \n

    \"blog

    \n

    Do you see it? Right under the logo and the header menu? I want to remove this horizontal stripe!\nThe thing is, I can't find how. As far as I can tell, it's not an Elementor element, because when I edit the page in Elementor I can't interact with it. I also didn't find how to remove it from the WP Customize tool.

    \n

    I do have pages on my site that don't have this top horizontal stripe, like this one:

    \n

    \"enter

    \n

    Let's call this kind of page &quot;Good Page&quot;

    \n

    I can edit a good page to create the beautiful page I want:

    \n

    \"enter

    \n

    but whenever I try to create a new page I get a page with this horizontal stripe. I tried creating a new page directly from WP, from Elementor, I tried using a good page and creating an Elementor template from it and then importing the template to a new page, and even tried cloning a good page, using this WP plugin but in all these attempts, the new page I got had that stripe );

    \n

    Looking at the page attributes for both a good page and a new page I created, I couldn't figure out any attribues that were controling this horizontal stripe.

    \n

    I would be grateful for some help on on to remove this horizontal stripe!

    \n

    In adddition, I would also love some debugging pointers on how to go about identifying an element such as this one, and then hide it in the CSS.

    \n

    Thank you so much for you help :)

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398605,"author":"SavPhill","author_id":202754,"author_profile":"https://wordpress.stackexchange.com/users/202754","pm_score":1,"selected":false,"text":"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \n
     .yourexampleselector {\n    \n    Display: none;\n    \n    }\n
    \n"},{"answer_id":398615,"author":"Arnaud Dev","author_id":168393,"author_profile":"https://wordpress.stackexchange.com/users/168393","pm_score":0,"selected":false,"text":"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n\"enter

    \n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \n

    \"enter

    \n"}],"string":"[\n {\n \"answer_id\": 398605,\n \"author\": \"SavPhill\",\n \"author_id\": 202754,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/202754\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \\n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \\n
     .yourexampleselector {\\n    \\n    Display: none;\\n    \\n    }\\n
    \\n\"\n },\n {\n \"answer_id\": 398615,\n \"author\": \"Arnaud Dev\",\n \"author_id\": 168393,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/168393\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \\n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\\n\\\"enter

    \\n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \\n

    \\\"enter

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/11/27"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398602","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/215262/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398602\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/215262/\"\n]"},"input":{"kind":"string","value":"I created my first WordPress website using Elementor and an all-in-one theme called Webify.\n\nSince I am new to WordPress and to website design, I've imported a demo website that comes with the Webify theme and I am editing based on that import.\n\nI noticed that some pages on my site have this top 'stripe' with a background image and some text on the page name and location.\n\nFor example, the blog page has this horizontal stripe, with a red background image, and the text ***Blog*** on the left-hand side and ***Home / Blog*** on the right-hand side:\n\n[![blog page](https://i.stack.imgur.com/1xQbx.png)](https://i.stack.imgur.com/1xQbx.png)\n\nDo you see it? Right under the logo and the header menu? I want to remove this horizontal stripe!\nThe thing is, I can't find how. As far as I can tell, it's not an Elementor element, because when I edit the page in Elementor I can't interact with it. I also didn't find how to remove it from the WP Customize tool.\n\nI do have pages on my site that don't have this top horizontal stripe, like this one:\n\n[![enter image description here](https://i.stack.imgur.com/njjyc.jpg)](https://i.stack.imgur.com/njjyc.jpg)\n\nLet's call this kind of page \"Good Page\"\n\nI can edit a good page to create the beautiful page I want:\n\n[![enter image description here](https://i.stack.imgur.com/GGKRj.jpg)](https://i.stack.imgur.com/GGKRj.jpg)\n\nbut whenever I try to create a new page I get a page with this horizontal stripe. I tried creating a new page directly from WP, from Elementor, I tried using a good page and creating an Elementor template from it and then importing the template to a new page, and even tried cloning a good page, using [this WP plugin](https://wordpress.org/plugins/copy-delete-posts/) but in all these attempts, the new page I got had that stripe );\n\nLooking at the page attributes for both a good page and a new page I created, I couldn't figure out any attribues that were controling this horizontal stripe.\n\nI would be grateful for some help on on to remove this horizontal stripe!\n\nIn adddition, I would also love some debugging pointers on how to go about identifying an element such as this one, and then hide it in the CSS.\n\nThank you so much for you help :)"},"output":{"kind":"string","value":"If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.\n\nNether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.\n\n```\n .yourexampleselector {\n\n Display: none;\n\n }\n\n```"}}},{"rowIdx":7657485,"cells":{"qid":{"kind":"number","value":398898,"string":"398,898"},"question":{"kind":"string","value":"

    I use this to display all categories:

    \n
    &lt;?php $args = array(\n    'child_of'            =&gt; 0,\n    'current_category'    =&gt; 0,\n    'depth'               =&gt; 0,\n    'echo'                =&gt; 1,\n    'exclude'             =&gt; '',\n    'exclude_tree'        =&gt; '',\n    'feed'                =&gt; '',\n    'feed_image'          =&gt; '',\n    'feed_type'           =&gt; '',\n    'hide_empty'          =&gt; 1,\n    'hide_title_if_empty' =&gt; false,\n    'hierarchical'        =&gt; true,\n    'order'               =&gt; 'ASC',\n    'orderby'             =&gt; 'name',\n    'separator'           =&gt; ' ',\n    'show_count'          =&gt; 0,\n    'show_option_all'     =&gt; '',\n    'style'               =&gt; 'h3',\n    'taxonomy'            =&gt; 'category',\n    'title_li'            =&gt; __( 'Categories' ),\n    'use_desc_for_title'  =&gt; 1,\n); \n\nvar_dump( wp_list_categories($args) );  ?&gt;\n
    \n

    But it also gives me back the word &quot;NULL&quot;.

    \n

    \"enter

    \n

    How can I remove the &quot;NULL&quot;?

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398605,"author":"SavPhill","author_id":202754,"author_profile":"https://wordpress.stackexchange.com/users/202754","pm_score":1,"selected":false,"text":"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \n
     .yourexampleselector {\n    \n    Display: none;\n    \n    }\n
    \n"},{"answer_id":398615,"author":"Arnaud Dev","author_id":168393,"author_profile":"https://wordpress.stackexchange.com/users/168393","pm_score":0,"selected":false,"text":"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n\"enter

    \n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \n

    \"enter

    \n"}],"string":"[\n {\n \"answer_id\": 398605,\n \"author\": \"SavPhill\",\n \"author_id\": 202754,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/202754\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \\n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \\n
     .yourexampleselector {\\n    \\n    Display: none;\\n    \\n    }\\n
    \\n\"\n },\n {\n \"answer_id\": 398615,\n \"author\": \"Arnaud Dev\",\n \"author_id\": 168393,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/168393\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \\n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\\n\\\"enter

    \\n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \\n

    \\\"enter

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/05"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398898","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/137495/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398898\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/137495/\"\n]"},"input":{"kind":"string","value":"I use this to display all categories:\n\n```\n 0,\n 'current_category' => 0,\n 'depth' => 0,\n 'echo' => 1,\n 'exclude' => '',\n 'exclude_tree' => '',\n 'feed' => '',\n 'feed_image' => '',\n 'feed_type' => '',\n 'hide_empty' => 1,\n 'hide_title_if_empty' => false,\n 'hierarchical' => true,\n 'order' => 'ASC',\n 'orderby' => 'name',\n 'separator' => ' ',\n 'show_count' => 0,\n 'show_option_all' => '',\n 'style' => 'h3',\n 'taxonomy' => 'category',\n 'title_li' => __( 'Categories' ),\n 'use_desc_for_title' => 1,\n); \n\nvar_dump( wp_list_categories($args) ); ?>\n\n```\n\nBut it also gives me back the word \"NULL\".\n\n[![enter image description here](https://i.stack.imgur.com/Igqsr.jpg)](https://i.stack.imgur.com/Igqsr.jpg)\n\nHow can I remove the \"NULL\"?"},"output":{"kind":"string","value":"If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.\n\nNether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.\n\n```\n .yourexampleselector {\n\n Display: none;\n\n }\n\n```"}}},{"rowIdx":7657486,"cells":{"qid":{"kind":"number","value":398964,"string":"398,964"},"question":{"kind":"string","value":"

    I would like to have an svg downloaded from my site as a png. Searching I found this code and I must say that everything works. The site is a project that will only be viewed from mobile https://7c81b.wineqrcode.com/ and I would like you to change the size of the downloaded image. Currently the photo is generated based on the size of the svg. Is there any way to get around this? Thanks

    \n
    function downloadSVGAsPNG(e){\nconst canvas = document.createElement(&quot;canvas&quot;);\nconst svg = document.querySelector('#Layer_1');\nconst base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));\nconst w = parseInt(svg.getAttribute('width'));\nconst h = parseInt(svg.getAttribute('height'));\nconst img_to_download = document.createElement('img');\nimg_to_download.src = 'data:image/svg+xml;base64,' + base64doc;\nconsole.log(w, h);\nimg_to_download.onload = function () {\n    console.log('img loaded');\n    canvas.setAttribute('width', w);\n    canvas.setAttribute('height', h);\n    const context = canvas.getContext(&quot;2d&quot;);\n    //context.clearRect(0, 0, w, h);\n    context.drawImage(img_to_download,0,0,w,h);\n    const dataURL = canvas.toDataURL('image/png');\n    if (window.navigator.msSaveBlob) {\n    window.navigator.msSaveBlob(canvas.msToBlob(), &quot;download.png&quot;);\n    e.preventDefault();\n    } else {\n    const a = document.createElement('a');\n    const my_evt = new MouseEvent('click');\n    a.download = 'download.png';\n    a.href = dataURL;\n    a.dispatchEvent(my_evt);\n    }\n    //canvas.parentNode.removeChild(canvas);\n}  \n}\nconst downloadPNG = document.querySelector('#downloadPNG');\nif(downloadPNG) { downloadPNG.addEventListener('click', downloadSVGAsPNG);}\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":398605,"author":"SavPhill","author_id":202754,"author_profile":"https://wordpress.stackexchange.com/users/202754","pm_score":1,"selected":false,"text":"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \n
     .yourexampleselector {\n    \n    Display: none;\n    \n    }\n
    \n"},{"answer_id":398615,"author":"Arnaud Dev","author_id":168393,"author_profile":"https://wordpress.stackexchange.com/users/168393","pm_score":0,"selected":false,"text":"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n\"enter

    \n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \n

    \"enter

    \n"}],"string":"[\n {\n \"answer_id\": 398605,\n \"author\": \"SavPhill\",\n \"author_id\": 202754,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/202754\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \\n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \\n
     .yourexampleselector {\\n    \\n    Display: none;\\n    \\n    }\\n
    \\n\"\n },\n {\n \"answer_id\": 398615,\n \"author\": \"Arnaud Dev\",\n \"author_id\": 168393,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/168393\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \\n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\\n\\\"enter

    \\n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \\n

    \\\"enter

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/07"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/398964","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/204509/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/398964\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/204509/\"\n]"},"input":{"kind":"string","value":"I would like to have an svg downloaded from my site as a png. Searching I found this code and I must say that everything works. The site is a project that will only be viewed from mobile and I would like you to change the size of the downloaded image. Currently the photo is generated based on the size of the svg. Is there any way to get around this? Thanks\n\n```\nfunction downloadSVGAsPNG(e){\nconst canvas = document.createElement(\"canvas\");\nconst svg = document.querySelector('#Layer_1');\nconst base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));\nconst w = parseInt(svg.getAttribute('width'));\nconst h = parseInt(svg.getAttribute('height'));\nconst img_to_download = document.createElement('img');\nimg_to_download.src = 'data:image/svg+xml;base64,' + base64doc;\nconsole.log(w, h);\nimg_to_download.onload = function () {\n console.log('img loaded');\n canvas.setAttribute('width', w);\n canvas.setAttribute('height', h);\n const context = canvas.getContext(\"2d\");\n //context.clearRect(0, 0, w, h);\n context.drawImage(img_to_download,0,0,w,h);\n const dataURL = canvas.toDataURL('image/png');\n if (window.navigator.msSaveBlob) {\n window.navigator.msSaveBlob(canvas.msToBlob(), \"download.png\");\n e.preventDefault();\n } else {\n const a = document.createElement('a');\n const my_evt = new MouseEvent('click');\n a.download = 'download.png';\n a.href = dataURL;\n a.dispatchEvent(my_evt);\n }\n //canvas.parentNode.removeChild(canvas);\n} \n}\nconst downloadPNG = document.querySelector('#downloadPNG');\nif(downloadPNG) { downloadPNG.addEventListener('click', downloadSVGAsPNG);}\n\n```"},"output":{"kind":"string","value":"If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.\n\nNether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.\n\n```\n .yourexampleselector {\n\n Display: none;\n\n }\n\n```"}}},{"rowIdx":7657487,"cells":{"qid":{"kind":"number","value":399000,"string":"399,000"},"question":{"kind":"string","value":"

    Let say I want to insert different inline formatting texts. I can do that by opening the HTML mode, but is there a way to do it directly in the visual mode? For example, if I type span.a in a paragraph block then it will insert &lt;span class=&quot;a&quot;&gt;&lt;/span&gt; in HTML, similarly how the formatting buttons like bold or italic do. Or perhaps at least a hotkey button to apply custom formatting, like Ctrl+B. Is that possible?

    \n

    Or to take it to another level, is there a way to implement Emmet in WordPress?

    \n"},"answers":{"kind":"list like","value":[{"answer_id":398605,"author":"SavPhill","author_id":202754,"author_profile":"https://wordpress.stackexchange.com/users/202754","pm_score":1,"selected":false,"text":"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \n
     .yourexampleselector {\n    \n    Display: none;\n    \n    }\n
    \n"},{"answer_id":398615,"author":"Arnaud Dev","author_id":168393,"author_profile":"https://wordpress.stackexchange.com/users/168393","pm_score":0,"selected":false,"text":"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n\"enter

    \n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \n

    \"enter

    \n"}],"string":"[\n {\n \"answer_id\": 398605,\n \"author\": \"SavPhill\",\n \"author_id\": 202754,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/202754\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.

    \\n

    Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.

    \\n
     .yourexampleselector {\\n    \\n    Display: none;\\n    \\n    }\\n
    \\n\"\n },\n {\n \"answer_id\": 398615,\n \"author\": \"Arnaud Dev\",\n \"author_id\": 168393,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/168393\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.

    \\n

    And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\\n\\\"enter

    \\n

    You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.

    \\n

    \\\"enter

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/08"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/399000","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/64282/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/399000\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/64282/\"\n]"},"input":{"kind":"string","value":"Let say I want to insert different inline formatting texts. I can do that by opening the HTML mode, but is there a way to do it directly in the visual mode? For example, if I type `span.a` in a paragraph block then it will insert `` in HTML, similarly how the formatting buttons like bold or italic do. Or perhaps at least a hotkey button to apply custom formatting, like `Ctrl+B`. Is that possible?\n\nOr to take it to another level, is there a way to implement [Emmet](https://emmet.io/ \"Emmet — the essential toolkit for web-developers\") in WordPress?"},"output":{"kind":"string","value":"If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.\n\nNether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.\n\n```\n .yourexampleselector {\n\n Display: none;\n\n }\n\n```"}}},{"rowIdx":7657488,"cells":{"qid":{"kind":"number","value":399225,"string":"399,225"},"question":{"kind":"string","value":"

    I would like to ask about the wp_redirect(); function. Before I ask this question, everything was working on both local and test servers. But right now, for some unknown reason, on my local wp_redirect is not working.

    \n

    My current structure is this:

    \n
    get_header();\n\n...\n\nwp_redirect($url);\nexit();\n
    \n

    This was also working with our previous programmer. If I declare my get_header after the wp_redirect, the wp_redirect function will work as intended. However, why is it that before, it was working? Btw, I read this SO Answer after I had this problem.

    \n

    Were you able to work the wp_redirect after the get_header?

    \n

    Note: I tried to rollback to previous version and on the old version, other part of the code that uses the same structure above no longer works.

    \n

    The only difference between the environment was on my local, I accidentally dropped my table and reinstalled from scratch. Other than that, nothing comes to mind.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":399227,"author":"Jacob Peattie","author_id":39152,"author_profile":"https://wordpress.stackexchange.com/users/39152","pm_score":2,"selected":false,"text":"

    wp_redirect() works by sending a Location header. Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling wp_redirect().

    \n

    Using wp_redirect() after get_header() never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if header.php was completely empty, so get_header() did not output HTML.

    \n"},{"answer_id":399228,"author":"mukto90","author_id":57944,"author_profile":"https://wordpress.stackexchange.com/users/57944","pm_score":0,"selected":false,"text":"

    You cannot redirect with wp_redirect() after the page content is rendered (this is what get_header() does).

    \n

    So, you basically have 2 options-

    \n
      \n
    1. Place wp_redirect() before you include the header.

      \n
    2. \n
    3. With JavaScript-

      \n
    4. \n
    \n
    &lt;script type=&quot;text/javascript&quot;&gt;\n    window.location = 'https://google.com';\n&lt;/script&gt;\n
    \n"}],"string":"[\n {\n \"answer_id\": 399227,\n \"author\": \"Jacob Peattie\",\n \"author_id\": 39152,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/39152\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

    wp_redirect() works by sending a Location header. Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling wp_redirect().

    \\n

    Using wp_redirect() after get_header() never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if header.php was completely empty, so get_header() did not output HTML.

    \\n\"\n },\n {\n \"answer_id\": 399228,\n \"author\": \"mukto90\",\n \"author_id\": 57944,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/57944\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    You cannot redirect with wp_redirect() after the page content is rendered (this is what get_header() does).

    \\n

    So, you basically have 2 options-

    \\n
      \\n
    1. Place wp_redirect() before you include the header.

      \\n
    2. \\n
    3. With JavaScript-

      \\n
    4. \\n
    \\n
    &lt;script type=&quot;text/javascript&quot;&gt;\\n    window.location = 'https://google.com';\\n&lt;/script&gt;\\n
    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/14"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/399225","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/214554/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/399225\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/214554/\"\n]"},"input":{"kind":"string","value":"I would like to ask about the wp\\_redirect(); function. Before I ask this question, everything was working on both local and test servers. But right now, for some unknown reason, on my local wp\\_redirect is not working.\n\nMy current structure is this:\n\n```\nget_header();\n\n...\n\nwp_redirect($url);\nexit();\n\n```\n\nThis was also working with our previous programmer. If I declare my get\\_header after the wp\\_redirect, the wp\\_redirect function will work as intended. However, why is it that before, it was working? Btw, I read this [SO Answer](https://wordpress.stackexchange.com/a/97982/214554) after I had this problem.\n\nWere you able to work the wp\\_redirect after the get\\_header?\n\nNote: I tried to rollback to previous version and on the old version, other part of the code that uses the same structure above no longer works.\n\nThe only difference between the environment was on my local, I accidentally dropped my table and reinstalled from scratch. Other than that, nothing comes to mind."},"output":{"kind":"string","value":"`wp_redirect()` works by sending a [Location header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location). Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling `wp_redirect()`.\n\nUsing `wp_redirect()` after `get_header()` never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if `header.php` was completely empty, so `get_header()` did not output HTML."}}},{"rowIdx":7657489,"cells":{"qid":{"kind":"number","value":399237,"string":"399,237"},"question":{"kind":"string","value":"

    I searched the whole net and stackexchange for a reason and a solution, but couldn't find any. There are many questions (and answers) related to own plugins and the code how to create tables on activation. But this applies not here, because I have this problem with well known and maintained plugins from the wordpress plugin repository.

    \n

    So, the situation:\nA kvm guest with around 20 docker stacks. Each stack consists of a nginx, a php:8-fpm and a mariadb container. In the nginx container is a web directory as a shared volume, that contains a wordpress installation. (So I'm not using the wordpress docker image!).

    \n

    The wordpress'es are running like a charm. I can access the backend and the frontends, I can install plugins and themes... everything is working... until...

    \n

    Until it comes to a plugin installation that wants to create own sql tables on activation.

    \n

    The tables are not created, I only receive an error that says, the table xxx is not existent and the plugin can not be activated.

    \n

    This happens on all plugins from the wordpress plugin repository, when they want to create own tables on activation.

    \n

    Everything else is working like a charm.

    \n

    The sql user is allowed to create tables... this was checked through the mysql console.\nThe wp-config.php is correct... everything has worked when not in a docker container. This happens only when inside a docker container.

    \n

    So here's my docker-compose.yml

    \n
    version: '3.8'\nservices:\n  app:\n    image: nginx:latest\n    restart: always\n    volumes:\n      - ./web:/usr/share/nginx/html\n      - ./default.conf:/etc/nginx/conf.d/default.conf\n      - ./logs:/var/www/logs\n  php-fpm:\n    image: php:8-fpm\n    restart: always\n    volumes:\n        - ./web:/usr/share/nginx/html\n        - ./errors.ini:/usr/local/etc/php/conf.d/errors.ini:rw\n        - ./logs:/var/www/logs\n    logging:\n      driver: syslog\n      options:\n        tag: docker/php-fpm\n  mariadb:\n    image: mariadb:latest\n    restart: always\n    environment:\n      MYSQL_ROOT_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'\n      MYSQL_DATABASE: 'database'\n      MYSQL_USER: 'dbuser'\n      MYSQL_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'\n    expose:\n      - &quot;3306&quot;\n    volumes:\n      - ./mysql:/var/lib/mysql\n
    \n

    Here comes the default.conf:

    \n
    server {\n    server_name _;\n    index index.php index.html;\n\n    client_max_body_size 1024M;\n    client_body_timeout 900s;\n    fastcgi_buffers 16 16k; \n    fastcgi_buffer_size 32k;\n    send_timeout 3600;\n    keepalive_timeout 60m;\n    fastcgi_send_timeout 3600s;\n    fastcgi_read_timeout 3600s;\n    \n    error_log  /var/www/logs/nginx-error.log;\n    access_log /var/www/logs/nginx-access.log;\n    \n    root /usr/share/nginx/html;\n\n    location / {\n        try_files $uri $uri/ /index.php$is_args$args;\n    }\n\n    location ~ \\.php$ {\n        try_files $uri =404;\n        fastcgi_split_path_info ^(.+\\.php)(/.+)$;\n        fastcgi_index index.php;\n        include fastcgi_params;\n        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n        fastcgi_param PATH_INFO $fastcgi_path_info;\n        fastcgi_param HTTPS on;\n        fastcgi_pass php-fpm:9000;\n    }\n\n}\n
    \n

    Ohh, one more fun fact:\nA simple php script, that creates a table with the same database user credentials through mysqli classes, works like a charm:

    \n
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(&quot;mariadb&quot;, &quot;dbuser&quot;, &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;, &quot;database&quot;);\n\n/* Create table doesn't return a resultset */\n$sql = &quot;CREATE TABLE MyGuests2 (\nid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\nfirstname VARCHAR(30) NOT NULL,\nlastname VARCHAR(30) NOT NULL,\nemail VARCHAR(50),\nreg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE     CURRENT_TIMESTAMP\n)&quot;;\n$mysqli-&gt;query($sql);\nprintf(&quot;Table myGuests2 successfully created.\\n&quot;);\n\n/* Select queries return a resultset */\n$result = $mysqli-&gt;query(&quot;SELECT id FROM MyGuests2 LIMIT 10&quot;);\nprintf(&quot;Select returned %d rows.\\n&quot;, $result-&gt;num_rows);\n\n/* If we have to retrieve large amount of data we use     MYSQLI_USE_RESULT */\n$result = $mysqli-&gt;query(&quot;SELECT * FROM MyGuests&quot;,     MYSQLI_USE_RESULT);\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":399302,"author":"Christin Löhner","author_id":215861,"author_profile":"https://wordpress.stackexchange.com/users/215861","pm_score":3,"selected":true,"text":"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \n

    Update\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \n
    \n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \n\n
    FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n
    \n"},{"answer_id":400325,"author":"Mark Kaplun","author_id":23970,"author_profile":"https://wordpress.stackexchange.com/users/23970","pm_score":2,"selected":false,"text":"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \n"}],"string":"[\n {\n \"answer_id\": 399302,\n \"author\": \"Christin Löhner\",\n \"author_id\": 215861,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/215861\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \\n

    Update\\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \\n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \\n
    \\n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \\n\\n
    FROM php:8-fpm\\n\\nRUN apt-get update\\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\\n\\nRUN apt-get clean\\nRUN rm -rf /var/lib/apt/lists/*\\n\\nCOPY mail.ini /usr/local/etc/php/conf.d/\\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\\nRUN chmod +x /etc/cron.hourly/cronjob.sh\\n\\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\\n\\nRUN docker-php-ext-enable pdo_mysql\\nRUN docker-php-ext-enable mysqli\\nRUN docker-php-ext-enable opcache\\nRUN docker-php-ext-enable bcmath\\nRUN docker-php-ext-enable bz2\\nRUN docker-php-ext-enable gd\\nRUN docker-php-ext-enable pspell\\nRUN docker-php-ext-enable snmp\\nRUN docker-php-ext-enable soap\\nRUN docker-php-ext-enable tidy\\nRUN docker-php-ext-enable xsl\\nRUN docker-php-ext-enable zip\\nRUN docker-php-ext-enable exif\\nRUN docker-php-ext-enable gettext\\nRUN docker-php-ext-enable intl\\n
    \\n\"\n },\n {\n \"answer_id\": 400325,\n \"author\": \"Mark Kaplun\",\n \"author_id\": 23970,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/23970\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \\n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/14"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/399237","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/215861/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/399237\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/215861/\"\n]"},"input":{"kind":"string","value":"I searched the whole net and stackexchange for a reason and a solution, but couldn't find any. There are many questions (and answers) related to own plugins and the code how to create tables on activation. But this applies not here, because I have this problem with well known and maintained plugins from the wordpress plugin repository.\n\n**So, the situation:**\nA kvm guest with around 20 docker stacks. Each stack consists of a nginx, a php:8-fpm and a mariadb container. In the nginx container is a web directory as a shared volume, that contains a wordpress installation. (So I'm not using the wordpress docker image!).\n\nThe wordpress'es are running like a charm. I can access the backend and the frontends, I can install plugins and themes... everything is working... until...\n\n*Until it comes to a plugin installation that wants to create own sql tables on activation.*\n\nThe tables are not created, I only receive an error that says, the table xxx is not existent and the plugin can not be activated.\n\nThis happens on all plugins from the wordpress plugin repository, when they want to create own tables on activation.\n\nEverything else is working like a charm.\n\nThe sql user is allowed to create tables... this was checked through the mysql console.\nThe wp-config.php is correct... everything has worked when not in a docker container. This happens only when inside a docker container.\n\n**So here's my docker-compose.yml**\n\n```\nversion: '3.8'\nservices:\n app:\n image: nginx:latest\n restart: always\n volumes:\n - ./web:/usr/share/nginx/html\n - ./default.conf:/etc/nginx/conf.d/default.conf\n - ./logs:/var/www/logs\n php-fpm:\n image: php:8-fpm\n restart: always\n volumes:\n - ./web:/usr/share/nginx/html\n - ./errors.ini:/usr/local/etc/php/conf.d/errors.ini:rw\n - ./logs:/var/www/logs\n logging:\n driver: syslog\n options:\n tag: docker/php-fpm\n mariadb:\n image: mariadb:latest\n restart: always\n environment:\n MYSQL_ROOT_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'\n MYSQL_DATABASE: 'database'\n MYSQL_USER: 'dbuser'\n MYSQL_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'\n expose:\n - \"3306\"\n volumes:\n - ./mysql:/var/lib/mysql\n\n```\n\n**Here comes the default.conf:**\n\n```\nserver {\n server_name _;\n index index.php index.html;\n\n client_max_body_size 1024M;\n client_body_timeout 900s;\n fastcgi_buffers 16 16k; \n fastcgi_buffer_size 32k;\n send_timeout 3600;\n keepalive_timeout 60m;\n fastcgi_send_timeout 3600s;\n fastcgi_read_timeout 3600s;\n\n error_log /var/www/logs/nginx-error.log;\n access_log /var/www/logs/nginx-access.log;\n\n root /usr/share/nginx/html;\n\n location / {\n try_files $uri $uri/ /index.php$is_args$args;\n }\n\n location ~ \\.php$ {\n try_files $uri =404;\n fastcgi_split_path_info ^(.+\\.php)(/.+)$;\n fastcgi_index index.php;\n include fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_param PATH_INFO $fastcgi_path_info;\n fastcgi_param HTTPS on;\n fastcgi_pass php-fpm:9000;\n }\n\n}\n\n```\n\n**Ohh, one more fun fact:**\nA simple php script, that creates a table with the same database user credentials through mysqli classes, works like a charm:\n\n```\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(\"mariadb\", \"dbuser\", \"xxxxxxxxxxxxxxxxxxxxxxxxxxx\", \"database\");\n\n/* Create table doesn't return a resultset */\n$sql = \"CREATE TABLE MyGuests2 (\nid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\nfirstname VARCHAR(30) NOT NULL,\nlastname VARCHAR(30) NOT NULL,\nemail VARCHAR(50),\nreg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\n)\";\n$mysqli->query($sql);\nprintf(\"Table myGuests2 successfully created.\\n\");\n\n/* Select queries return a resultset */\n$result = $mysqli->query(\"SELECT id FROM MyGuests2 LIMIT 10\");\nprintf(\"Select returned %d rows.\\n\", $result->num_rows);\n\n/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */\n$result = $mysqli->query(\"SELECT * FROM MyGuests\", MYSQLI_USE_RESULT);\n\n```"},"output":{"kind":"string","value":"Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.\n\n**Update**\nI've tested this now with different PHP versions and different plugins from the wordpress repository.\n\nThis happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing \"php:8-fpm\" with \"php:8.0-fpm\" or any other version... it works again.\n\n---\n\nBy the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:\n\n```sh\nFROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n\n```"}}},{"rowIdx":7657490,"cells":{"qid":{"kind":"number","value":399279,"string":"399,279"},"question":{"kind":"string","value":"

    I have my custom Wordpress+Woocommerce theme created that I want to show on my github page as a reference.

    \n

    The theme does not contain any login data. Of course it contains server-side php code that shows how the client page is created. I always tried to structure the logic according to other themes/according to how code inside Woocommerce plugin works.

    \n

    Is there a security danger for the site when making the theme source public?

    \n"},"answers":{"kind":"list like","value":[{"answer_id":399302,"author":"Christin Löhner","author_id":215861,"author_profile":"https://wordpress.stackexchange.com/users/215861","pm_score":3,"selected":true,"text":"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \n

    Update\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \n
    \n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \n\n
    FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n
    \n"},{"answer_id":400325,"author":"Mark Kaplun","author_id":23970,"author_profile":"https://wordpress.stackexchange.com/users/23970","pm_score":2,"selected":false,"text":"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \n"}],"string":"[\n {\n \"answer_id\": 399302,\n \"author\": \"Christin Löhner\",\n \"author_id\": 215861,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/215861\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \\n

    Update\\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \\n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \\n
    \\n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \\n\\n
    FROM php:8-fpm\\n\\nRUN apt-get update\\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\\n\\nRUN apt-get clean\\nRUN rm -rf /var/lib/apt/lists/*\\n\\nCOPY mail.ini /usr/local/etc/php/conf.d/\\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\\nRUN chmod +x /etc/cron.hourly/cronjob.sh\\n\\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\\n\\nRUN docker-php-ext-enable pdo_mysql\\nRUN docker-php-ext-enable mysqli\\nRUN docker-php-ext-enable opcache\\nRUN docker-php-ext-enable bcmath\\nRUN docker-php-ext-enable bz2\\nRUN docker-php-ext-enable gd\\nRUN docker-php-ext-enable pspell\\nRUN docker-php-ext-enable snmp\\nRUN docker-php-ext-enable soap\\nRUN docker-php-ext-enable tidy\\nRUN docker-php-ext-enable xsl\\nRUN docker-php-ext-enable zip\\nRUN docker-php-ext-enable exif\\nRUN docker-php-ext-enable gettext\\nRUN docker-php-ext-enable intl\\n
    \\n\"\n },\n {\n \"answer_id\": 400325,\n \"author\": \"Mark Kaplun\",\n \"author_id\": 23970,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/23970\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \\n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/15"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/399279","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/215899/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/399279\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/215899/\"\n]"},"input":{"kind":"string","value":"I have my custom Wordpress+Woocommerce theme created that I want to show on my github page as a reference.\n\nThe theme does not contain any login data. Of course it contains server-side php code that shows how the client page is created. I always tried to structure the logic according to other themes/according to how code inside Woocommerce plugin works.\n\n**Is there a security danger for the site when making the theme source public?**"},"output":{"kind":"string","value":"Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.\n\n**Update**\nI've tested this now with different PHP versions and different plugins from the wordpress repository.\n\nThis happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing \"php:8-fpm\" with \"php:8.0-fpm\" or any other version... it works again.\n\n---\n\nBy the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:\n\n```sh\nFROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n\n```"}}},{"rowIdx":7657491,"cells":{"qid":{"kind":"number","value":400336,"string":"400,336"},"question":{"kind":"string","value":"

    I'm studying someone else's code (a custom search widget based on Elementor) and there's one thing I just don't understand.

    \n
    $type_term = get_term_by('slug', get_query_var($taxonomy), $taxonomy);\n$type = (!empty($type_term) &amp;&amp; !empty($type_term-&gt;slug)) ? $type_term-&gt;slug : 0;\n
    \n
    wp_dropdown_categories(array(\n                'show_option_all' =&gt; '',\n                'show_option_none' =&gt; 'Select ' . $taxonomy_obj-&gt;label,\n                'option_none_value' =&gt; '0',\n                'orderby' =&gt; 'name',\n                'order' =&gt; 'ASC',\n                'hide_empty' =&gt; 1,\n                'depth' =&gt; 3,\n                'echo' =&gt; 1,\n                'selected' =&gt; $type,\n                'hierarchical' =&gt; 1,\n                'name' =&gt; $taxonomy,\n                'id' =&gt; $taxonomy . '-select',\n                'class' =&gt; $taxonomy . '-select',\n                'tab_index' =&gt; 1,\n                'taxonomy' =&gt; $taxonomy,\n                'value_field' =&gt; 'slug'\n            ));\n
    \n

    I realize $type is the slug of the selected term.\nBut why do I have to manually assign 'selected' =&gt; $type? What does this field even mean? Shouldn't this be automatically passed to the selected attribute? Am I even correct in that get_query_var($taxonomy)returns the selected taxonomy term?

    \n

    Or more generally speaking, how/where is the selected option stored and how/where is it retrieved for the search? I'm sure there is something really obvious I'm not getting but the documentation didn't help.

    \n

    I hope this is somewhat comprehensible. Thanks!

    \n"},"answers":{"kind":"list like","value":[{"answer_id":399302,"author":"Christin Löhner","author_id":215861,"author_profile":"https://wordpress.stackexchange.com/users/215861","pm_score":3,"selected":true,"text":"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \n

    Update\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \n
    \n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \n\n
    FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n
    \n"},{"answer_id":400325,"author":"Mark Kaplun","author_id":23970,"author_profile":"https://wordpress.stackexchange.com/users/23970","pm_score":2,"selected":false,"text":"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \n"}],"string":"[\n {\n \"answer_id\": 399302,\n \"author\": \"Christin Löhner\",\n \"author_id\": 215861,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/215861\",\n \"pm_score\": 3,\n \"selected\": true,\n \"text\": \"

    Like kero already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.

    \\n

    Update\\nI've tested this now with different PHP versions and different plugins from the wordpress repository.

    \\n

    This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.

    \\n
    \\n

    By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:

    \\n\\n
    FROM php:8-fpm\\n\\nRUN apt-get update\\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\\n\\nRUN apt-get clean\\nRUN rm -rf /var/lib/apt/lists/*\\n\\nCOPY mail.ini /usr/local/etc/php/conf.d/\\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\\nRUN chmod +x /etc/cron.hourly/cronjob.sh\\n\\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\\n\\nRUN docker-php-ext-enable pdo_mysql\\nRUN docker-php-ext-enable mysqli\\nRUN docker-php-ext-enable opcache\\nRUN docker-php-ext-enable bcmath\\nRUN docker-php-ext-enable bz2\\nRUN docker-php-ext-enable gd\\nRUN docker-php-ext-enable pspell\\nRUN docker-php-ext-enable snmp\\nRUN docker-php-ext-enable soap\\nRUN docker-php-ext-enable tidy\\nRUN docker-php-ext-enable xsl\\nRUN docker-php-ext-enable zip\\nRUN docker-php-ext-enable exif\\nRUN docker-php-ext-enable gettext\\nRUN docker-php-ext-enable intl\\n
    \\n\"\n },\n {\n \"answer_id\": 400325,\n \"author\": \"Mark Kaplun\",\n \"author_id\": 23970,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/23970\",\n \"pm_score\": 2,\n \"selected\": false,\n \"text\": \"

    Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.

    \\n

    I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/16"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400336","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/215929/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400336\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/215929/\"\n]"},"input":{"kind":"string","value":"I'm studying someone else's code (a custom search widget based on Elementor) and there's one thing I just don't understand.\n\n```\n$type_term = get_term_by('slug', get_query_var($taxonomy), $taxonomy);\n$type = (!empty($type_term) && !empty($type_term->slug)) ? $type_term->slug : 0;\n\n```\n\n```\nwp_dropdown_categories(array(\n 'show_option_all' => '',\n 'show_option_none' => 'Select ' . $taxonomy_obj->label,\n 'option_none_value' => '0',\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'hide_empty' => 1,\n 'depth' => 3,\n 'echo' => 1,\n 'selected' => $type,\n 'hierarchical' => 1,\n 'name' => $taxonomy,\n 'id' => $taxonomy . '-select',\n 'class' => $taxonomy . '-select',\n 'tab_index' => 1,\n 'taxonomy' => $taxonomy,\n 'value_field' => 'slug'\n ));\n\n```\n\nI realize `$type` is the slug of the selected term.\nBut why do I have to manually assign `'selected' => $type`? What does this field even mean? Shouldn't this be automatically passed to the selected attribute? Am I even correct in that `get_query_var($taxonomy)`returns the selected taxonomy term?\n\nOr more generally speaking, how/where is the selected option stored and how/where is it retrieved for the search? I'm sure there is something really obvious I'm not getting but the documentation didn't help.\n\nI hope this is somewhat comprehensible. Thanks!"},"output":{"kind":"string","value":"Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.\n\n**Update**\nI've tested this now with different PHP versions and different plugins from the wordpress repository.\n\nThis happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing \"php:8-fpm\" with \"php:8.0-fpm\" or any other version... it works again.\n\n---\n\nBy the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:\n\n```sh\nFROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n\n```"}}},{"rowIdx":7657492,"cells":{"qid":{"kind":"number","value":400397,"string":"400,397"},"question":{"kind":"string","value":"

    I am creating a custom theme. In it I am trying to add salon booking plugin. This plugin creates default booking page. When I am viewing the booking page I cannot see the booking form. I have tried installing the salon booking plugin in WordPress default theme twenty twenty-one and it is working fine in this theme. Not sure what is breaking in my theme.

    \n

    In my theme I have added wp_head() just before end of head tag in header.php. I have also added wp_footer() just before the end of body tag in footer.php.

    \n

    I have following php files

    \n
      \n
    • header.php
    • \n
    • footer.php
    • \n
    • functions.php
    • \n
    • index.php
    • \n
    • front-page.php
    • \n
    \n

    I have following pages - home page (that I created, this is pointing to front-page.php), Booking, Thank you for booking, Booking my account. Last three booking pages were created as part of the salon booking plugin.

    \n

    header.php:

    \n
    &lt;!DOCTYPE html&gt;\n&lt;html &lt;?php language_attributes();?&gt;&gt;\n&lt;head&gt;\n    &lt;meta charset=&lt;?php bloginfo('charset');?&gt;&gt;\n    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, viewport-fit=cover&quot;&gt;\n    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;\n    &lt;!--&lt;title&gt;Dust Doctors LLC Theme&lt;/title&gt;--&gt;\n    &lt;title&gt;&lt;?php bloginfo('name');?&gt;&lt;/title&gt;\n    &lt;link rel=&quot;shortcut icon&quot; href=&quot;&lt;?php echo get_theme_file_uri('/img/favicon.ico');?&gt;&quot;&gt;\n    &lt;?php /*include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); */?&gt;\n    &lt;?php wp_head(); ?&gt;\n    \n&lt;/head&gt;\n&lt;body &lt;?php body_class();?&gt; data-spy=&quot;scroll&quot; data-target=&quot;#navbarResponsive&quot;&gt;\n\n    &lt;!-- Start Header Section --&gt;\n    &lt;header id=&quot;home&quot;&gt;\n\n        &lt;!-- Navigation --&gt;\n        &lt;nav class=&quot;navbar navbar-expand-lg fixed-top&quot;&gt;\n            &lt;div class=&quot;container-fluid&quot;&gt;\n                &lt;a href=&quot;#home&quot; class=&quot;navbar-brand&quot;&gt;&lt;img src=&quot;&lt;?php echo get_theme_file_uri('/img/logo.jpeg');?&gt;&quot; alt=&quot;&quot;&gt;&lt;/a&gt;\n                &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarResponsive&quot;&gt;\n                    &lt;span class=&quot;custom-toggler-icon&quot;&gt;&lt;i class=&quot;fas fa-bars&quot;&gt;&lt;/i&gt;&lt;/span&gt;\n                &lt;/button&gt;\n\n                &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarResponsive&quot;&gt;\n                    &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#aboutUs&quot; class=&quot;nav-link&quot;&gt;About Us&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#services&quot; class=&quot;nav-link&quot;&gt;Our Services&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#portfolio&quot; class=&quot;nav-link&quot;&gt;Portfolio&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#clients&quot; class=&quot;nav-link&quot;&gt;Clients&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#contact&quot; class=&quot;nav-link&quot;&gt;Contact Us&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#book&quot; class=&quot;nav-link&quot;&gt;Book Now&lt;/a&gt;\n                        &lt;/li&gt;\n                        &lt;li class=&quot;nav-item&quot;&gt;\n                            &lt;a href=&quot;#faq&quot; class=&quot;nav-link&quot;&gt;FAQ&lt;/a&gt;\n                        &lt;/li&gt;\n                    &lt;/ul&gt;\n                &lt;/div&gt;\n            &lt;/div&gt;\n        &lt;/nav&gt;\n        &lt;!-- End Navigation --&gt;\n    &lt;/header&gt;\n    &lt;!-- End Header Section --&gt; \n
    \n

    footer.php:

    \n
    &lt;footer&gt;\n    \n    &lt;div class=&quot;container footer px-0&quot;&gt;\n        &lt;hr class=&quot;socket&quot;&gt;\n        &lt;div class=&quot;row&quot;&gt;\n            &lt;div class=&quot;col-12 d-flex justify-content-center&quot;&gt;\n                &lt;img src=&quot;img/logo.jpeg&quot; alt=&quot;&quot; class=&quot;brand__logo&quot;&gt;\n            &lt;/div&gt;\n        &lt;/div&gt;\n        &lt;div class=&quot;row outer&quot;&gt;\n            &lt;div class=&quot;container&quot;&gt;\n                &lt;div class=&quot;row py-3&quot;&gt;\n                    &lt;!--&lt;div class=&quot;col-md-6 px-0 pr-md-3&quot;&gt;--&gt;\n                    &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt;\n                        &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Corporate Office&lt;/h5&gt;\n                        &lt;p&gt;\n                            &lt;i class=&quot;fas fa-map-marker&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;100 Street Name,&lt;br&gt;\n                        &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Our City, &lt;br&gt;\n                        &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;AA 10000\n                        &lt;/p&gt;\n                    &lt;/div&gt; &lt;!-- End Column --&gt;\n                    &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt;\n                        &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Contact Info&lt;/h5&gt;\n                        &lt;p&gt;&lt;i class=&quot;fas fa-phone&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;(888) 888-8888 &lt;br&gt;\n                            &lt;i class=&quot;fas fa-envelope&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;info@dustdoctorsllc.com &lt;br&gt;\n                            &lt;i class=&quot;fas fa-fax&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;(888) 888-8888&lt;/p&gt;\n                            &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Follow Us On&lt;/h5&gt;\n                        &lt;ul class=&quot;social&quot;&gt;\n                            &lt;li&gt;&lt;span&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-facebook-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;\n                            &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-twitter-square&quot; &gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n                            &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-instagram&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n                            &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-youtube-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n                            &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-linkedin&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n                        &lt;/ul&gt;\n                    &lt;/div&gt;\n                    &lt;!---&lt;div class=&quot;col-md-6 px-0 pr-md-3&quot;&gt;--&gt;\n                        &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt;\n                            &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Useful Links&lt;/h5&gt;\n                            &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;PRIVACY POLICY&lt;/a&gt;&lt;br&gt;\n                            &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;TERMS&lt;/a&gt;&lt;br&gt;\n                            &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;COMPANY&lt;/a&gt;&lt;br&gt;\n                            &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;SERVICES&lt;/a&gt;&lt;br&gt;\n                        &lt;/div&gt;                  \n                &lt;/div&gt; &lt;!-- End Row --&gt;\n            &lt;/div&gt; &lt;!-- End Container --&gt;\n\n            &lt;hr class=&quot;socket&quot;&gt;\n            &lt;div class=&quot;col-12 d-flex justify-content-center&quot;&gt;\n                &lt;p class=&quot;text-center&quot;&gt;&amp;copy; Dust Doctors LLC 2021&lt;/p&gt;\n            &lt;/div&gt;\n\n        &lt;/div&gt; &lt;!-- End Row Outer --&gt;\n    &lt;/div&gt; &lt;!-- End Container Fluid --&gt;\n    \n&lt;/footer&gt;\n    &lt;!-- Top Scroll --&gt;\n    &lt;a href=&quot;#home&quot; class=&quot;top-scroll&quot;&gt;\n        &lt;i class=&quot;fa fa-angle-up&quot;&gt;&lt;/i&gt;\n    &lt;/a&gt;\n    &lt;!-- End of Top Scroll --&gt;\n\n\n    &lt;!-- Script Source Files --&gt;\n\n\n    &lt;!-- Plugins.js --&gt;\n    &lt;script src=&quot;js/plugins.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- Waypoints https://cdnjs.com/libraries/waypoints\n        https://github.com/imakewebthings/waypoints --&gt;\n    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- Font Awesome https://fontawesome.com/  https://use.fontawesome.com/releases/v5.13.0/js/all.js --&gt;\n    &lt;script src=&quot;https://use.fontawesome.com/releases/v5.13.0/js/all.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- Lightbox Image Gallery https://cdnjs.com/libraries/lightbox2  https://lokeshdhakar.com/projects/lightbox2/ --&gt;\n    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- Owl Carousel https://cdnjs.com/libraries/OwlCarousel2\n        http://owlcarousel2.github.io/OwlCarousel2/ --&gt;\n    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- jQuery CounterUp https://www.jsdelivr.com/package/npm/jquery.counterup\n        https://github.com/bfintal/Counter-Up2 --&gt;\n    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/jquery.counterup@2.1.0/jquery.counterup.min.js&quot;&gt;&lt;/script&gt;\n    &lt;!-- Bootstrap Form Validator https://cdnjs.com/libraries/1000hz-bootstrap-validator --&gt;\n    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js&quot;&gt;&lt;/script&gt;\n    \n    &lt;!-- End of Script Source Files --&gt;\n    &lt;?php wp_footer(); ?&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n
    \n

    index.php:

    \n
    &lt;?php get_header(); ?&gt;\n\n\n\n&lt;?php get_footer();?&gt;\n
    \n

    functions.php:

    \n
    &lt;?php\n    function theme_assets(){\n        /*wp_enqueue_style('dust_doctors_main_styles',get_stylesheet_uri());*/\n        /* bootstrap*/\n        wp_enqueue_style('bootstrap','//cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css',array(),'v5.1.3',false);\n        /* main css*/\n        wp_enqueue_style('main_style',get_theme_file_uri('/css/style.css'),array('bootstrap'),'1.0',false);\n        /* plugins css*/\n        wp_enqueue_style('plugins_style',get_theme_file_uri('/css/plugins.css'),array(),'1.0',false);\n        /* google fonts*/\n        wp_enqueue_style('google-fonts','//fonts.googleapis.com/css?family=Lato:300,400,700&amp;display=swap',array(),'1.0',false);\n        /* animate css*/\n        wp_enqueue_style('animate-css','//cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css',array(),'v3.7.2',false);\n        /* lightbox*/\n        wp_enqueue_style('lightbox','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css',array(),'v2.11.1',false);\n         /* owl carousel */\n         wp_enqueue_style('owlcarousel1','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css',array(),'v2.3.4',false);\n         wp_enqueue_style('owlcarousel2','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css',array(),'v2.3.4',false);\n         /* jquery */\n         wp_enqueue_script('boot-jquery','//code.jquery.com/jquery-3.4.1.min.js',array('jquery'),'',false);\n         /* bootstrap popper js*/\n         wp_enqueue_script('boot-popper-js','//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',array('jquery'),'v1.14.7',false);\n         /* bootstrap main js*/\n         wp_enqueue_script('boot-main-js','//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',array('jquery'),'v4.3.1',false);\n         /* main js script*/\n         wp_enqueue_script('plugin-js',get_theme_file_uri('/js/plugins.js'),array('jquery','jquery-ui-core','jquery-ui-selectmenu'),'1.0',true);\n         /* waypoints*/ \n         wp_enqueue_script('waypoints','//cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js',array('jquery'),'v4.0.1',true);\n         /* font awesome */\n         wp_enqueue_script('font-awesome','//use.fontawesome.com/releases/v5.13.0/js/all.js',array(),'v5.13.0',true);\n         /* lightbox */\n         wp_enqueue_script('lightbox-js','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js',array('jquery'),'v2.11.1',true);\n         /* owl carousel */\n         wp_enqueue_script('owl-carousel-js','/cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js',array('jquery'),'v2.3.4',true);\n         /* counter js */\n         wp_enqueue_script('counter-js','//cdn.jsdelivr.net/npm/jquery.counterup@2.1.0/jquery.counterup.min.js',array('jquery'),'v2.1.0',true);\n         /* form validator*/\n         wp_enqueue_script('form-validator','//cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js',array('jquery'),'v0.11.9',true);\n       \n    }\n\n    /* change login logo in wp-admin*/\n    function my_login_logo() { ?&gt;\n        &lt;style type=&quot;text/css&quot;&gt;\n            body.login{\n                background-image:url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/img/slide-02.jpeg);\n                background-size: cover;\n                background-position: center center;\n                background-repeat:no-repeat;\n            }\n            #login h1 a, .login h1 a {\n                background-image: url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/img/logo.jpeg);\n            height:150px;\n            width:150px;\n            background-size: 150px 150px;\n            background-repeat: no-repeat;\n                padding-bottom: 30px;\n            }\n        &lt;/style&gt;\n    &lt;?php }\n\n    function my_login_logo_url() {\n        return home_url();\n    }\n\n    function my_login_logo_url_title() {\n        return 'Dust Doctors LLC Login';\n    }\n\n    function add_site_favicon() {\n        echo '&lt;link rel=&quot;shortcut icon&quot;\n    href=&quot;' . get_stylesheet_directory_uri() . '/img/favicon.ico&quot; /&gt;';\n    }\n    \n\n        /*function custom_unregister_theme_post_types() {\n            global $wp_post_types;\n        \n              if ( isset( $wp_post_types[&quot;image&quot;] ) ) {\n                 unset( $wp_post_types[ &quot;image&quot; ] ); //UPDATED\n              }\n        \n        }\n        add_action( 'init', 'custom_unregister_theme_post_types', 20 );*/\n        \n    add_action('wp_enqueue_scripts','theme_assets');\n    add_action( 'login_enqueue_scripts', 'my_login_logo' );\n    add_filter( 'login_headerurl', 'my_login_logo_url' );\n    add_filter( 'login_headertext', 'my_login_logo_url_title' );\n    add_action('login_head', 'add_site_favicon');\n    add_action('admin_head', 'add_site_favicon');\n?&gt;\n
    \n

    front-page.php:

    \n
        &lt;?php get_header(); ?&gt;\n    \n    &lt;?php \n    //custom fields\n    $landing_background_image = get_field('landing_background_image');\n    $landing_header = get_field('landing_header');\n    if (empty($landing_header)){\n        $landing_header = 'looking for a cleaning service?';\n    }\n    $landing_tag_line = get_field('landing_tag_line');\n    if (empty($landing_tag_line)){\n        $landing_tag_line = 'we are here to make your home shine';\n    }\n    if (empty($landing_button)){\n        $landing_button = &quot;let's shine&quot;;\n    }\n    ?&gt;\n    \n    \n        &lt;!-- Start Landing Page Section --&gt;\n        &lt;section&gt;\n            &lt;!-- Start Landing Page Image and Title --&gt;\n            &lt;div class=&quot;landing&quot;&gt;\n                &lt;div class=&quot;home-wrap&quot;&gt;\n                    &lt;!--&lt;div class=&quot;home-inner&quot;&gt;&lt;/div&gt;--&gt;\n                    &lt;ul class=&quot;home-slideshow&quot;&gt;\n                    &lt;li&gt;\n                        &lt;?php if(!empty($landing_background_image)){?&gt;\n                            &lt;span style=&quot;background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(&lt;?php echo $landing_background_image['url'];?&gt;)&quot;&gt;Image 01&lt;/span&gt;\n                        &lt;?php } else{?&gt;\n                            &lt;span style=&quot;background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(&lt;?php echo get_theme_file_uri('/img/slide-02.jpeg');?&gt;)&quot;&gt;Image 01&lt;/span&gt;\n                        &lt;?php }?&gt;\n                &lt;!--        &lt;div class=&quot;slide__title text-center text-uppercase&quot;&gt;\n                        &lt;h1 class=&quot;slide__title__main&quot;&gt;looking for a cleaning service?&lt;/h1&gt;\n                        &lt;h3 class=&quot;slide__title__sub&quot;&gt;we are here to make your home shine&lt;/h3&gt;--&gt;\n                        &lt;/div&gt;\n                    &lt;/li&gt;\n                    &lt;/ul&gt;\n                &lt;/div&gt;\n            &lt;/div&gt;\n            &lt;!-- End Landing Page Image and Title--&gt;\n    \n            &lt;!-- Start Landing Page Button --&gt;\n            &lt;div class=&quot;caption text-center text-light text-uppercase&quot;&gt;\n                &lt;!--&lt;h1 class=&quot;caption__title__main os-animation&quot; data-animation=&quot;fadeInUp&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;1s&quot;&gt;looking for a cleaning service?&lt;/h1&gt;\n                &lt;h3 class=&quot;caption__title__sub os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;2s&quot;&gt;we are here to make your home shine&lt;/h3&gt;\n                &lt;a href=&quot;#booking&quot; class=&quot;btn btn__primary btn__animated os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;3s&quot;&gt;let's shine&lt;/a&gt;--&gt;\n                &lt;h1 class=&quot;caption__title__main os-animation&quot; data-animation=&quot;fadeInUp&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;1s&quot;&gt;&lt;?php echo $landing_header;?&gt;&lt;/h1&gt;\n                &lt;h3 class=&quot;caption__title__sub os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;2s&quot;&gt;&lt;?php echo $landing_tag_line;?&gt;&lt;/h3&gt;\n                &lt;a href=&quot;#booking&quot; class=&quot;btn btn__primary btn__animated os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;3s&quot;&gt;&lt;?php echo $landing_button;?&gt;&lt;/a&gt;\n            &lt;/div&gt;\n            &lt;!-- End Landing Page Button --&gt;\n    \n            &lt;!-- Start Bouncing Down Arrow --&gt;\n            &lt;a href=&quot;#aboutUs&quot; class=&quot;down-arrow text-center&quot;&gt;\n                &lt;!--&lt;div class=&quot;arrow d-none d-md-block&quot;&gt;--&gt;\n                &lt;div class=&quot;arrow&quot;&gt;\n                    &lt;i class=&quot;fas fa-angle-down&quot;&gt;&lt;/i&gt;\n                &lt;/div&gt;\n            &lt;/a&gt;\n            &lt;!-- End Bouncing Down Arrow --&gt;\n        &lt;/section&gt;\n        &lt;!-- End Landing Page Section --&gt;\n    \n&lt;?php get_footer();?&gt;\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/17"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400397","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/216993/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400397\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/216993/\"\n]"},"input":{"kind":"string","value":"I am creating a custom theme. In it I am trying to add salon booking plugin. This plugin creates default booking page. When I am viewing the booking page I cannot see the booking form. I have tried installing the salon booking plugin in WordPress default theme twenty twenty-one and it is working fine in this theme. Not sure what is breaking in my theme.\n\nIn my theme I have added `wp_head()` just before end of head tag in `header.php`. I have also added `wp_footer()` just before the end of body tag in footer.php.\n\nI have following php files\n\n* `header.php`\n* `footer.php`\n* `functions.php`\n* `index.php`\n* `front-page.php`\n\nI have following pages - home page (that I created, this is pointing to front-page.php), Booking, Thank you for booking, Booking my account. Last three booking pages were created as part of the salon booking plugin.\n\n`header.php`:\n\n```\n\n>\n\n >\n \n \n \n <?php bloginfo('name');?>\n \">\n \n \n\n\n data-spy=\"scroll\" data-target=\"#navbarResponsive\">\n\n \n
    \n\n \n \n \n
    \n \n\n```\n\n`footer.php`:\n\n```\n
    \n\n
    \n
    \n
    \n
    \n \"\"\n
    \n
    \n
    \n
    \n
    \n \n
    \n
    Corporate Office
    \n

    \n &nbsp;&nbsp;&nbsp;&nbsp;100 Street Name,
    \n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Our City,
    \n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AA 10000\n

    \n
    \n
    \n
    Contact Info
    \n

    &nbsp;&nbsp;&nbsp;&nbsp;(888) 888-8888
    \n &nbsp;&nbsp;&nbsp;&nbsp;info@dustdoctorsllc.com
    \n &nbsp;&nbsp;&nbsp;&nbsp;(888) 888-8888

    \n
    Follow Us On
    \n
      \n
    • \n
    • \n
    • \n
    • \n
    • \n
    \n
    \n \n
    \n
    Useful Links
    \n &nbsp;&nbsp;&nbsp;&nbsp;PRIVACY POLICY
    \n &nbsp;&nbsp;&nbsp;&nbsp;TERMS
    \n &nbsp;&nbsp;&nbsp;&nbsp;COMPANY
    \n &nbsp;&nbsp;&nbsp;&nbsp;SERVICES
    \n
    \n
    \n
    \n\n
    \n
    \n

    &copy; Dust Doctors LLC 2021

    \n
    \n\n
    \n
    \n\n
    \n \n \n \n \n \n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n\n\n\n```\n\n`index.php`:\n\n```\n\n\n\n\n```\n\n`functions.php`:\n\n```\n\n \n ';\n }\n\n /*function custom_unregister_theme_post_types() {\n global $wp_post_types;\n\n if ( isset( $wp_post_types[\"image\"] ) ) {\n unset( $wp_post_types[ \"image\" ] ); //UPDATED\n }\n\n }\n add_action( 'init', 'custom_unregister_theme_post_types', 20 );*/\n\n add_action('wp_enqueue_scripts','theme_assets');\n add_action( 'login_enqueue_scripts', 'my_login_logo' );\n add_filter( 'login_headerurl', 'my_login_logo_url' );\n add_filter( 'login_headertext', 'my_login_logo_url_title' );\n add_action('login_head', 'add_site_favicon');\n add_action('admin_head', 'add_site_favicon');\n?>\n\n```\n\n`front-page.php`:\n\n```\n \n\n \n\n \n
    \n \n
    \n
    \n \n
      \n
    • \n \n )\">Image 01\n \n )\">Image 01\n \n \n
    \n \n \n
    \n
    \n \n\n \n
    \n \n

    \n

    \n \n
    \n \n\n \n \n \n
    \n \n
    \n
    \n \n \n \n\n\n\n```"},"output":{"kind":"string","value":"Your theme does not contain a main post loop, so there is no place for the plugin to do its work\n\n```php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n\n```\n\n"}}},{"rowIdx":7657493,"cells":{"qid":{"kind":"number","value":400444,"string":"400,444"},"question":{"kind":"string","value":"

    my javascript code isn't working. I put the js folder next to the other folders, the astra-child folder, astra folder and other themes. Is this correct. Then in the js folder, I created custom_script.js file and put the javascript in there. And in functions.php file enqueued it.

    \n
    &lt;?php\n/**\n * Astra Child Theme functions and definitions\n *\n * @link https://developer.wordpress.org/themes/basics/theme-functions/\n *\n * @package Astra Child\n * @since 1.0.0\n */\n\n/**\n * Define Constants\n */\ndefine( 'CHILD_THEME_ASTRA_CHILD_VERSION', '1.0.0' );\n\n/**\n * Enqueue styles\n */\nfunction child_enqueue_styles() {\n\n    wp_enqueue_style( 'astra-child-theme-css', get_stylesheet_directory_uri() . '/style.css', array('astra-theme-css'), CHILD_THEME_ASTRA_CHILD_VERSION, 'all' );\n\n}\n\nadd_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );\n\n}\n\nfunction my_scripts_method() {\nwp_enqueue_script(\n'custom-script',\nget_stylesheet_directory_uri() . '/js/custom_script.js',\n);\nadd_action( 'wp_enqueue_scripts', 'my_scripts_method');\n\n}\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/19"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400444","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/205788/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400444\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/205788/\"\n]"},"input":{"kind":"string","value":"my javascript code isn't working. I put the js folder next to the other folders, the astra-child folder, astra folder and other themes. Is this correct. Then in the js folder, I created custom\\_script.js file and put the javascript in there. And in functions.php file enqueued it.\n\n```php\n"}}},{"rowIdx":7657494,"cells":{"qid":{"kind":"number","value":400480,"string":"400,480"},"question":{"kind":"string","value":"

    WordPress supports storing multiple post meta values for a single post using the same meta key. For example one post can have multiple instances of meta_key 'pet' with meta_value 'cat', 'dog', and/or 'fish'. This is super useful when using get_post_meta because you can get an array of all values for the pet meta key, versus managing a serialized array in a single field.

    \n

    It's also really useful when using a meta query, because you can query any post where meta_key 'pet' = 'cat', and get posts where any instance of 'pet' is equal to 'cat', regardless of how many other instances of the meta key may be associated with the post with different values.

    \n

    But is the opposite (e.g. != or NOT LIKE or NOT IN) possible? I'm using the following and it's returning lots of posts that have one instance of meta_key 'pet' = 'cat'.

    \n
    $pet_owners = new WP_Query([\n  'post_type' =&gt; 'pet_owner',\n  'posts_per_page' =&gt; -1,\n  'meta_query' =&gt; [\n    [\n      'key' =&gt; 'pet',\n      'value' =&gt; 'cat',\n      'compare' =&gt; '!='\n    ]\n  ]\n]);\n
    \n

    Edit: I had an error in my pseudocode as flagged by Buttered_toast below.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/20"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400480","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/28924/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400480\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/28924/\"\n]"},"input":{"kind":"string","value":"WordPress supports storing multiple post meta values for a single post using the same meta key. For example one post can have multiple instances of meta\\_key 'pet' with meta\\_value 'cat', 'dog', and/or 'fish'. This is super useful when using get\\_post\\_meta because you can get an array of all values for the pet meta key, versus managing a serialized array in a single field.\n\nIt's also really useful when using a meta query, because you can query any post where meta\\_key 'pet' = 'cat', and get posts where any instance of 'pet' is equal to 'cat', regardless of how many other instances of the meta key may be associated with the post with different values.\n\nBut is the opposite (e.g. `!=` or `NOT LIKE` or `NOT IN`) possible? I'm using the following and it's returning lots of posts that have one instance of meta\\_key 'pet' = 'cat'.\n\n```\n$pet_owners = new WP_Query([\n 'post_type' => 'pet_owner',\n 'posts_per_page' => -1,\n 'meta_query' => [\n [\n 'key' => 'pet',\n 'value' => 'cat',\n 'compare' => '!='\n ]\n ]\n]);\n\n```\n\n**Edit**: I had an error in my pseudocode as flagged by Buttered\\_toast below."},"output":{"kind":"string","value":"Your theme does not contain a main post loop, so there is no place for the plugin to do its work\n\n```php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n\n```\n\n"}}},{"rowIdx":7657495,"cells":{"qid":{"kind":"number","value":400507,"string":"400,507"},"question":{"kind":"string","value":"

    I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there.\nWould anybody know, how I could activate it, if that is the problem. Thanks

    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/21"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400507","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/205788/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400507\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/205788/\"\n]"},"input":{"kind":"string","value":"I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there.\nWould anybody know, how I could activate it, if that is the problem. Thanks"},"output":{"kind":"string","value":"Your theme does not contain a main post loop, so there is no place for the plugin to do its work\n\n```php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n\n```\n\n"}}},{"rowIdx":7657496,"cells":{"qid":{"kind":"number","value":400598,"string":"400,598"},"question":{"kind":"string","value":"

    I am very new to HTML and PHP and have spent hours trying to find the right questions to ask. I would like to create a simple webform on a page and add a button that will generate text (on the same page) based on the variables answered in the webform. I don't need to/want to capture the data from the form. I do not want to show the output in a table format. If possible, I would like the output to be editable and have a copy button. The user would answer the questions they want to, then see the summary of their answers. Any questions they skipped would not show up in the summary. In an ideal situation, they would also be able to edit the compiled text before copying it.

    \n

    Example:

    \n

    Question 1 (required)
    \nQuestion 2 (optional)
    \nQuestion 3 (optional)

    \n

    [Generate]

    \n

    (On webpage, print:) &quot;Hello (Q1 answer). Based on your blah blah, we think your idea to (Q2 answer) is great!&quot;

    \n

    This is do-able, right? I feel like it is such a simple thing to do that no one talks about how to do it. I understand how to create forms and input fields, but I'm not sure how to make the generate button that will compile the answers from the questions into a paragraph on the page. Any syntax examples would be so, so helpful.

    \n

    Thank you!!

    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/23"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400598","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/217202/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400598\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/217202/\"\n]"},"input":{"kind":"string","value":"I am very new to HTML and PHP and have spent hours trying to find the right questions to ask. I would like to create a simple webform on a page and add a button that will generate text (on the same page) based on the variables answered in the webform. I don't need to/want to capture the data from the form. I *do not* want to show the output in a table format. If possible, I would like the output to be editable and have a copy button. The user would answer the questions they want to, then see the summary of their answers. Any questions they skipped would not show up in the summary. In an ideal situation, they would also be able to edit the compiled text before copying it.\n\n**Example:**\n\nQuestion 1 (required) \n\nQuestion 2 (optional) \n\nQuestion 3 (optional)\n\n[Generate]\n\n(On webpage, print:) \"Hello (Q1 answer). Based on your blah blah, we think your idea to (Q2 answer) is great!\"\n\nThis is do-able, right? I feel like it is such a simple thing to do that no one talks about how to do it. I understand how to create forms and input fields, but I'm not sure how to make the generate button that will compile the answers from the questions into a paragraph on the page. Any syntax examples would be so, so helpful.\n\nThank you!!"},"output":{"kind":"string","value":"Your theme does not contain a main post loop, so there is no place for the plugin to do its work\n\n```php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n\n```\n\n"}}},{"rowIdx":7657497,"cells":{"qid":{"kind":"number","value":400712,"string":"400,712"},"question":{"kind":"string","value":"

    I am trying to change the classes for the &quot;View cart&quot; button after adding an item to the cart. What I tried to do is to hook into the &quot;woocommerce_ajax_added_to_cart&quot; action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook:

    \n
    function set_button_classes() {\n\n    echo &quot;&lt;script&gt;document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');&lt;/script&gt;&quot;;\n\n}\nadd_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); \n
    \n

    Any pointers would be really appreciated.

    \n"},"answers":{"kind":"list like","value":[{"answer_id":400400,"author":"Tom J Nowell","author_id":736,"author_profile":"https://wordpress.stackexchange.com/users/736","pm_score":1,"selected":false,"text":"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \n
    if ( have_posts() ) {\n    while ( have_posts() ) {\n        the_post(); \n        //\n        // Post Content here\n        //\n        the_content();\n    } // end while\n} // end if\n
    \n

    https://codex.wordpress.org/The_Loop

    \n"},{"answer_id":400401,"author":"seshadri mandal","author_id":216993,"author_profile":"https://wordpress.stackexchange.com/users/216993","pm_score":0,"selected":false,"text":"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \n \n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n
    \n\n"}],"string":"[\n {\n \"answer_id\": 400400,\n \"author\": \"Tom J Nowell\",\n \"author_id\": 736,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/736\",\n \"pm_score\": 1,\n \"selected\": false,\n \"text\": \"

    Your theme does not contain a main post loop, so there is no place for the plugin to do its work

    \\n
    if ( have_posts() ) {\\n    while ( have_posts() ) {\\n        the_post(); \\n        //\\n        // Post Content here\\n        //\\n        the_content();\\n    } // end while\\n} // end if\\n
    \\n

    https://codex.wordpress.org/The_Loop

    \\n\"\n },\n {\n \"answer_id\": 400401,\n \"author\": \"seshadri mandal\",\n \"author_id\": 216993,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/216993\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.

    \\n \\n
        &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \\n
    \\n\\n\"\n }\n]"},"date":{"kind":"string","value":"2021/12/28"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400712","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/217352/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400712\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/217352/\"\n]"},"input":{"kind":"string","value":"I am trying to change the classes for the \"View cart\" button after adding an item to the cart. What I tried to do is to hook into the \"woocommerce\\_ajax\\_added\\_to\\_cart\" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook:\n\n```\nfunction set_button_classes() {\n\n echo \"\";\n\n}\nadd_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); \n\n```\n\nAny pointers would be really appreciated."},"output":{"kind":"string","value":"Your theme does not contain a main post loop, so there is no place for the plugin to do its work\n\n```php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n\n```\n\n"}}},{"rowIdx":7657498,"cells":{"qid":{"kind":"number","value":400820,"string":"400,820"},"question":{"kind":"string","value":"

    I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?

    \n
    &lt;?php\n\nadd_action( 'template_redirect', function() {\n    if ( is_page( 4848 ) ) {\n        return;\n    }\n    wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n    //wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) );\n    exit;\n} );\n
    \n"},"answers":{"kind":"list like","value":[{"answer_id":400821,"author":"Maytha8","author_id":200755,"author_profile":"https://wordpress.stackexchange.com/users/200755","pm_score":0,"selected":false,"text":"

    Use user_can( wp_get_current_user(), 'administrator' ) to determine if the user is logged in and is an administrator.

    \n
    add_action( 'template_redirect', function() {\n  if ( is_page( 4848 ) ) {\n    return;\n  }\n  if (!user_can( wp_get_current_user(), 'administrator' )) {\n    wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n  }\n  exit;\n} );\n
    \n"},{"answer_id":400842,"author":"Buttered_Toast","author_id":192133,"author_profile":"https://wordpress.stackexchange.com/users/192133","pm_score":2,"selected":true,"text":"

    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted remove_action on it.
    \nWhat Maythan8 answered will work but it can be done with fewer functions.

    \n
    add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n    if (is_page(4848) || current_user_can('administrator')) return;\n    if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n
    \n

    You used esc_url_raw but this function is used for escaping url before DB storage, if your url is just for output use esc_url.
    \nAlso better to use wp_safe_redirect if you are redirecting from and to the same host.

    \n"}],"string":"[\n {\n \"answer_id\": 400821,\n \"author\": \"Maytha8\",\n \"author_id\": 200755,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/200755\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Use user_can( wp_get_current_user(), 'administrator' ) to determine if the user is logged in and is an administrator.

    \\n
    add_action( 'template_redirect', function() {\\n  if ( is_page( 4848 ) ) {\\n    return;\\n  }\\n  if (!user_can( wp_get_current_user(), 'administrator' )) {\\n    wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\\n  }\\n  exit;\\n} );\\n
    \\n\"\n },\n {\n \"answer_id\": 400842,\n \"author\": \"Buttered_Toast\",\n \"author_id\": 192133,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/192133\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted remove_action on it.
    \\nWhat Maythan8 answered will work but it can be done with fewer functions.

    \\n
    add_action('template_redirect', 'bt_maintenance_redirect');\\nfunction bt_maintenance_redirect () {\\n    if (is_page(4848) || current_user_can('administrator')) return;\\n    if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\\n}\\n
    \\n

    You used esc_url_raw but this function is used for escaping url before DB storage, if your url is just for output use esc_url.
    \\nAlso better to use wp_safe_redirect if you are redirecting from and to the same host.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2022/01/01"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400820","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/179876/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400820\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/179876/\"\n]"},"input":{"kind":"string","value":"I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?\n\n```\nI am moving a site from a Genesis theme to Colorlib theme. The genesis theme includes add_action( 'genesis_before_while', 'custom function' ); in a custom archive page, which loads restricted content from a template part. Is there a standard WP hook equivalent? or a work-around?

    \n"},"answers":{"kind":"list like","value":[{"answer_id":400821,"author":"Maytha8","author_id":200755,"author_profile":"https://wordpress.stackexchange.com/users/200755","pm_score":0,"selected":false,"text":"

    Use user_can( wp_get_current_user(), 'administrator' ) to determine if the user is logged in and is an administrator.

    \n
    add_action( 'template_redirect', function() {\n  if ( is_page( 4848 ) ) {\n    return;\n  }\n  if (!user_can( wp_get_current_user(), 'administrator' )) {\n    wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n  }\n  exit;\n} );\n
    \n"},{"answer_id":400842,"author":"Buttered_Toast","author_id":192133,"author_profile":"https://wordpress.stackexchange.com/users/192133","pm_score":2,"selected":true,"text":"

    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted remove_action on it.
    \nWhat Maythan8 answered will work but it can be done with fewer functions.

    \n
    add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n    if (is_page(4848) || current_user_can('administrator')) return;\n    if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n
    \n

    You used esc_url_raw but this function is used for escaping url before DB storage, if your url is just for output use esc_url.
    \nAlso better to use wp_safe_redirect if you are redirecting from and to the same host.

    \n"}],"string":"[\n {\n \"answer_id\": 400821,\n \"author\": \"Maytha8\",\n \"author_id\": 200755,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/200755\",\n \"pm_score\": 0,\n \"selected\": false,\n \"text\": \"

    Use user_can( wp_get_current_user(), 'administrator' ) to determine if the user is logged in and is an administrator.

    \\n
    add_action( 'template_redirect', function() {\\n  if ( is_page( 4848 ) ) {\\n    return;\\n  }\\n  if (!user_can( wp_get_current_user(), 'administrator' )) {\\n    wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\\n  }\\n  exit;\\n} );\\n
    \\n\"\n },\n {\n \"answer_id\": 400842,\n \"author\": \"Buttered_Toast\",\n \"author_id\": 192133,\n \"author_profile\": \"https://wordpress.stackexchange.com/users/192133\",\n \"pm_score\": 2,\n \"selected\": true,\n \"text\": \"

    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted remove_action on it.
    \\nWhat Maythan8 answered will work but it can be done with fewer functions.

    \\n
    add_action('template_redirect', 'bt_maintenance_redirect');\\nfunction bt_maintenance_redirect () {\\n    if (is_page(4848) || current_user_can('administrator')) return;\\n    if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\\n}\\n
    \\n

    You used esc_url_raw but this function is used for escaping url before DB storage, if your url is just for output use esc_url.
    \\nAlso better to use wp_safe_redirect if you are redirecting from and to the same host.

    \\n\"\n }\n]"},"date":{"kind":"string","value":"2022/01/02"},"metadata":{"kind":"list like","value":["https://wordpress.stackexchange.com/questions/400831","https://wordpress.stackexchange.com","https://wordpress.stackexchange.com/users/212424/"],"string":"[\n \"https://wordpress.stackexchange.com/questions/400831\",\n \"https://wordpress.stackexchange.com\",\n \"https://wordpress.stackexchange.com/users/212424/\"\n]"},"input":{"kind":"string","value":"I am moving a site from a Genesis theme to Colorlib theme. The genesis theme includes `add_action( 'genesis_before_while', 'custom function' );` in a custom archive page, which loads restricted content from a template part. Is there a standard WP hook equivalent? or a work-around?"},"output":{"kind":"string","value":"I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. \n\nWhat Maythan8 answered will work but it can be done with fewer functions.\n\n```php\nadd_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n\n```\n\nYou used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. \n\nAlso better to use `wp_safe_redirect` if you are redirecting from and to the same host."}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":76574,"numItemsPerPage":100,"numTotalItems":7658345,"offset":7657400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjA5ODc2MCwic3ViIjoiL2RhdGFzZXRzL2JpZ2NvZGUvY29kZS1leGNoYW5nZSIsImV4cCI6MTc1NjEwMjM2MCwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.cdgXre1HRffCfQ5qtfz0Qw76aVSyeocUxVe427YVABui-M5dUMHbF2rzt6Ocw24Eh_otnodRtle8lIwJs9EAAw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    qid
    int64
    4
    8.14M
    question
    stringlengths
    20
    48.3k
    answers
    list
    date
    stringlengths
    10
    10
    metadata
    list
    input
    stringlengths
    12
    45k
    output
    stringlengths
    2
    31.8k
    393,266
    <p>I've searched online and have not been able to find any answers to this one. I am in the middle of developing a new website and have started trying to work with the new theme.json feature in WordPress 5.8.</p> <p>I've had no problems setting the layout width and defining a color pallette, however, when it then comes to setting a custom font family the editor doesn't seem to pick this up.</p> <p>I have enqueued the custom Google font:</p> <pre><code>function prefix_block_styles() { wp_enqueue_style( 'prefix-editor-font', '//fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&amp;display=swap'); } add_action( 'enqueue_block_editor_assets', 'prefix_block_styles' ); </code></pre> <p>And then I have this as my current theme.json:</p> <pre><code>{ &quot;version&quot;:1, &quot;settings&quot;: { &quot;typography&quot;: { &quot;fontFamilies&quot;: [ { &quot;fontFamily&quot;: &quot;Helvetica Neue, Helvetica, Arial, sans-serif&quot;, &quot;slug&quot;: &quot;helvetica-arial&quot;, &quot;name&quot;: &quot;Helvetica or Arial&quot; }, { &quot;fontFamily&quot;: &quot;\&quot;Ubuntu\&quot;, sans-serif&quot;, &quot;slug&quot;: &quot;ubuntu-sansserif&quot;, &quot;name&quot;: &quot;Ubuntu&quot; } ] }, &quot;layout&quot;: { &quot;contentSize&quot;: &quot;1600px&quot;, &quot;wideSize&quot;: &quot;1600px&quot; } } } </code></pre> <p>When I then refresh the editor, it still loads in serif.</p> <p>Does anyone know what I am doing wrong here?</p> <p>Thanks</p>
    [ { "answer_id": 393459, "author": "Xavi", "author_id": 210356, "author_profile": "https://wordpress.stackexchange.com/users/210356", "pm_score": 3, "selected": false, "text": "<p>I had the same problem and I find out how to solve it:</p>\n<p>For each &quot;fontFamily&quot; inside &quot;fontFamilies&quot; array, you get a custom variable.\nFrom your example You can use both variables on your stylesheet or in theme.json:</p>\n<pre><code>--wp--preset--font-family--helvetica-arial\n--wp--preset--font-family--ubuntu-sansserif\n</code></pre>\n<p>And then you call the font like this:</p>\n<pre><code>{\n &quot;version&quot;:1,\n &quot;settings&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamilies&quot;: [\n {\n &quot;fontFamily&quot;: &quot;Helvetica Neue, Helvetica, Arial, sans-serif&quot;,\n &quot;slug&quot;: &quot;helvetica-arial&quot;,\n &quot;name&quot;: &quot;Helvetica or Arial&quot;\n },\n {\n &quot;fontFamily&quot;: &quot;\\&quot;Ubuntu\\&quot;, sans-serif&quot;,\n &quot;slug&quot;: &quot;ubuntu-sansserif&quot;,\n &quot;name&quot;: &quot;Ubuntu&quot;,\n &quot;google&quot;: &quot;family=Ubuntu:wght@300;400;500;700&amp;display=swap&quot;,\n\n }\n ]\n },\n &quot;layout&quot;: {\n &quot;contentSize&quot;: &quot;1600px&quot;,\n &quot;wideSize&quot;: &quot;1600px&quot;\n }\n },\n &quot;styles&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamily&quot;: &quot;var(--wp--preset--font-family--ubuntu-sansserif)&quot;,\n }\n }\n}\n</code></pre>\n<p>Sometimes you need to activate / deactivate your theme.</p>\n" }, { "answer_id": 398301, "author": "psorensen", "author_id": 38536, "author_profile": "https://wordpress.stackexchange.com/users/38536", "pm_score": 1, "selected": false, "text": "<p>At this time, <code>typography.fontFamilies</code> is only available in the Gutenberg plugin. The plugin must be installed for this setting to take effect. See the comparison toggle at <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings</a></p>\n" } ]
    2021/08/13
    [ "https://wordpress.stackexchange.com/questions/393266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104675/" ]
    I've searched online and have not been able to find any answers to this one. I am in the middle of developing a new website and have started trying to work with the new theme.json feature in WordPress 5.8. I've had no problems setting the layout width and defining a color pallette, however, when it then comes to setting a custom font family the editor doesn't seem to pick this up. I have enqueued the custom Google font: ``` function prefix_block_styles() { wp_enqueue_style( 'prefix-editor-font', '//fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap'); } add_action( 'enqueue_block_editor_assets', 'prefix_block_styles' ); ``` And then I have this as my current theme.json: ``` { "version":1, "settings": { "typography": { "fontFamilies": [ { "fontFamily": "Helvetica Neue, Helvetica, Arial, sans-serif", "slug": "helvetica-arial", "name": "Helvetica or Arial" }, { "fontFamily": "\"Ubuntu\", sans-serif", "slug": "ubuntu-sansserif", "name": "Ubuntu" } ] }, "layout": { "contentSize": "1600px", "wideSize": "1600px" } } } ``` When I then refresh the editor, it still loads in serif. Does anyone know what I am doing wrong here? Thanks
    I had the same problem and I find out how to solve it: For each "fontFamily" inside "fontFamilies" array, you get a custom variable. From your example You can use both variables on your stylesheet or in theme.json: ``` --wp--preset--font-family--helvetica-arial --wp--preset--font-family--ubuntu-sansserif ``` And then you call the font like this: ``` { "version":1, "settings": { "typography": { "fontFamilies": [ { "fontFamily": "Helvetica Neue, Helvetica, Arial, sans-serif", "slug": "helvetica-arial", "name": "Helvetica or Arial" }, { "fontFamily": "\"Ubuntu\", sans-serif", "slug": "ubuntu-sansserif", "name": "Ubuntu", "google": "family=Ubuntu:wght@300;400;500;700&display=swap", } ] }, "layout": { "contentSize": "1600px", "wideSize": "1600px" } }, "styles": { "typography": { "fontFamily": "var(--wp--preset--font-family--ubuntu-sansserif)", } } } ``` Sometimes you need to activate / deactivate your theme.
    393,309
    <p>I am getting an error on my WordPress website after changing the server. it's working on cPanel but not working on the AWS server.</p> <p>I haven't change anything in this file.</p> <p><a href="https://i.stack.imgur.com/qgniX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qgniX.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/i6RMO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i6RMO.png" alt="enter image description here" /></a></p>
    [ { "answer_id": 393459, "author": "Xavi", "author_id": 210356, "author_profile": "https://wordpress.stackexchange.com/users/210356", "pm_score": 3, "selected": false, "text": "<p>I had the same problem and I find out how to solve it:</p>\n<p>For each &quot;fontFamily&quot; inside &quot;fontFamilies&quot; array, you get a custom variable.\nFrom your example You can use both variables on your stylesheet or in theme.json:</p>\n<pre><code>--wp--preset--font-family--helvetica-arial\n--wp--preset--font-family--ubuntu-sansserif\n</code></pre>\n<p>And then you call the font like this:</p>\n<pre><code>{\n &quot;version&quot;:1,\n &quot;settings&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamilies&quot;: [\n {\n &quot;fontFamily&quot;: &quot;Helvetica Neue, Helvetica, Arial, sans-serif&quot;,\n &quot;slug&quot;: &quot;helvetica-arial&quot;,\n &quot;name&quot;: &quot;Helvetica or Arial&quot;\n },\n {\n &quot;fontFamily&quot;: &quot;\\&quot;Ubuntu\\&quot;, sans-serif&quot;,\n &quot;slug&quot;: &quot;ubuntu-sansserif&quot;,\n &quot;name&quot;: &quot;Ubuntu&quot;,\n &quot;google&quot;: &quot;family=Ubuntu:wght@300;400;500;700&amp;display=swap&quot;,\n\n }\n ]\n },\n &quot;layout&quot;: {\n &quot;contentSize&quot;: &quot;1600px&quot;,\n &quot;wideSize&quot;: &quot;1600px&quot;\n }\n },\n &quot;styles&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamily&quot;: &quot;var(--wp--preset--font-family--ubuntu-sansserif)&quot;,\n }\n }\n}\n</code></pre>\n<p>Sometimes you need to activate / deactivate your theme.</p>\n" }, { "answer_id": 398301, "author": "psorensen", "author_id": 38536, "author_profile": "https://wordpress.stackexchange.com/users/38536", "pm_score": 1, "selected": false, "text": "<p>At this time, <code>typography.fontFamilies</code> is only available in the Gutenberg plugin. The plugin must be installed for this setting to take effect. See the comparison toggle at <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings</a></p>\n" } ]
    2021/08/14
    [ "https://wordpress.stackexchange.com/questions/393309", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192859/" ]
    I am getting an error on my WordPress website after changing the server. it's working on cPanel but not working on the AWS server. I haven't change anything in this file. [![enter image description here](https://i.stack.imgur.com/qgniX.png)](https://i.stack.imgur.com/qgniX.png) [![enter image description here](https://i.stack.imgur.com/i6RMO.png)](https://i.stack.imgur.com/i6RMO.png)
    I had the same problem and I find out how to solve it: For each "fontFamily" inside "fontFamilies" array, you get a custom variable. From your example You can use both variables on your stylesheet or in theme.json: ``` --wp--preset--font-family--helvetica-arial --wp--preset--font-family--ubuntu-sansserif ``` And then you call the font like this: ``` { "version":1, "settings": { "typography": { "fontFamilies": [ { "fontFamily": "Helvetica Neue, Helvetica, Arial, sans-serif", "slug": "helvetica-arial", "name": "Helvetica or Arial" }, { "fontFamily": "\"Ubuntu\", sans-serif", "slug": "ubuntu-sansserif", "name": "Ubuntu", "google": "family=Ubuntu:wght@300;400;500;700&display=swap", } ] }, "layout": { "contentSize": "1600px", "wideSize": "1600px" } }, "styles": { "typography": { "fontFamily": "var(--wp--preset--font-family--ubuntu-sansserif)", } } } ``` Sometimes you need to activate / deactivate your theme.
    393,323
    <p>I have a 7-page static site I built with a page builder theme, child theme and some plugins. I would like to override all CSS (theme AND plugins) with custom CSS stylesheets on a page-by-page basis.</p> <p>How can I do this? Can I accomplish this with functions.php and my child theme? Please be explicit in your answer -- I'm still learning Wordpress!</p> <p><em>More info:</em> If you're curious, I used a handy tool -- <a href="http://purifycss.online" rel="nofollow noreferrer">purifycss.online</a> -- to remove unused CSS and saved the CSS stylesheet for each page. I wold like to remove all other CSS and apply these to their proper pages. PurifyCSS links to a <a href="https://www.webperftools.com/blog/how-to-remove-unused-css-in-wordpress/" rel="nofollow noreferrer">blog post</a> that partially describes this process. However, the post describes how to assign each stylesheet to a page type, not a page. I tried to modify the method for my needs but failed.</p>
    [ { "answer_id": 393459, "author": "Xavi", "author_id": 210356, "author_profile": "https://wordpress.stackexchange.com/users/210356", "pm_score": 3, "selected": false, "text": "<p>I had the same problem and I find out how to solve it:</p>\n<p>For each &quot;fontFamily&quot; inside &quot;fontFamilies&quot; array, you get a custom variable.\nFrom your example You can use both variables on your stylesheet or in theme.json:</p>\n<pre><code>--wp--preset--font-family--helvetica-arial\n--wp--preset--font-family--ubuntu-sansserif\n</code></pre>\n<p>And then you call the font like this:</p>\n<pre><code>{\n &quot;version&quot;:1,\n &quot;settings&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamilies&quot;: [\n {\n &quot;fontFamily&quot;: &quot;Helvetica Neue, Helvetica, Arial, sans-serif&quot;,\n &quot;slug&quot;: &quot;helvetica-arial&quot;,\n &quot;name&quot;: &quot;Helvetica or Arial&quot;\n },\n {\n &quot;fontFamily&quot;: &quot;\\&quot;Ubuntu\\&quot;, sans-serif&quot;,\n &quot;slug&quot;: &quot;ubuntu-sansserif&quot;,\n &quot;name&quot;: &quot;Ubuntu&quot;,\n &quot;google&quot;: &quot;family=Ubuntu:wght@300;400;500;700&amp;display=swap&quot;,\n\n }\n ]\n },\n &quot;layout&quot;: {\n &quot;contentSize&quot;: &quot;1600px&quot;,\n &quot;wideSize&quot;: &quot;1600px&quot;\n }\n },\n &quot;styles&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamily&quot;: &quot;var(--wp--preset--font-family--ubuntu-sansserif)&quot;,\n }\n }\n}\n</code></pre>\n<p>Sometimes you need to activate / deactivate your theme.</p>\n" }, { "answer_id": 398301, "author": "psorensen", "author_id": 38536, "author_profile": "https://wordpress.stackexchange.com/users/38536", "pm_score": 1, "selected": false, "text": "<p>At this time, <code>typography.fontFamilies</code> is only available in the Gutenberg plugin. The plugin must be installed for this setting to take effect. See the comparison toggle at <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings</a></p>\n" } ]
    2021/08/15
    [ "https://wordpress.stackexchange.com/questions/393323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210224/" ]
    I have a 7-page static site I built with a page builder theme, child theme and some plugins. I would like to override all CSS (theme AND plugins) with custom CSS stylesheets on a page-by-page basis. How can I do this? Can I accomplish this with functions.php and my child theme? Please be explicit in your answer -- I'm still learning Wordpress! *More info:* If you're curious, I used a handy tool -- [purifycss.online](http://purifycss.online) -- to remove unused CSS and saved the CSS stylesheet for each page. I wold like to remove all other CSS and apply these to their proper pages. PurifyCSS links to a [blog post](https://www.webperftools.com/blog/how-to-remove-unused-css-in-wordpress/) that partially describes this process. However, the post describes how to assign each stylesheet to a page type, not a page. I tried to modify the method for my needs but failed.
    I had the same problem and I find out how to solve it: For each "fontFamily" inside "fontFamilies" array, you get a custom variable. From your example You can use both variables on your stylesheet or in theme.json: ``` --wp--preset--font-family--helvetica-arial --wp--preset--font-family--ubuntu-sansserif ``` And then you call the font like this: ``` { "version":1, "settings": { "typography": { "fontFamilies": [ { "fontFamily": "Helvetica Neue, Helvetica, Arial, sans-serif", "slug": "helvetica-arial", "name": "Helvetica or Arial" }, { "fontFamily": "\"Ubuntu\", sans-serif", "slug": "ubuntu-sansserif", "name": "Ubuntu", "google": "family=Ubuntu:wght@300;400;500;700&display=swap", } ] }, "layout": { "contentSize": "1600px", "wideSize": "1600px" } }, "styles": { "typography": { "fontFamily": "var(--wp--preset--font-family--ubuntu-sansserif)", } } } ``` Sometimes you need to activate / deactivate your theme.
    393,352
    <p>I have a site that I am working on and I noticed that I get this error in my browser console:</p> <p>Failed to load resource: the server responded with a status of 404 ()</p> <p>It was trying to load a image file called 'bg-10-free-img.jpg'</p> <p>Now I did look in the console and <a href="https://i.stack.imgur.com/tWwQn.png" rel="nofollow noreferrer">I did see this Image file in the console</a> but when I try to go to the link where it should exist, I get an error 404 Page. I even checked in my hosting file directory and nothing with that name came up.</p> <p>For clarification, this is a site that is running on the latest version of PHP and Wordpress. The site I'm having trouble with is <a href="https://starlightdesigning.com" rel="nofollow noreferrer">https://starlightdesigning.com</a></p> <p>If anyone knows a fix for this issue that would be awesome!</p>
    [ { "answer_id": 393459, "author": "Xavi", "author_id": 210356, "author_profile": "https://wordpress.stackexchange.com/users/210356", "pm_score": 3, "selected": false, "text": "<p>I had the same problem and I find out how to solve it:</p>\n<p>For each &quot;fontFamily&quot; inside &quot;fontFamilies&quot; array, you get a custom variable.\nFrom your example You can use both variables on your stylesheet or in theme.json:</p>\n<pre><code>--wp--preset--font-family--helvetica-arial\n--wp--preset--font-family--ubuntu-sansserif\n</code></pre>\n<p>And then you call the font like this:</p>\n<pre><code>{\n &quot;version&quot;:1,\n &quot;settings&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamilies&quot;: [\n {\n &quot;fontFamily&quot;: &quot;Helvetica Neue, Helvetica, Arial, sans-serif&quot;,\n &quot;slug&quot;: &quot;helvetica-arial&quot;,\n &quot;name&quot;: &quot;Helvetica or Arial&quot;\n },\n {\n &quot;fontFamily&quot;: &quot;\\&quot;Ubuntu\\&quot;, sans-serif&quot;,\n &quot;slug&quot;: &quot;ubuntu-sansserif&quot;,\n &quot;name&quot;: &quot;Ubuntu&quot;,\n &quot;google&quot;: &quot;family=Ubuntu:wght@300;400;500;700&amp;display=swap&quot;,\n\n }\n ]\n },\n &quot;layout&quot;: {\n &quot;contentSize&quot;: &quot;1600px&quot;,\n &quot;wideSize&quot;: &quot;1600px&quot;\n }\n },\n &quot;styles&quot;: {\n &quot;typography&quot;: {\n &quot;fontFamily&quot;: &quot;var(--wp--preset--font-family--ubuntu-sansserif)&quot;,\n }\n }\n}\n</code></pre>\n<p>Sometimes you need to activate / deactivate your theme.</p>\n" }, { "answer_id": 398301, "author": "psorensen", "author_id": 38536, "author_profile": "https://wordpress.stackexchange.com/users/38536", "pm_score": 1, "selected": false, "text": "<p>At this time, <code>typography.fontFamilies</code> is only available in the Gutenberg plugin. The plugin must be installed for this setting to take effect. See the comparison toggle at <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/#settings</a></p>\n" } ]
    2021/08/16
    [ "https://wordpress.stackexchange.com/questions/393352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210265/" ]
    I have a site that I am working on and I noticed that I get this error in my browser console: Failed to load resource: the server responded with a status of 404 () It was trying to load a image file called 'bg-10-free-img.jpg' Now I did look in the console and [I did see this Image file in the console](https://i.stack.imgur.com/tWwQn.png) but when I try to go to the link where it should exist, I get an error 404 Page. I even checked in my hosting file directory and nothing with that name came up. For clarification, this is a site that is running on the latest version of PHP and Wordpress. The site I'm having trouble with is <https://starlightdesigning.com> If anyone knows a fix for this issue that would be awesome!
    I had the same problem and I find out how to solve it: For each "fontFamily" inside "fontFamilies" array, you get a custom variable. From your example You can use both variables on your stylesheet or in theme.json: ``` --wp--preset--font-family--helvetica-arial --wp--preset--font-family--ubuntu-sansserif ``` And then you call the font like this: ``` { "version":1, "settings": { "typography": { "fontFamilies": [ { "fontFamily": "Helvetica Neue, Helvetica, Arial, sans-serif", "slug": "helvetica-arial", "name": "Helvetica or Arial" }, { "fontFamily": "\"Ubuntu\", sans-serif", "slug": "ubuntu-sansserif", "name": "Ubuntu", "google": "family=Ubuntu:wght@300;400;500;700&display=swap", } ] }, "layout": { "contentSize": "1600px", "wideSize": "1600px" } }, "styles": { "typography": { "fontFamily": "var(--wp--preset--font-family--ubuntu-sansserif)", } } } ``` Sometimes you need to activate / deactivate your theme.
    393,511
    <p>i am currently trying to remove the draft(action) from the custom post type dropdown menu. I am sharing a screenshot it will help you to understand my question. I have no idea how to achieve this, is there any hook or method. Kindly help me out. Thank you in advance.</p> <p><a href="https://i.stack.imgur.com/5rlIW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5rlIW.png" alt="enter image description here" /></a></p>
    [ { "answer_id": 393516, "author": "Dipendra Pancholi", "author_id": 182923, "author_profile": "https://wordpress.stackexchange.com/users/182923", "pm_score": 2, "selected": false, "text": "<p>You can use the below code for this. You just need to change the &quot;posttype&quot; in the action name, for which you want to remove draft from the bulk action.</p>\n<pre><code>function remove_draft_from_bulk_actions( $actions ) {\n \n if( isset( $actions[ 'draft' ] ) ) {\n unset( $actions[ 'draft' ] );\n }\n\n return $actions;\n}\nadd_filter( 'bulk_actions-edit-posttype', 'remove_draft_from_bulk_actions', 99 );\n</code></pre>\n<p><strong>Below is the screenshot for this:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/NI0Zp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NI0Zp.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 398870, "author": "SQROM", "author_id": 215542, "author_profile": "https://wordpress.stackexchange.com/users/215542", "pm_score": 0, "selected": false, "text": "<p>this is for remove rank math bulks</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_draft_from_bulk_actions( $actions ) {\n \n if( isset( $actions[ 'rank_math_bulk_robots_noindex' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_noindex' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_nofollow' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_nofollow' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_index' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_index' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_remove_canonical' ] ) ) {\n unset( $actions[ 'rank_math_bulk_remove_canonical' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_redirect' ] ) ) {\n unset( $actions[ 'rank_math_bulk_redirect' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_stop_redirect' ] ) ) {\n unset( $actions[ 'rank_math_bulk_stop_redirect' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_schema_none' ] ) ) {\n unset( $actions[ 'rank_math_bulk_schema_none' ] );\n }\n if( isset( $actions[ 'bulk-action-selector-top' ] ) ) {\n unset( $actions[ 'bulk-action-selector-top' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_schema_default' ] ) ) {\n unset( $actions[ 'rank_math_bulk_schema_default' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_follow' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_follow' ] );\n }\n if( isset( $actions[ 'rank_math_options' ] ) ) {\n unset( $actions[ 'rank_math_options' ] );\n }\n return $actions;\n}\nadd_filter( 'bulk_actions-edit-post', 'remove_draft_from_bulk_actions', 99 );\n</code></pre>\n" } ]
    2021/08/19
    [ "https://wordpress.stackexchange.com/questions/393511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/206959/" ]
    i am currently trying to remove the draft(action) from the custom post type dropdown menu. I am sharing a screenshot it will help you to understand my question. I have no idea how to achieve this, is there any hook or method. Kindly help me out. Thank you in advance. [![enter image description here](https://i.stack.imgur.com/5rlIW.png)](https://i.stack.imgur.com/5rlIW.png)
    You can use the below code for this. You just need to change the "posttype" in the action name, for which you want to remove draft from the bulk action. ``` function remove_draft_from_bulk_actions( $actions ) { if( isset( $actions[ 'draft' ] ) ) { unset( $actions[ 'draft' ] ); } return $actions; } add_filter( 'bulk_actions-edit-posttype', 'remove_draft_from_bulk_actions', 99 ); ``` **Below is the screenshot for this:** [![enter image description here](https://i.stack.imgur.com/NI0Zp.png)](https://i.stack.imgur.com/NI0Zp.png)
    393,595
    <p>I'm making a shortcode function that collects data from WordPress media library</p> <pre><code>function byn_recent_resources_shortcode($atts, $content = null) { global $post; extract(shortcode_atts(array( 'group' =&gt; 'public', 'num' =&gt; '1', 'orderby' =&gt; 'post_date', ), $atts)); $args = array( 'post_status' =&gt; 'inherit', 'posts_per_page' =&gt; $num, 'post_type' =&gt; 'attachment', ); $args['tax_query'] = array( array( 'taxonomy' =&gt; 'group', 'terms' =&gt; array( $group ), 'field' =&gt; 'slug', ), ); $output = ''; $posts = get_posts($args); foreach($posts as $post) { setup_postdata($post); $output .= ' &lt;article&gt; &lt;div class=&quot;thumbnail&quot;&gt; // IF STATEMENT GOES HERE // &lt;/div&gt; &lt;/article&gt; '; } wp_reset_postdata(); return '&lt;div class=&quot;resource-list&quot; id=&quot;resource-list&quot;&gt;&lt;div class=&quot;post-outer-wrap&quot;&gt;'. $output .'&lt;/div&gt;&lt;/div&gt;'; } add_shortcode('byn-recent-resources', 'byn_recent_resources_shortcode'); </code></pre> <p>Inside the <strong><code>&lt;div class=&quot;thumbnail&quot;&gt;</code></strong> output, I'm planning to enable <strong><code>&lt;if&gt;</code></strong> statement like so</p> <pre><code>&lt;?php if ( wp_attachment_is_image( $id ) ) { ?&gt; // Do option A &lt;?php } else { ?&gt; // Do option B &lt;?php } ?&gt; </code></pre> <p>How do I do that?</p>
    [ { "answer_id": 393516, "author": "Dipendra Pancholi", "author_id": 182923, "author_profile": "https://wordpress.stackexchange.com/users/182923", "pm_score": 2, "selected": false, "text": "<p>You can use the below code for this. You just need to change the &quot;posttype&quot; in the action name, for which you want to remove draft from the bulk action.</p>\n<pre><code>function remove_draft_from_bulk_actions( $actions ) {\n \n if( isset( $actions[ 'draft' ] ) ) {\n unset( $actions[ 'draft' ] );\n }\n\n return $actions;\n}\nadd_filter( 'bulk_actions-edit-posttype', 'remove_draft_from_bulk_actions', 99 );\n</code></pre>\n<p><strong>Below is the screenshot for this:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/NI0Zp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NI0Zp.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 398870, "author": "SQROM", "author_id": 215542, "author_profile": "https://wordpress.stackexchange.com/users/215542", "pm_score": 0, "selected": false, "text": "<p>this is for remove rank math bulks</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_draft_from_bulk_actions( $actions ) {\n \n if( isset( $actions[ 'rank_math_bulk_robots_noindex' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_noindex' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_nofollow' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_nofollow' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_index' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_index' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_remove_canonical' ] ) ) {\n unset( $actions[ 'rank_math_bulk_remove_canonical' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_redirect' ] ) ) {\n unset( $actions[ 'rank_math_bulk_redirect' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_stop_redirect' ] ) ) {\n unset( $actions[ 'rank_math_bulk_stop_redirect' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_schema_none' ] ) ) {\n unset( $actions[ 'rank_math_bulk_schema_none' ] );\n }\n if( isset( $actions[ 'bulk-action-selector-top' ] ) ) {\n unset( $actions[ 'bulk-action-selector-top' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_schema_default' ] ) ) {\n unset( $actions[ 'rank_math_bulk_schema_default' ] );\n }\n if( isset( $actions[ 'rank_math_bulk_robots_follow' ] ) ) {\n unset( $actions[ 'rank_math_bulk_robots_follow' ] );\n }\n if( isset( $actions[ 'rank_math_options' ] ) ) {\n unset( $actions[ 'rank_math_options' ] );\n }\n return $actions;\n}\nadd_filter( 'bulk_actions-edit-post', 'remove_draft_from_bulk_actions', 99 );\n</code></pre>\n" } ]
    2021/08/21
    [ "https://wordpress.stackexchange.com/questions/393595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64468/" ]
    I'm making a shortcode function that collects data from WordPress media library ``` function byn_recent_resources_shortcode($atts, $content = null) { global $post; extract(shortcode_atts(array( 'group' => 'public', 'num' => '1', 'orderby' => 'post_date', ), $atts)); $args = array( 'post_status' => 'inherit', 'posts_per_page' => $num, 'post_type' => 'attachment', ); $args['tax_query'] = array( array( 'taxonomy' => 'group', 'terms' => array( $group ), 'field' => 'slug', ), ); $output = ''; $posts = get_posts($args); foreach($posts as $post) { setup_postdata($post); $output .= ' <article> <div class="thumbnail"> // IF STATEMENT GOES HERE // </div> </article> '; } wp_reset_postdata(); return '<div class="resource-list" id="resource-list"><div class="post-outer-wrap">'. $output .'</div></div>'; } add_shortcode('byn-recent-resources', 'byn_recent_resources_shortcode'); ``` Inside the **`<div class="thumbnail">`** output, I'm planning to enable **`<if>`** statement like so ``` <?php if ( wp_attachment_is_image( $id ) ) { ?> // Do option A <?php } else { ?> // Do option B <?php } ?> ``` How do I do that?
    You can use the below code for this. You just need to change the "posttype" in the action name, for which you want to remove draft from the bulk action. ``` function remove_draft_from_bulk_actions( $actions ) { if( isset( $actions[ 'draft' ] ) ) { unset( $actions[ 'draft' ] ); } return $actions; } add_filter( 'bulk_actions-edit-posttype', 'remove_draft_from_bulk_actions', 99 ); ``` **Below is the screenshot for this:** [![enter image description here](https://i.stack.imgur.com/NI0Zp.png)](https://i.stack.imgur.com/NI0Zp.png)
    393,689
    <p>I'm trying to add a Button, which generates a random URL every time it's clicked.</p> <p>I found :</p> <pre><code>&lt;a href=&quot;&lt;?php echo ( &quot;http://meet.jit.si/&quot; . rand(1000, 9000) )?&gt;&quot; target=&quot;_blank&quot;&gt; click here &lt;/a&gt; </code></pre> <p>But I have no idea where to post this into.</p>
    [ { "answer_id": 393695, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 2, "selected": false, "text": "<p>It looks like your code works as written.</p>\n<p>Alternatively, you can generate an alphanumeric string using <a href=\"https://www.php.net/manual/en/function.uniqid.php\" rel=\"nofollow noreferrer\"><code>uniqid()</code></a>...</p>\n<pre><code>&lt;a href=&quot;http://meet.jit.si/&lt;?php echo uniqid()?&gt;&quot; target=&quot;_blank&quot;&gt; click here &lt;/a&gt;\n</code></pre>\n<hr />\n<p><strong>EDIT:</strong> Modified code based on additional information.</p>\n<p>This should create a shortcode that allows you to easily add a button to a unique meeting link by adding <code>[rand_jitsi_btn]</code> to a post/page:</p>\n<pre><code>// hook our shortcode creation to `init` so that WordPress has time to initialize properly\nadd_action( 'init', 'add_custom_shortcode' );\nfunction add_custom_shortcode() {\n add_shortcode( 'rand_jitsi_btn', 'create_rand_jitsi_btn' );\n}\n// Code to create the button\nfunction create_rand_jitsi_btn() {\n return '&lt;a href=&quot;http://meet.jit.si/' . uniqid() . '&quot; target=&quot;_blank&quot;&gt; Launch Meeting &lt;/a&gt;';\n}\n</code></pre>\n<p>I haven't tested this code, but it <em>should</em> work if you place it in your child theme's <code>functions.php</code> file.</p>\n<p>Note: You can use something like <code>random_int()</code> instead of <code>uniqid()</code> if you need <em>numeric</em> randoms.</p>\n" }, { "answer_id": 393696, "author": "vlood", "author_id": 733, "author_profile": "https://wordpress.stackexchange.com/users/733", "pm_score": 0, "selected": false, "text": "<p>You could create a shortcode for the button and use that for inserting a link with a random Jitsi room anywhere in the content of your site or even in the widgets. Make the button label a variable in the shortcode so that you can further customise it.</p>\n" } ]
    2021/08/24
    [ "https://wordpress.stackexchange.com/questions/393689", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210595/" ]
    I'm trying to add a Button, which generates a random URL every time it's clicked. I found : ``` <a href="<?php echo ( "http://meet.jit.si/" . rand(1000, 9000) )?>" target="_blank"> click here </a> ``` But I have no idea where to post this into.
    It looks like your code works as written. Alternatively, you can generate an alphanumeric string using [`uniqid()`](https://www.php.net/manual/en/function.uniqid.php)... ``` <a href="http://meet.jit.si/<?php echo uniqid()?>" target="_blank"> click here </a> ``` --- **EDIT:** Modified code based on additional information. This should create a shortcode that allows you to easily add a button to a unique meeting link by adding `[rand_jitsi_btn]` to a post/page: ``` // hook our shortcode creation to `init` so that WordPress has time to initialize properly add_action( 'init', 'add_custom_shortcode' ); function add_custom_shortcode() { add_shortcode( 'rand_jitsi_btn', 'create_rand_jitsi_btn' ); } // Code to create the button function create_rand_jitsi_btn() { return '<a href="http://meet.jit.si/' . uniqid() . '" target="_blank"> Launch Meeting </a>'; } ``` I haven't tested this code, but it *should* work if you place it in your child theme's `functions.php` file. Note: You can use something like `random_int()` instead of `uniqid()` if you need *numeric* randoms.
    393,717
    <p>due to debugging and error hunting in a plugin, I have a quick question.</p> <p>What does $wpdb-&gt;get_row() return in case there are no results? The documentation says:</p> <pre><code>(array|object|null|void) Database query result in format specified by $output or null on failure. </code></pre> <p>But when looking at the source code, it rather seems like it returns &quot;null&quot;...</p> <p>A quick help would be appreciated, I always thought that it returns an empty array but I might be mistaken!</p>
    [ { "answer_id": 393718, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wpdb/#select-a-row\" rel=\"nofollow noreferrer\">From the docs</a>: <em>Returns <strong>null</strong> if no result is found...</em></p>\n" }, { "answer_id": 393724, "author": "Howard E", "author_id": 57589, "author_profile": "https://wordpress.stackexchange.com/users/57589", "pm_score": 0, "selected": false, "text": "<p>Yes, the docs are correct... but to check you could do something simple like</p>\n<pre><code>&lt;?php\nglobal $wpdb;\n$result = $wpdb-&gt;get_row(&quot;SELECT * from $wpdb-&gt;posts where ID = '9999999'&quot;);\necho '&lt;pre&gt;'; var_dump( $result ); echo '&lt;/pre&gt;';\n</code></pre>\n<p>Where the resulting output is</p>\n<pre><code>NULL\n</code></pre>\n" } ]
    2021/08/24
    [ "https://wordpress.stackexchange.com/questions/393717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153053/" ]
    due to debugging and error hunting in a plugin, I have a quick question. What does $wpdb->get\_row() return in case there are no results? The documentation says: ``` (array|object|null|void) Database query result in format specified by $output or null on failure. ``` But when looking at the source code, it rather seems like it returns "null"... A quick help would be appreciated, I always thought that it returns an empty array but I might be mistaken!
    [From the docs](https://developer.wordpress.org/reference/classes/wpdb/#select-a-row): *Returns **null** if no result is found...*
    393,728
    <p>I'm making a button shortcode that requires to attach extra HTML element to <code>wp_foot</code> for each shortcode added.</p> <pre><code>function action_button_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'title' =&gt; 'Title', 'color' =&gt; 'blue', // blue, green 'url' =&gt; 'url', 'icon' =&gt; 'arrow', // arrow, download, email, search, account, lock 'level' =&gt; 'primary', // primary, secondary, tertiary 'target' =&gt; 'self', // blank, self ), $atts )); if($target == 'modal'){ return '&lt;span class=&quot;byn-btn btn-' . $level . ' bg-' . $color . ' icon-' . $icon . '&quot; data-toggle=&quot;modal&quot; data-target=&quot;#modal' . url_to_postid( $url ) . '&quot;&gt;&lt;span&gt;' . $title . '&lt;/span&gt;&lt;/span&gt;'; } else { return '&lt;a href=&quot;' . $url . '&quot; class=&quot;byn-btn btn-' . $level . ' bg-' . $color . ' icon-' . $icon . '&quot; target=&quot;_' . $target . '&quot;&gt;&lt;span&gt;' . $title . '&lt;/span&gt;&lt;/a&gt;'; } $content = wpautop(trim($content)); } add_shortcode( 'ci-action-button', 'action_button_shortcode' ); </code></pre> <p>When user set <code>'target' =&gt; 'modal'</code>, it will add this extra HTML to <code>wp_foot</code>. Something like loop, since there can be multiple buttons added to the page</p> <pre><code>&lt;div class=&quot;modal fade&quot; id=&quot;modal' . url_to_postid( $url ) . '&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;modal' . url_to_postid( $url ) . 'Label&quot; aria-hidden=&quot;true&quot;&gt; &lt;div class=&quot;modal-dialog modal-dialog-centered&quot; role=&quot;document&quot;&gt; &lt;div class=&quot;modal-content subscribe-fields&quot;&gt; &lt;div class=&quot;modal-body&quot;&gt; &lt;div class=&quot;fullframe&quot;&gt;&lt;iframe width=&quot;100%&quot; src=&quot;'. $url .'&quot; class=&quot;fullHeight&quot;&gt;&lt;/iframe&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How to do that?</p>
    [ { "answer_id": 393718, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wpdb/#select-a-row\" rel=\"nofollow noreferrer\">From the docs</a>: <em>Returns <strong>null</strong> if no result is found...</em></p>\n" }, { "answer_id": 393724, "author": "Howard E", "author_id": 57589, "author_profile": "https://wordpress.stackexchange.com/users/57589", "pm_score": 0, "selected": false, "text": "<p>Yes, the docs are correct... but to check you could do something simple like</p>\n<pre><code>&lt;?php\nglobal $wpdb;\n$result = $wpdb-&gt;get_row(&quot;SELECT * from $wpdb-&gt;posts where ID = '9999999'&quot;);\necho '&lt;pre&gt;'; var_dump( $result ); echo '&lt;/pre&gt;';\n</code></pre>\n<p>Where the resulting output is</p>\n<pre><code>NULL\n</code></pre>\n" } ]
    2021/08/25
    [ "https://wordpress.stackexchange.com/questions/393728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64468/" ]
    I'm making a button shortcode that requires to attach extra HTML element to `wp_foot` for each shortcode added. ``` function action_button_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'title' => 'Title', 'color' => 'blue', // blue, green 'url' => 'url', 'icon' => 'arrow', // arrow, download, email, search, account, lock 'level' => 'primary', // primary, secondary, tertiary 'target' => 'self', // blank, self ), $atts )); if($target == 'modal'){ return '<span class="byn-btn btn-' . $level . ' bg-' . $color . ' icon-' . $icon . '" data-toggle="modal" data-target="#modal' . url_to_postid( $url ) . '"><span>' . $title . '</span></span>'; } else { return '<a href="' . $url . '" class="byn-btn btn-' . $level . ' bg-' . $color . ' icon-' . $icon . '" target="_' . $target . '"><span>' . $title . '</span></a>'; } $content = wpautop(trim($content)); } add_shortcode( 'ci-action-button', 'action_button_shortcode' ); ``` When user set `'target' => 'modal'`, it will add this extra HTML to `wp_foot`. Something like loop, since there can be multiple buttons added to the page ``` <div class="modal fade" id="modal' . url_to_postid( $url ) . '" tabindex="-1" role="dialog" aria-labelledby="modal' . url_to_postid( $url ) . 'Label" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content subscribe-fields"> <div class="modal-body"> <div class="fullframe"><iframe width="100%" src="'. $url .'" class="fullHeight"></iframe></div> </div> </div> </div> </div> ``` How to do that?
    [From the docs](https://developer.wordpress.org/reference/classes/wpdb/#select-a-row): *Returns **null** if no result is found...*
    393,746
    <p>We have our blog posts on a custom page with a custom pagination. For example a blog post name is url.de/postname instead of url.de/blog/postname.</p> <p>Therefore we have a page /blog/ which has the pagination on it. The links from the pagination module like /blog/2/ lead to a 404 error page, because the /page/ part is missing.</p> <p>I cannot edit the page urls - therefore i would like to use a redirect rule for this.</p> <p>What i got till now:</p> <pre><code>function my_pagination_rewrite() { add_rewrite_rule( '(([^/]+/)*blog)/?([0-9]{1,})/?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[3]', 'top' ); } add_action( 'init', 'my_pagination_rewrite' ); </code></pre> <p>But this leads to /blog/2/page/2 --&gt; 404.</p> <p>How can i get this code to return /blog/page/2 or just return /blog/2/ (and show the content of /blog/page/2)</p> <p>Thanks for help!</p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/25
    [ "https://wordpress.stackexchange.com/questions/393746", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17691/" ]
    We have our blog posts on a custom page with a custom pagination. For example a blog post name is url.de/postname instead of url.de/blog/postname. Therefore we have a page /blog/ which has the pagination on it. The links from the pagination module like /blog/2/ lead to a 404 error page, because the /page/ part is missing. I cannot edit the page urls - therefore i would like to use a redirect rule for this. What i got till now: ``` function my_pagination_rewrite() { add_rewrite_rule( '(([^/]+/)*blog)/?([0-9]{1,})/?$', 'index.php?pagename=$matches[1]&paged=$matches[3]', 'top' ); } add_action( 'init', 'my_pagination_rewrite' ); ``` But this leads to /blog/2/page/2 --> 404. How can i get this code to return /blog/page/2 or just return /blog/2/ (and show the content of /blog/page/2) Thanks for help!
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,786
    <p>I'm using ACF to add categories color. I display them in the articles loop.</p> <p>I would like to retrieve the parent category color if the child color is empty. If the parent is also empty, get the primary color.</p> <p>Here is what I have:</p> <pre><code>$terms = get_the_terms( get_the_ID(), 'category' ); if ( $terms ) { foreach ( $terms as $term ) { $cat_id = $term-&gt;term_id; } $cat_color = get_field('category-color', 'category' . '_' . $cat_id); if ( empty( $cat_color ) ) { $cat_color = // Get the parent category color; } else { $cat_color = get_field('primary-color', 'option'); } echo '&lt;div class=&quot;post_loop-cat&quot; style=&quot;background-color: '.$cat_color.';&quot;&gt;' . $term-&gt;name . '&lt;/div&gt;'; } </code></pre> <p>How can I get the color of the parent category?</p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/26
    [ "https://wordpress.stackexchange.com/questions/393786", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210698/" ]
    I'm using ACF to add categories color. I display them in the articles loop. I would like to retrieve the parent category color if the child color is empty. If the parent is also empty, get the primary color. Here is what I have: ``` $terms = get_the_terms( get_the_ID(), 'category' ); if ( $terms ) { foreach ( $terms as $term ) { $cat_id = $term->term_id; } $cat_color = get_field('category-color', 'category' . '_' . $cat_id); if ( empty( $cat_color ) ) { $cat_color = // Get the parent category color; } else { $cat_color = get_field('primary-color', 'option'); } echo '<div class="post_loop-cat" style="background-color: '.$cat_color.';">' . $term->name . '</div>'; } ``` How can I get the color of the parent category?
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,799
    <h3>Goal</h3> <p>Every time an admin clicks on the &quot;Trash&quot; button below a comment, refresh the page. If the comment was trashed while the admin was in the &quot;All&quot; category, he should be in the &quot;All&quot; category again after the refresh. If he was in the &quot;Pending&quot; category, he should be there again after the refresh.</p> <h3>Why</h3> <p>I'm developing a plugin that has a function hooked on <code>init</code> and will trash comments that are past a certain age. The <code>init</code> hook runs when the button &quot;Trash&quot; below a comment is clicked so as the admin is e.g. in the &quot;Pending&quot; category and trashes a comment, it is possible other comments shown in the table have been trashed in the meantime by my function so the admin should no longer see those other comments after he has trashed the comment.</p> <h3>Things tried</h3> <ol> <li>Tried hooking the script mentioned in <a href="https://wordpress.stackexchange.com/a/235639/210026">this answer</a> on the <code>trashed_comment</code> action with no success.</li> </ol> <pre><code>add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { echo '&lt;script&gt;location.reload();&lt;/script&gt;'; } </code></pre> <ol start="2"> <li>Also tried using <code>set_current_screen( 'edit-comments' )</code> on the <code>trashed_comment</code> action with no success.</li> </ol> <pre><code>add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { set_current_screen( 'edit-comments' ); } </code></pre> <ol start="3"> <li>Tried hooking the script mentioned in <a href="https://stackoverflow.com/a/13893949">this answer</a> on the <code>trashed_comment</code> action with no success.</li> </ol> <pre><code>add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { Header('Location: '.$_SERVER['PHP_SELF']); } </code></pre> <ol start="4"> <li>Tried hooking the script mentioned in <a href="https://stackoverflow.com/a/16073407">this answer</a> on the <code>trashed_comment</code> action with no success.</li> </ol> <pre><code>add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { $page = $_SERVER['PHP_SELF']; echo '&lt;meta http-equiv=&quot;Refresh&quot; content=&quot;0;' . $page . '&quot;&gt;; } </code></pre>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/26
    [ "https://wordpress.stackexchange.com/questions/393799", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210026/" ]
    ### Goal Every time an admin clicks on the "Trash" button below a comment, refresh the page. If the comment was trashed while the admin was in the "All" category, he should be in the "All" category again after the refresh. If he was in the "Pending" category, he should be there again after the refresh. ### Why I'm developing a plugin that has a function hooked on `init` and will trash comments that are past a certain age. The `init` hook runs when the button "Trash" below a comment is clicked so as the admin is e.g. in the "Pending" category and trashes a comment, it is possible other comments shown in the table have been trashed in the meantime by my function so the admin should no longer see those other comments after he has trashed the comment. ### Things tried 1. Tried hooking the script mentioned in [this answer](https://wordpress.stackexchange.com/a/235639/210026) on the `trashed_comment` action with no success. ``` add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { echo '<script>location.reload();</script>'; } ``` 2. Also tried using `set_current_screen( 'edit-comments' )` on the `trashed_comment` action with no success. ``` add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { set_current_screen( 'edit-comments' ); } ``` 3. Tried hooking the script mentioned in [this answer](https://stackoverflow.com/a/13893949) on the `trashed_comment` action with no success. ``` add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { Header('Location: '.$_SERVER['PHP_SELF']); } ``` 4. Tried hooking the script mentioned in [this answer](https://stackoverflow.com/a/16073407) on the `trashed_comment` action with no success. ``` add_action( 'trashed_comment', 'my_refresh_function', 10, 2 ); function my_refresh_function( $comment_ID, $comment_obj ) { $page = $_SERVER['PHP_SELF']; echo '<meta http-equiv="Refresh" content="0;' . $page . '">; } ```
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,801
    <p>I've created a Custom Post Type called 'Item' and added a multi-upload file/image/video field type but I'm not able to figure out how to register that custom field with WPGraphQL. Here's how I registered my CPT with WPGraphQL:</p> <pre class="lang-php prettyprint-override"><code> add_filter( 'register_post_type_args', function( $args, $post_type ) { if ( 'item' === $post_type ) { $args['show_in_graphql'] = true; $args['graphql_single_name'] = 'item'; $args['graphql_plural_name'] = 'items'; } return $args; }, 10, 2 ); </code></pre> <p>Any suggestions or can someone point me in the right direction for documentation? I've gotten different answers in my search and nothing has worked so far. Thanks!</p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/26
    [ "https://wordpress.stackexchange.com/questions/393801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210715/" ]
    I've created a Custom Post Type called 'Item' and added a multi-upload file/image/video field type but I'm not able to figure out how to register that custom field with WPGraphQL. Here's how I registered my CPT with WPGraphQL: ```php add_filter( 'register_post_type_args', function( $args, $post_type ) { if ( 'item' === $post_type ) { $args['show_in_graphql'] = true; $args['graphql_single_name'] = 'item'; $args['graphql_plural_name'] = 'items'; } return $args; }, 10, 2 ); ``` Any suggestions or can someone point me in the right direction for documentation? I've gotten different answers in my search and nothing has worked so far. Thanks!
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,829
    <p>I want to add custom overlay search to my WordPress site using add action. Somehow, it is not triggering the javascripts to show the overlay html. However, it is working in a browser when I test simply in browser by saving as html, <a href="https://js.do/code/overlayworkingcode" rel="nofollow noreferrer">can be checked here</a>. How can I properly add them n functions.php to run these codes.</p> <p>Here is my codes which I add to functions.php. Even, the scripts are also present when the page loads. The searchbox contains the onclick event.</p> <p>The form code</p> <pre><code>&lt;form method=&quot;get&quot; id=&quot;search&quot; action=&quot;https://tatest.tutorialsart.com/&quot;&gt; &lt;input id=&quot;search-input&quot; inputmode=&quot;search&quot; onclick=&quot;openSearch()&quot; type=&quot;text&quot; name=&quot;s&quot; title=&quot;Search for&quot; placeholder=&quot;Search for&quot; /&gt; &lt;button id=&quot;search-submit&quot; type=&quot;submit&quot;&gt; &lt;span class=&quot;tie-icon-search tie-search-icon&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; &lt;span class=&quot;screen-reader-text&quot;&gt;Search for&lt;/span&gt; &lt;/button&gt; &lt;/form&gt; </code></pre> <p>The scripts for triggering the overlay in functions.php</p> <pre><code>add_action( 'wp_footer', 'Search_trigger_script' ); function Search_trigger_script() { ?&gt; &lt;script type=&quot;text/javascript&quot;&gt; function openSearch() { document.getElementById(&quot;myOverlay&quot;).style.display = &quot;block&quot;; } function closeSearch() { document.getElementById(&quot;myOverlay&quot;).style.display = &quot;none&quot;; } &lt;/script&gt; &lt;?php } </code></pre> <p>The html overlay code in functions.php</p> <pre><code>add_action( 'wp_footer', 'Search_overlay_html' ); function Search_overlay_html() { ?&gt; &lt;html&gt; &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css&quot;&gt; &lt;style&gt; body { font-family: Arial; } * { box-sizing: border-box; } .openBtn { background: #f1f1f1; border: none; padding: 10px 15px; font-size: 20px; cursor: pointer; } .openBtn:hover { background: #bbb; } .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.9); } .overlay-content { position: relative; top: 2%; width: 80%; text-align: center; margin-top: 30px; margin: auto; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; cursor: pointer; color: white; } .overlay .closebtn:hover { color: #ccc; } .overlay input[type=text] { padding: 15px; font-size: 17px; border: none; float: left; width: 80%; background: white; } .overlay input[type=text]:hover { background: #f1f1f1; } .overlay button { float: left; width: 20%; padding: 15px; background: #ddd; font-size: 17px; border: none; cursor: pointer; } .overlay button:hover { background: #bbb; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;myOverlay&quot; class=&quot;overlay&quot;&gt; &lt;span class=&quot;closebtn&quot; onclick=&quot;closeSearch()&quot; title=&quot;Close Overlay&quot;&gt;×&lt;/span&gt; &lt;div class=&quot;overlay-content&quot;&gt; &lt;form action=&quot;/action_page.php&quot;&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Search..&quot; name=&quot;search&quot;&gt; &lt;button type=&quot;submit&quot;&gt;&lt;i class=&quot;fa fa-search&quot;&gt;&lt;/i&gt;&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php } </code></pre>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/26
    [ "https://wordpress.stackexchange.com/questions/393829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201013/" ]
    I want to add custom overlay search to my WordPress site using add action. Somehow, it is not triggering the javascripts to show the overlay html. However, it is working in a browser when I test simply in browser by saving as html, [can be checked here](https://js.do/code/overlayworkingcode). How can I properly add them n functions.php to run these codes. Here is my codes which I add to functions.php. Even, the scripts are also present when the page loads. The searchbox contains the onclick event. The form code ``` <form method="get" id="search" action="https://tatest.tutorialsart.com/"> <input id="search-input" inputmode="search" onclick="openSearch()" type="text" name="s" title="Search for" placeholder="Search for" /> <button id="search-submit" type="submit"> <span class="tie-icon-search tie-search-icon" aria-hidden="true"></span> <span class="screen-reader-text">Search for</span> </button> </form> ``` The scripts for triggering the overlay in functions.php ``` add_action( 'wp_footer', 'Search_trigger_script' ); function Search_trigger_script() { ?> <script type="text/javascript"> function openSearch() { document.getElementById("myOverlay").style.display = "block"; } function closeSearch() { document.getElementById("myOverlay").style.display = "none"; } </script> <?php } ``` The html overlay code in functions.php ``` add_action( 'wp_footer', 'Search_overlay_html' ); function Search_overlay_html() { ?> <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { font-family: Arial; } * { box-sizing: border-box; } .openBtn { background: #f1f1f1; border: none; padding: 10px 15px; font-size: 20px; cursor: pointer; } .openBtn:hover { background: #bbb; } .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.9); } .overlay-content { position: relative; top: 2%; width: 80%; text-align: center; margin-top: 30px; margin: auto; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; cursor: pointer; color: white; } .overlay .closebtn:hover { color: #ccc; } .overlay input[type=text] { padding: 15px; font-size: 17px; border: none; float: left; width: 80%; background: white; } .overlay input[type=text]:hover { background: #f1f1f1; } .overlay button { float: left; width: 20%; padding: 15px; background: #ddd; font-size: 17px; border: none; cursor: pointer; } .overlay button:hover { background: #bbb; } </style> </head> <body> <div id="myOverlay" class="overlay"> <span class="closebtn" onclick="closeSearch()" title="Close Overlay">×</span> <div class="overlay-content"> <form action="/action_page.php"> <input type="text" placeholder="Search.." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> </body> </html> <?php } ```
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,836
    <p>I have successfully changed the name of a specific page using this code in my functions.php file:</p> <pre><code>add_filter('pre_get_document_title', 'change_my_property_title'); function change_my_property_title($title) { if ( is_page('property') ) { return 'Property'; } return $title; } </code></pre> <p>My problem is I can't figure out how to change the name to an actual php variable that is on the property page. I am pulling property information from a json url and would like the address to be the title. If I try to point to the variable in my return statement nothing comes up.</p> <p>Here is the page I'm working on: <a href="http://geekoutaustin.com/live/property/?id=d86967ad43c2f5271b02f94247ef858d&amp;wpf28382_5=8252427" rel="nofollow noreferrer">http://geekoutaustin.com/live/property/?id=d86967ad43c2f5271b02f94247ef858d&amp;wpf28382_5=8252427</a></p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/27
    [ "https://wordpress.stackexchange.com/questions/393836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210568/" ]
    I have successfully changed the name of a specific page using this code in my functions.php file: ``` add_filter('pre_get_document_title', 'change_my_property_title'); function change_my_property_title($title) { if ( is_page('property') ) { return 'Property'; } return $title; } ``` My problem is I can't figure out how to change the name to an actual php variable that is on the property page. I am pulling property information from a json url and would like the address to be the title. If I try to point to the variable in my return statement nothing comes up. Here is the page I'm working on: <http://geekoutaustin.com/live/property/?id=d86967ad43c2f5271b02f94247ef858d&wpf28382_5=8252427>
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,858
    <p>This is my Shortcode: <code>[mbv name=”product-info”]</code></p> <p>And i want to display this shortcode's content after <a href="https://github.com/woocommerce/woocommerce/blob/b19500728b4b292562afb65eb3a0c0f50d5859de/templates/single-product/short-description.php#L24" rel="nofollow noreferrer">WooCommerce Short Product Description</a></p> <p>How can i do it?</p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/27
    [ "https://wordpress.stackexchange.com/questions/393858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210558/" ]
    This is my Shortcode: `[mbv name=”product-info”]` And i want to display this shortcode's content after [WooCommerce Short Product Description](https://github.com/woocommerce/woocommerce/blob/b19500728b4b292562afb65eb3a0c0f50d5859de/templates/single-product/short-description.php#L24) How can i do it?
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    393,877
    <p>Hope someone can help me with this.</p> <p>This is my code:</p> <pre><code>function swh_woocommerce_store_credit_shortcode() { $store_credits = swh_woocommerce_get_store_credits(); echo &quot;&lt;span style= 'display: inline;'&gt;Remaining Credit:&lt;/span&gt;&quot;; return wc_price($store_credits); } add_shortcode( 'swh_store_credit_total_value', 'swh_woocommerce_store_credit_shortcode' ); </code></pre> <p>I'm trying to display echo and return in the same line.</p> <p>i. e. <code>Remaning Credit: $80</code> and not</p> <pre><code>Remaining Credit: $80 </code></pre> <p>Thanks!</p>
    [ { "answer_id": 393749, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": -1, "selected": false, "text": "<p>You should keep the slug page in your URL.\nIt is way more easier and better to read.</p>\n<p>Here is something correct :</p>\n<pre><code>add_rewrite_rule( '(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top' );\n</code></pre>\n" }, { "answer_id": 393788, "author": "Pierre R", "author_id": 134512, "author_profile": "https://wordpress.stackexchange.com/users/134512", "pm_score": 0, "selected": false, "text": "<p>I'll add another answer because the rule is only a part of the problem.</p>\n<p>Here is what I have tested and is working :</p>\n<pre><code>&lt;?php\nclass BadRewritesRules {\n\n public function __construct() {\n add_action('init', [$this, 'custom_post_types_rewrite_rules']);\n remove_filter('template_redirect', 'redirect_canonical');\n }\n\n public function custom_post_types_rewrite_rules() {\n add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');\n }\n\n}\n\nnew BadRewritesRules();\n</code></pre>\n<p>In reality, I used another URL and you can see it working here : <a href=\"https://tests.pierre-roels.com/bad-rewrite-rules/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/bad-rewrite-rules/2/</a>\nYou can use pagination and also view each &quot;member&quot; with the same slug.</p>\n<p>But as I said, this is a poor solution in my opinion because we must remove the <code>template_redirect</code> action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an <code>.htaccess</code> redirect ?</p>\n<p>Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings &gt; Permalinks and submit the page</p>\n<p>Here is the solution with .htacess. Add this to your .htaccess :</p>\n<p><code>RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]</code></p>\n<p>and don't forget to fix you rule :\n<code>add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&amp;paged=$matches[2]', 'top');</code>.</p>\n<p>I have made another test just for you : <a href=\"https://tests.pierre-roels.com/blog/2/\" rel=\"nofollow noreferrer\">https://tests.pierre-roels.com/blog/2/</a></p>\n<p>This solution allow you to not remove the <code>template_redirect</code> hook, it redirects the user the right end-url</p>\n" } ]
    2021/08/27
    [ "https://wordpress.stackexchange.com/questions/393877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210770/" ]
    Hope someone can help me with this. This is my code: ``` function swh_woocommerce_store_credit_shortcode() { $store_credits = swh_woocommerce_get_store_credits(); echo "<span style= 'display: inline;'>Remaining Credit:</span>"; return wc_price($store_credits); } add_shortcode( 'swh_store_credit_total_value', 'swh_woocommerce_store_credit_shortcode' ); ``` I'm trying to display echo and return in the same line. i. e. `Remaning Credit: $80` and not ``` Remaining Credit: $80 ``` Thanks!
    I'll add another answer because the rule is only a part of the problem. Here is what I have tested and is working : ``` <?php class BadRewritesRules { public function __construct() { add_action('init', [$this, 'custom_post_types_rewrite_rules']); remove_filter('template_redirect', 'redirect_canonical'); } public function custom_post_types_rewrite_rules() { add_rewrite_rule('(blog)/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top'); } } new BadRewritesRules(); ``` In reality, I used another URL and you can see it working here : <https://tests.pierre-roels.com/bad-rewrite-rules/2/> You can use pagination and also view each "member" with the same slug. But as I said, this is a poor solution in my opinion because we must remove the `template_redirect` action hook. It would be better to hook on the Laravel part to build links the right way :( Or maybe an `.htaccess` redirect ? Don't forget to flush permalinks everytime you make a change. To do so, you can simply go to Settings > Permalinks and submit the page Here is the solution with .htacess. Add this to your .htaccess : `RewriteRule (blog)/([0-9]+)/? /$1/page/$2/ [R=301,L]` and don't forget to fix you rule : `add_rewrite_rule('(blog)/page/([0-9-]+)[/]?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');`. I have made another test just for you : <https://tests.pierre-roels.com/blog/2/> This solution allow you to not remove the `template_redirect` hook, it redirects the user the right end-url
    394,020
    <p>I recently noticed a new feature in the Gutenberg editor (I'm guessing introduced in Wordpress 5.8) that seemingly allows any user to post as any other user:</p> <p><a href="https://i.stack.imgur.com/nIo3m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nIo3m.png" alt="enter image description here" /></a></p> <p>I confirmed that using this new option, a user belonging to the Author role was able to successfully to post as a user belonging to the Admin role. Why on Earth was this feature introduced with seemingly no permissions checks, and can it be disabled?</p>
    [ { "answer_id": 394027, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!</p>\n<p>In the block editor, the presence of the author field depends on wether the user has the action <code>wp:action-assign-author</code>, but there is no direct capability that determines this. It is added because it's implied via the <code>edit_others_posts</code> capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).</p>\n<p>If we take a look at the <a href=\"https://github.com/humanmade/authorship\" rel=\"nofollow noreferrer\">authorship plugin</a> we see that it can be removed:</p>\n<pre><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n $response-&gt;add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n</code></pre>\n<p>So something like this might remove it for all users when editing posts:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n</code></pre>\n<p>You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.</p>\n<p><em><strong>This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI</strong></em></p>\n" }, { "answer_id": 394029, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 1, "selected": false, "text": "<p>After a lot of testing (easier since I remembered that any cap added to a role with <code>add_cap</code> has to explicitly be removed with <code>remove_cap</code> rather than just removing the <code>add_cap</code> call, and that even <code>wp-cli</code> can't help for this purpose), I finally managed to determine that...</p>\n<hr />\n<h2>This dropdown is a side effect of the <code>edit_others_posts</code> capability</h2>\n<p>I had originally enabled this cap for my Author role because <em>another</em> of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, <em>even</em> when the <code>moderate_comments</code> capability is also enabled. Enabling <code>edit_others_posts</code> at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.</p>\n<p>In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that <em>should</em> be unrelated.</p>\n<p>I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the <code>moderate_comments</code> cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.</p>\n" } ]
    2021/08/31
    [ "https://wordpress.stackexchange.com/questions/394020", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167562/" ]
    I recently noticed a new feature in the Gutenberg editor (I'm guessing introduced in Wordpress 5.8) that seemingly allows any user to post as any other user: [![enter image description here](https://i.stack.imgur.com/nIo3m.png)](https://i.stack.imgur.com/nIo3m.png) I confirmed that using this new option, a user belonging to the Author role was able to successfully to post as a user belonging to the Admin role. Why on Earth was this feature introduced with seemingly no permissions checks, and can it be disabled?
    This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes! In the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ). If we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed: ``` /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] ); } return $response; } ``` So something like this might remove it for all users when editing posts: ```php /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); } return $response; } add_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 ); ``` You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author. ***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***
    394,032
    <p>I wonder if this is possible on wordpress. In my application I will have a contact form, in this contact form, when filling in the fields, there must be a field that will generate an ID. This ID the customer will be able to write down and save. I will also receive this ID along with the details this person has filled in. It is possible? Or is there already a plugin for this type of situation?</p>
    [ { "answer_id": 394027, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!</p>\n<p>In the block editor, the presence of the author field depends on wether the user has the action <code>wp:action-assign-author</code>, but there is no direct capability that determines this. It is added because it's implied via the <code>edit_others_posts</code> capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).</p>\n<p>If we take a look at the <a href=\"https://github.com/humanmade/authorship\" rel=\"nofollow noreferrer\">authorship plugin</a> we see that it can be removed:</p>\n<pre><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n $response-&gt;add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n</code></pre>\n<p>So something like this might remove it for all users when editing posts:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n</code></pre>\n<p>You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.</p>\n<p><em><strong>This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI</strong></em></p>\n" }, { "answer_id": 394029, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 1, "selected": false, "text": "<p>After a lot of testing (easier since I remembered that any cap added to a role with <code>add_cap</code> has to explicitly be removed with <code>remove_cap</code> rather than just removing the <code>add_cap</code> call, and that even <code>wp-cli</code> can't help for this purpose), I finally managed to determine that...</p>\n<hr />\n<h2>This dropdown is a side effect of the <code>edit_others_posts</code> capability</h2>\n<p>I had originally enabled this cap for my Author role because <em>another</em> of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, <em>even</em> when the <code>moderate_comments</code> capability is also enabled. Enabling <code>edit_others_posts</code> at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.</p>\n<p>In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that <em>should</em> be unrelated.</p>\n<p>I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the <code>moderate_comments</code> cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.</p>\n" } ]
    2021/08/31
    [ "https://wordpress.stackexchange.com/questions/394032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203043/" ]
    I wonder if this is possible on wordpress. In my application I will have a contact form, in this contact form, when filling in the fields, there must be a field that will generate an ID. This ID the customer will be able to write down and save. I will also receive this ID along with the details this person has filled in. It is possible? Or is there already a plugin for this type of situation?
    This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes! In the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ). If we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed: ``` /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] ); } return $response; } ``` So something like this might remove it for all users when editing posts: ```php /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); } return $response; } add_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 ); ``` You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author. ***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***
    394,086
    <p>I have created a form and the table in the database I want submissions to be sent to. From my research I've found that this code should send it to the database:</p> <pre><code>&lt;?php /* PHP code that processes form */ if(isset($_POST['submit'])){ global $wpdb; $tablename = Form_Submissions; $data=array( 'FirstName' =&gt; $_POST['fname'], 'LastName' =&gt; $POST['lname'], 'Consent' =&gt; $POST['consent'] ); $format = array( '%s', '%s', '%s' ); $wpdb -&gt; insert($tablename, $data, $format); echo '&lt;script type=&quot;text/javascript&quot;&gt; document.getElementById(&quot;frm&quot;).style.display=&quot;none&quot;; &lt;/script&gt;'; } ?&gt; </code></pre> <p>However, nothing is happening. I'm at complete loss on where to go from here. Am I missing something simple, or am I completely off target? Thank you for your help!</p> <p>Here is the code for the form and the code that activates the form just in case.</p> <pre><code>&lt;html&gt; &lt;style&gt; /* Stylings for Heading Statement */ .h3{ text-align: center; font-size: 24px; padding: 10px; color: white; } /* Stylings for checkbox */ .box{ font-size: 22px; padding: 20px; color: white; } /* Stylings for input labels (names and checkbox labels) */ .input-label{ text-align: center; font-size: 22px; padding: 10px; color: white; } /* Button used to open the contact form - fixed at the bottom of the page */ .open-button { width: 170px; height: 60px; background-color: transparent; outline: none; position: relative; left: -168px; top: 20px; } /* The popup form - hidden by default */ .form-popup { display: none; position: absolute; top: 25%; left: -530px; border: none; z-index: 9; background-color: #1e1e1e; width: 1000px; padding: 20px; border-radius: 20px; text-align: center; } /* Sets style and size of input fields */ .form-popup input[type=text] { width: 30%; padding: 5px; margin: 5px 0 22px 0; border: none; background: #FFFFFF; } /* Sets color and style of the input boxes when selected */ .form-popup input:focus { background-color: #FFFFFF; outline: none; } /* Stylings of the submit button */ .btn { background-color: #DB2600; border-radius: 9999px; font-size: 24px; width: 120px; height: 45px; transition: 0.3s; color: white; } /* Changes the color of the sugmit button when curser hovers over it */ .btn:hover { opacity: 1; background-color: #000000; } /* Hides the default checkbox */ .box input { position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; } /* creates custom checkbox */ .checkmark { position: absolute; height: 20px; width: 20px; background-color: white; border-radius: 2px; } /* Sets the color of checkbox when checked */ .box input:checked ~ .checkmark { background-color: #DB2600; } /* creates checkmark inside checkbox */ .checkmark:after { content: &quot;&quot;; position: absolute; display: none; } /* Displays checkmark when checkbox is clicked */ .box input:checked ~ .checkmark:after { display: block; } /* Positions and styles checkmark */ .box .checkmark:after { left: 7px; top: 3px; width: 6px; height: 12px; border: solid white; border-width: 0 3px 3px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } /* Column formatting for checkbos and statement. This is what is aligning the two items. */ .column1 { float: left; width: 26%; } .column2 { float: left; width: 74%; margin-top:-5px; } /* Clears floats after the columns */ .row:after { content: &quot;&quot;; display: table; clear: both; } &lt;/style&gt; &lt;body&gt; &lt;!-- Code for the form --&gt; &lt;div class=&quot;form-popup&quot; id=&quot;Form&quot;&gt; &lt;form method=&quot;post&quot;&gt; &lt;!-- acknolwdgement statment --&gt; &lt;h3 class=&quot;h3&quot;&gt;form statement&lt;/h3&gt; &lt;!-- label and input for First Name --&gt; &lt;label for=&quot;fname&quot; class=&quot;input-label&quot;&gt;First name:&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;fname&quot; required/&gt; &lt;!-- label and input for Last Name --&gt; &lt;label for=&quot;lname&quot; class=&quot;input-label&quot;&gt;&amp;nbsp &amp;nbsp Last name:&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;lname&quot; required/&gt; &lt;br&gt; &lt;br&gt; &lt;!-- checkbox and label, placed to columns to achieve desired formating --&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;column1&quot; style=&quot;text-align: right;&quot;&gt; &lt;label class=&quot;box&quot; style=&quot;border-color: red;&quot;&gt; &lt;input type=&quot;checkbox&quot; name=&quot;consent&quot; value=&quot;agree&quot; class=&quot;box&quot; required/&gt; &lt;span class=&quot;checkmark&quot;&gt;&lt;/span&gt; &lt;/label&gt;&lt;/div&gt; &lt;div class=&quot;column2&quot; style=&quot;text-align: left;&quot;&gt; &lt;label class=&quot;input-label&quot;&gt; I have read and understand the above statement. &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- Submit Button --&gt; &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot; class=&quot;btn&quot;&gt; &lt;/form&gt; &lt;/div&gt; &lt;script&gt; function openForm() { /* Opens Consent Form */ document.getElementById(&quot;Form&quot;).style.display = &quot;block&quot;; } &lt;/script&gt; &lt;/body&gt; &lt;?php /* PHP code that processes form */ if(isset($_POST['submit'])){ global $wpdb; $tablename = Form_Submissions; $data=array( 'FirstName' =&gt; $_POST['fname'], 'LastName' =&gt; $POST['lname'], 'Consent' =&gt; $POST['consent'] ); $format = array( '%s', '%s', '%s' ); $wpdb -&gt; insert($tablename, $data, $format); echo '&lt;script type=&quot;text/javascript&quot;&gt; document.getElementById(&quot;frm&quot;).style.display=&quot;none&quot;; &lt;/script&gt;'; } ?&gt; &lt;/html&gt; </code></pre> <p>The Switch Case that activates it:</p> <pre><code>&lt;?php /* code for pop-up button conditions */ $host = 'https://' .$_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;]; /* gets the current page's URL */ switch ( $host ){ case 'https://example1.com': case 'https://example2.com': case 'https://example3.com': require 'pop-up-button.php'; /*calls the PHP file containing the code for the form*/ echo '&lt;button id=&quot;close&quot; class=&quot;open-button&quot; onclick=&quot;openForm()&quot;&gt;&lt;/button&gt;'; break; default : /* the default case leaves the function and allows all pages with URL's not match the cases to run as normal pages */ break; }; ?&gt; </code></pre>
    [ { "answer_id": 394027, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes!</p>\n<p>In the block editor, the presence of the author field depends on wether the user has the action <code>wp:action-assign-author</code>, but there is no direct capability that determines this. It is added because it's implied via the <code>edit_others_posts</code> capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ).</p>\n<p>If we take a look at the <a href=\"https://github.com/humanmade/authorship\" rel=\"nofollow noreferrer\">authorship plugin</a> we see that it can be removed:</p>\n<pre><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n $response-&gt;add_link( REST_REL_LINK_ID, $links['self'][0]['href'] );\n }\n\n return $response;\n}\n</code></pre>\n<p>So something like this might remove it for all users when editing posts:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Filters the post data for a REST API response.\n *\n * This removes the `wp:action-assign-author` rel from the response so the default post author\n * control doesn't get shown on the block editor post editing screen.\n *\n * @param WP_REST_Response $response The response object.\n * @param WP_Post $post Post object.\n * @param WP_REST_Request $request Request object.\n * @return WP_REST_Response The response object.\n */\nfunction rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response {\n $links = $response-&gt;get_links();\n\n if ( isset( $links['https://api.w.org/action-assign-author'] ) ) {\n $response-&gt;remove_link( 'https://api.w.org/action-assign-author' );\n }\n\n return $response;\n}\nadd_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 );\n</code></pre>\n<p>You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author.</p>\n<p><em><strong>This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI</strong></em></p>\n" }, { "answer_id": 394029, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 1, "selected": false, "text": "<p>After a lot of testing (easier since I remembered that any cap added to a role with <code>add_cap</code> has to explicitly be removed with <code>remove_cap</code> rather than just removing the <code>add_cap</code> call, and that even <code>wp-cli</code> can't help for this purpose), I finally managed to determine that...</p>\n<hr />\n<h2>This dropdown is a side effect of the <code>edit_others_posts</code> capability</h2>\n<p>I had originally enabled this cap for my Author role because <em>another</em> of its side effects is the ability to moderate (i.e. Approve, Spam or Bin) comments, <em>even</em> when the <code>moderate_comments</code> capability is also enabled. Enabling <code>edit_others_posts</code> at the time was the only way to allow my Author role to moderate comments, just as disabling it now is the only way to prevent my Author role from posting as another user.</p>\n<p>In other words, Wordpress' cap system is so messy and interdependent that if I want to prevent a role from pretending to post as another user, I can't also allow that role to moderate comments - two completely different functions that <em>should</em> be unrelated.</p>\n<p>I even understand why they're related - because a post needs to be editable for its comments to be - but these caps should really be separated out, because editing a post and moderating spam on it are two different logical domains, and therefore two different roles. This is clearly understood on some level because the <code>moderate_comments</code> cap exists, but clearly it would have been too intuitive for Wordpress to make it the only cap that lets users... moderate comments.</p>\n" } ]
    2021/09/01
    [ "https://wordpress.stackexchange.com/questions/394086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210914/" ]
    I have created a form and the table in the database I want submissions to be sent to. From my research I've found that this code should send it to the database: ``` <?php /* PHP code that processes form */ if(isset($_POST['submit'])){ global $wpdb; $tablename = Form_Submissions; $data=array( 'FirstName' => $_POST['fname'], 'LastName' => $POST['lname'], 'Consent' => $POST['consent'] ); $format = array( '%s', '%s', '%s' ); $wpdb -> insert($tablename, $data, $format); echo '<script type="text/javascript"> document.getElementById("frm").style.display="none"; </script>'; } ?> ``` However, nothing is happening. I'm at complete loss on where to go from here. Am I missing something simple, or am I completely off target? Thank you for your help! Here is the code for the form and the code that activates the form just in case. ``` <html> <style> /* Stylings for Heading Statement */ .h3{ text-align: center; font-size: 24px; padding: 10px; color: white; } /* Stylings for checkbox */ .box{ font-size: 22px; padding: 20px; color: white; } /* Stylings for input labels (names and checkbox labels) */ .input-label{ text-align: center; font-size: 22px; padding: 10px; color: white; } /* Button used to open the contact form - fixed at the bottom of the page */ .open-button { width: 170px; height: 60px; background-color: transparent; outline: none; position: relative; left: -168px; top: 20px; } /* The popup form - hidden by default */ .form-popup { display: none; position: absolute; top: 25%; left: -530px; border: none; z-index: 9; background-color: #1e1e1e; width: 1000px; padding: 20px; border-radius: 20px; text-align: center; } /* Sets style and size of input fields */ .form-popup input[type=text] { width: 30%; padding: 5px; margin: 5px 0 22px 0; border: none; background: #FFFFFF; } /* Sets color and style of the input boxes when selected */ .form-popup input:focus { background-color: #FFFFFF; outline: none; } /* Stylings of the submit button */ .btn { background-color: #DB2600; border-radius: 9999px; font-size: 24px; width: 120px; height: 45px; transition: 0.3s; color: white; } /* Changes the color of the sugmit button when curser hovers over it */ .btn:hover { opacity: 1; background-color: #000000; } /* Hides the default checkbox */ .box input { position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; } /* creates custom checkbox */ .checkmark { position: absolute; height: 20px; width: 20px; background-color: white; border-radius: 2px; } /* Sets the color of checkbox when checked */ .box input:checked ~ .checkmark { background-color: #DB2600; } /* creates checkmark inside checkbox */ .checkmark:after { content: ""; position: absolute; display: none; } /* Displays checkmark when checkbox is clicked */ .box input:checked ~ .checkmark:after { display: block; } /* Positions and styles checkmark */ .box .checkmark:after { left: 7px; top: 3px; width: 6px; height: 12px; border: solid white; border-width: 0 3px 3px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } /* Column formatting for checkbos and statement. This is what is aligning the two items. */ .column1 { float: left; width: 26%; } .column2 { float: left; width: 74%; margin-top:-5px; } /* Clears floats after the columns */ .row:after { content: ""; display: table; clear: both; } </style> <body> <!-- Code for the form --> <div class="form-popup" id="Form"> <form method="post"> <!-- acknolwdgement statment --> <h3 class="h3">form statement</h3> <!-- label and input for First Name --> <label for="fname" class="input-label">First name:</label> <input type="text" name="fname" required/> <!-- label and input for Last Name --> <label for="lname" class="input-label">&nbsp &nbsp Last name:</label> <input type="text" name="lname" required/> <br> <br> <!-- checkbox and label, placed to columns to achieve desired formating --> <div class="row"> <div class="column1" style="text-align: right;"> <label class="box" style="border-color: red;"> <input type="checkbox" name="consent" value="agree" class="box" required/> <span class="checkmark"></span> </label></div> <div class="column2" style="text-align: left;"> <label class="input-label"> I have read and understand the above statement. </label> </div> </div> <br><br> <!-- Submit Button --> <input type="submit" name="submit" value="Submit" class="btn"> </form> </div> <script> function openForm() { /* Opens Consent Form */ document.getElementById("Form").style.display = "block"; } </script> </body> <?php /* PHP code that processes form */ if(isset($_POST['submit'])){ global $wpdb; $tablename = Form_Submissions; $data=array( 'FirstName' => $_POST['fname'], 'LastName' => $POST['lname'], 'Consent' => $POST['consent'] ); $format = array( '%s', '%s', '%s' ); $wpdb -> insert($tablename, $data, $format); echo '<script type="text/javascript"> document.getElementById("frm").style.display="none"; </script>'; } ?> </html> ``` The Switch Case that activates it: ``` <?php /* code for pop-up button conditions */ $host = 'https://' .$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; /* gets the current page's URL */ switch ( $host ){ case 'https://example1.com': case 'https://example2.com': case 'https://example3.com': require 'pop-up-button.php'; /*calls the PHP file containing the code for the form*/ echo '<button id="close" class="open-button" onclick="openForm()"></button>'; break; default : /* the default case leaves the function and allows all pages with URL's not match the cases to run as normal pages */ break; }; ?> ```
    This has been present since before the block editor, and even the classic editor, and can be seen in WordPress 2.0. It even predates proper metaboxes! In the block editor, the presence of the author field depends on wether the user has the action `wp:action-assign-author`, but there is no direct capability that determines this. It is added because it's implied via the `edit_others_posts` capabilty, but removing this has far and wide reaching consequences that go beyond just the author dropdown ( you won't be able to edit posts unless you are the author as well as lots of other things ). If we take a look at the [authorship plugin](https://github.com/humanmade/authorship) we see that it can be removed: ``` /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * This also adds a new `authorship:action-assign-authorship` rel so custom clients can refer to this. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); $response->add_link( REST_REL_LINK_ID, $links['self'][0]['href'] ); } return $response; } ``` So something like this might remove it for all users when editing posts: ```php /** * Filters the post data for a REST API response. * * This removes the `wp:action-assign-author` rel from the response so the default post author * control doesn't get shown on the block editor post editing screen. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response The response object. */ function rest_prepare_post_remove_author_action( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) : WP_REST_Response { $links = $response->get_links(); if ( isset( $links['https://api.w.org/action-assign-author'] ) ) { $response->remove_link( 'https://api.w.org/action-assign-author' ); } return $response; } add_filter( 'rest_prepare_post', 'rest_prepare_post_remove_author_action', 10, 3 ); ``` You may then adjust it to contain a role/capability check. Note that this may be purely cosmetic, users who directly make requests to the API, or use the classic editor, can still set the author. ***This just fools the block editor and other well behaving REST API applications into believing it isn't possible, but it does remove the UI***
    395,152
    <p>I use wordpress for my Social Media site. WordPress Pings allow other blog posts to appear in comments when they link to us.</p> <p>I want to limit it to only blog posts created on my own site. Basically I only want SELF-PINGS/Trackbacks.</p> <p>If Other site tries to send ping reject it then and their, but if my own site https://milyin.com's post tries to send a ping readily accept it and show it in comment section.</p> <p>I tried, <strong>wp-admin</strong> -&gt; <strong>discussion</strong> -&gt; (unselect) <strong>Allow links from other blog posts.</strong></p> <p>But that disables internal Pings too. Secondly My authors are able to turn on/off the pingbacks for each post. So, many of the posts still recieve external pings.</p> <p>Here's a screenshot of the same: <strong><a href="https://snipboard.io/8lVIrE.jpg" rel="nofollow noreferrer">https://snipboard.io/8lVIrE.jpg</a></strong></p> <p>I tried to do some code.</p> <p>I found a tutorial from <strong><a href="https://www.wpbeginner.com/wp-tutorials/how-disable-self-pingbacks-in-wordpress/" rel="nofollow noreferrer">How Disable Self Pingbacks in WordPress</a></strong></p> <p>And I tried to modify it to fit my needs</p> <pre><code>function SelfPing( &amp;$links ) { $Home = get_option( 'home' ); foreach ( $links as $l =&gt; $link ){ if ( strpos( $link, $Home ) === false){ unset($links[$l]); } } } add_action( 'pre_ping', 'SelfPing' ); </code></pre> <p>However this didn't solve the purpose.</p> <p>I still recieve pings from all sorts of sites, on my posts, as majority of my authors manually turn on Pings.</p> <p>So How can I have only self pings, and remove external pings, even when my authors manually turn on pings for all posts.</p>
    [ { "answer_id": 395178, "author": "vlood", "author_id": 733, "author_profile": "https://wordpress.stackexchange.com/users/733", "pm_score": 1, "selected": false, "text": "<p>If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to <code>xmlrpc.php</code> file only for requests from your own server by adding this to your <code>.htaccess</code> file</p>\n<pre><code>&lt;Files xmlrpc.php&gt;\n Order deny,allow\n Deny from all\n Allow from 127.0.0.1\n&lt;/Files&gt;\n</code></pre>\n<p>This would work only if your webserver is Apache and it's configured to read local <code>.htaccess</code> files of overriding it's main configuration. Nginx, Litespeed and others don't use <code>.htaccess</code> files whatsoever, so no point in trying this with them.</p>\n<p>Edit:</p>\n<p>If you are using <code>xmlrpc.php</code> for other stuff too, you could use the <code>xmlrpc_call</code> hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):</p>\n<pre><code>add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n if ( 'pingback.ping' !== $type_of_call ) {\n return;\n }\n if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n wp_die();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 395254, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>If you want to receive only linkbacks from your own WordPress site, then try both of these:</p>\n<p>But if you want to allow all that were sent as <em>trackbacks</em> (where the comment type is <code>trackback</code>), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a &quot;Pingback&quot; in the post's comments section.</p>\n<ol>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/xmlrpc_call/\" rel=\"nofollow noreferrer\"><code>xmlrpc_call</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#pingbacks\" rel=\"nofollow noreferrer\">pingbacks</a> sent via the XML-RPC method:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name &amp;&amp; false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server-&gt;error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n</code></pre>\n</li>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/pre_trackback_post/\" rel=\"nofollow noreferrer\"><code>pre_trackback_post</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#trackbacks\" rel=\"nofollow noreferrer\">trackbacks</a> sent via the standard HTTP POST method (i.e. not using XML-RPC):</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n</code></pre>\n</li>\n</ol>\n<p>And BTW, in the code in the question, <code>$home</code> is undefined and it should be <code>$Home</code> ( note the uppercase &quot;H&quot; and see <a href=\"https://www.php.net/manual/en/language.variables.basics.php\" rel=\"nofollow noreferrer\">this</a> which says, &quot;<em>variable name is case-sensitive</em>&quot; :) ).</p>\n" } ]
    2021/09/03
    [ "https://wordpress.stackexchange.com/questions/395152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166927/" ]
    I use wordpress for my Social Media site. WordPress Pings allow other blog posts to appear in comments when they link to us. I want to limit it to only blog posts created on my own site. Basically I only want SELF-PINGS/Trackbacks. If Other site tries to send ping reject it then and their, but if my own site https://milyin.com's post tries to send a ping readily accept it and show it in comment section. I tried, **wp-admin** -> **discussion** -> (unselect) **Allow links from other blog posts.** But that disables internal Pings too. Secondly My authors are able to turn on/off the pingbacks for each post. So, many of the posts still recieve external pings. Here's a screenshot of the same: **<https://snipboard.io/8lVIrE.jpg>** I tried to do some code. I found a tutorial from **[How Disable Self Pingbacks in WordPress](https://www.wpbeginner.com/wp-tutorials/how-disable-self-pingbacks-in-wordpress/)** And I tried to modify it to fit my needs ``` function SelfPing( &$links ) { $Home = get_option( 'home' ); foreach ( $links as $l => $link ){ if ( strpos( $link, $Home ) === false){ unset($links[$l]); } } } add_action( 'pre_ping', 'SelfPing' ); ``` However this didn't solve the purpose. I still recieve pings from all sorts of sites, on my posts, as majority of my authors manually turn on Pings. So How can I have only self pings, and remove external pings, even when my authors manually turn on pings for all posts.
    If you want to receive only linkbacks from your own WordPress site, then try both of these: But if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section. 1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method: ```php add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 ); function disallow_external_xmlrpc_pingback( $name, $args, $server ) { if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) { // Exit with a proper error. $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) ); } } ``` 2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC): ```php add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 ); function disallow_external_POST_trackback( $tb_id, $tb_url ) { if ( false === strpos( $tb_url, home_url() ) ) { // Exit with a proper error. trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' ); } } ``` And BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase "H" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, "*variable name is case-sensitive*" :) ).
    395,169
    <p>I have a huge problem! I am in the middle of migrating a drupal based online database to wordpress. In the old database every object (post) had downloadable qr code. Because the database is used for scientific purposes and users where allowed to use the downloaded qr code in their own publications for reference purposes. Since the system is five years old, some books have been printed using those qr codes, with the objects url embedded in the short code. It used the normal structure in drupal site-url/node/XXXX (where XXXX is the number of the content node) On the wordpress version the permalink structure is (and should be) for example like this: site-url/audio/name-of-the-post So for example <a href="https://soundandscience.de/node/1040" rel="nofollow noreferrer">https://soundandscience.de/node/1040</a> becomes <a href="https://soundandscience.de/audio/lautarchiv-recording-la-566-1-siebs-theodor-a-laute/" rel="nofollow noreferrer">https://soundandscience.de/audio/lautarchiv-recording-la-566-1-siebs-theodor-a-laute/</a></p> <p>What I can do, because I use ACF a lot, is create a field where the node number of the old post can be stored (in this example case: 1040)</p> <p>The post transference between drupal and wordpress will be handled manually (poor students)...</p> <p>But is there a way to make it possible, for the old shortcodes in printed books to be redirected to the new correct post?</p> <p>Best Martin</p>
    [ { "answer_id": 395178, "author": "vlood", "author_id": 733, "author_profile": "https://wordpress.stackexchange.com/users/733", "pm_score": 1, "selected": false, "text": "<p>If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to <code>xmlrpc.php</code> file only for requests from your own server by adding this to your <code>.htaccess</code> file</p>\n<pre><code>&lt;Files xmlrpc.php&gt;\n Order deny,allow\n Deny from all\n Allow from 127.0.0.1\n&lt;/Files&gt;\n</code></pre>\n<p>This would work only if your webserver is Apache and it's configured to read local <code>.htaccess</code> files of overriding it's main configuration. Nginx, Litespeed and others don't use <code>.htaccess</code> files whatsoever, so no point in trying this with them.</p>\n<p>Edit:</p>\n<p>If you are using <code>xmlrpc.php</code> for other stuff too, you could use the <code>xmlrpc_call</code> hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):</p>\n<pre><code>add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n if ( 'pingback.ping' !== $type_of_call ) {\n return;\n }\n if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n wp_die();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 395254, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>If you want to receive only linkbacks from your own WordPress site, then try both of these:</p>\n<p>But if you want to allow all that were sent as <em>trackbacks</em> (where the comment type is <code>trackback</code>), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a &quot;Pingback&quot; in the post's comments section.</p>\n<ol>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/xmlrpc_call/\" rel=\"nofollow noreferrer\"><code>xmlrpc_call</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#pingbacks\" rel=\"nofollow noreferrer\">pingbacks</a> sent via the XML-RPC method:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name &amp;&amp; false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server-&gt;error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n</code></pre>\n</li>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/pre_trackback_post/\" rel=\"nofollow noreferrer\"><code>pre_trackback_post</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#trackbacks\" rel=\"nofollow noreferrer\">trackbacks</a> sent via the standard HTTP POST method (i.e. not using XML-RPC):</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n</code></pre>\n</li>\n</ol>\n<p>And BTW, in the code in the question, <code>$home</code> is undefined and it should be <code>$Home</code> ( note the uppercase &quot;H&quot; and see <a href=\"https://www.php.net/manual/en/language.variables.basics.php\" rel=\"nofollow noreferrer\">this</a> which says, &quot;<em>variable name is case-sensitive</em>&quot; :) ).</p>\n" } ]
    2021/09/03
    [ "https://wordpress.stackexchange.com/questions/395169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212032/" ]
    I have a huge problem! I am in the middle of migrating a drupal based online database to wordpress. In the old database every object (post) had downloadable qr code. Because the database is used for scientific purposes and users where allowed to use the downloaded qr code in their own publications for reference purposes. Since the system is five years old, some books have been printed using those qr codes, with the objects url embedded in the short code. It used the normal structure in drupal site-url/node/XXXX (where XXXX is the number of the content node) On the wordpress version the permalink structure is (and should be) for example like this: site-url/audio/name-of-the-post So for example <https://soundandscience.de/node/1040> becomes <https://soundandscience.de/audio/lautarchiv-recording-la-566-1-siebs-theodor-a-laute/> What I can do, because I use ACF a lot, is create a field where the node number of the old post can be stored (in this example case: 1040) The post transference between drupal and wordpress will be handled manually (poor students)... But is there a way to make it possible, for the old shortcodes in printed books to be redirected to the new correct post? Best Martin
    If you want to receive only linkbacks from your own WordPress site, then try both of these: But if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section. 1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method: ```php add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 ); function disallow_external_xmlrpc_pingback( $name, $args, $server ) { if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) { // Exit with a proper error. $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) ); } } ``` 2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC): ```php add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 ); function disallow_external_POST_trackback( $tb_id, $tb_url ) { if ( false === strpos( $tb_url, home_url() ) ) { // Exit with a proper error. trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' ); } } ``` And BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase "H" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, "*variable name is case-sensitive*" :) ).
    395,184
    <p>In my current case, the system try to find a page and show 404 if it does not find. I would like with the same url... like <a href="https://example.com/%7B%7Bslug%7D%7D/" rel="nofollow noreferrer">https://example.com/{{slug}}/</a></p> <ol> <li>Check if a page with this slug exists : <ol> <li> <ul> <li>Yes - show the page</li> </ul> </li> <li> <ul> <li>No - switch to the category page (with same slug)</li> </ul> </li> <li> <ul> <li>No category page -&gt; show page 404</li> </ul> </li> </ol> </li> </ol> <p>What is the best recommandanted way to do this in WP?</p>
    [ { "answer_id": 395178, "author": "vlood", "author_id": 733, "author_profile": "https://wordpress.stackexchange.com/users/733", "pm_score": 1, "selected": false, "text": "<p>If you don't make any other use of XMLRPC service in WordPress than the pingbacks/trackbacks, you could try limiting requests to <code>xmlrpc.php</code> file only for requests from your own server by adding this to your <code>.htaccess</code> file</p>\n<pre><code>&lt;Files xmlrpc.php&gt;\n Order deny,allow\n Deny from all\n Allow from 127.0.0.1\n&lt;/Files&gt;\n</code></pre>\n<p>This would work only if your webserver is Apache and it's configured to read local <code>.htaccess</code> files of overriding it's main configuration. Nginx, Litespeed and others don't use <code>.htaccess</code> files whatsoever, so no point in trying this with them.</p>\n<p>Edit:</p>\n<p>If you are using <code>xmlrpc.php</code> for other stuff too, you could use the <code>xmlrpc_call</code> hook in order to check if the call is a pingback and if it's from the right address (localhost). Here's how it should look (in theory):</p>\n<pre><code>add_action( 'xmlrpc_call', 'limit_to_local_pingbacks', 10, 3 );\nfunction limit_to_local_pingbacks( string $type_of_call, array|string $args, wp_xmlrpc_server $server ) {\n if ( 'pingback.ping' !== $type_of_call ) {\n return;\n }\n if ( '127.0.0.1' !== $_SERVER['REMOTE_ADDR'] ) {\n wp_die();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 395254, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>If you want to receive only linkbacks from your own WordPress site, then try both of these:</p>\n<p>But if you want to allow all that were sent as <em>trackbacks</em> (where the comment type is <code>trackback</code>), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a &quot;Pingback&quot; in the post's comments section.</p>\n<ol>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/xmlrpc_call/\" rel=\"nofollow noreferrer\"><code>xmlrpc_call</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#pingbacks\" rel=\"nofollow noreferrer\">pingbacks</a> sent via the XML-RPC method:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 );\nfunction disallow_external_xmlrpc_pingback( $name, $args, $server ) {\n if ( 'pingback.ping' == $name &amp;&amp; false === strpos( $args[0], home_url() ) ) {\n // Exit with a proper error.\n $server-&gt;error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) );\n }\n}\n</code></pre>\n</li>\n<li><p>This uses the <a href=\"https://developer.wordpress.org/reference/hooks/pre_trackback_post/\" rel=\"nofollow noreferrer\"><code>pre_trackback_post</code> action</a> to disable <a href=\"https://wordpress.org/support/article/introduction-to-blogging/#trackbacks\" rel=\"nofollow noreferrer\">trackbacks</a> sent via the standard HTTP POST method (i.e. not using XML-RPC):</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 );\nfunction disallow_external_POST_trackback( $tb_id, $tb_url ) {\n if ( false === strpos( $tb_url, home_url() ) ) {\n // Exit with a proper error.\n trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' );\n }\n}\n</code></pre>\n</li>\n</ol>\n<p>And BTW, in the code in the question, <code>$home</code> is undefined and it should be <code>$Home</code> ( note the uppercase &quot;H&quot; and see <a href=\"https://www.php.net/manual/en/language.variables.basics.php\" rel=\"nofollow noreferrer\">this</a> which says, &quot;<em>variable name is case-sensitive</em>&quot; :) ).</p>\n" } ]
    2021/09/03
    [ "https://wordpress.stackexchange.com/questions/395184", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
    In my current case, the system try to find a page and show 404 if it does not find. I would like with the same url... like [https://example.com/{{slug}}/](https://example.com/%7B%7Bslug%7D%7D/) 1. Check if a page with this slug exists : 1. * Yes - show the page 2. * No - switch to the category page (with same slug) 3. * No category page -> show page 404 What is the best recommandanted way to do this in WP?
    If you want to receive only linkbacks from your own WordPress site, then try both of these: But if you want to allow all that were sent as *trackbacks* (where the comment type is `trackback`), then just ignore the second snippet below, which I added because in default/core themes like Twenty Twenty-One, both pingbacks and trackbacks would each appear as a "Pingback" in the post's comments section. 1. This uses the [`xmlrpc_call` action](https://developer.wordpress.org/reference/hooks/xmlrpc_call/) to disable [pingbacks](https://wordpress.org/support/article/introduction-to-blogging/#pingbacks) sent via the XML-RPC method: ```php add_action( 'xmlrpc_call', 'disallow_external_xmlrpc_pingback', 10, 3 ); function disallow_external_xmlrpc_pingback( $name, $args, $server ) { if ( 'pingback.ping' == $name && false === strpos( $args[0], home_url() ) ) { // Exit with a proper error. $server->error( new IXR_Error( 0, 'Sorry, trackbacks from remote sites are not allowed.' ) ); } } ``` 2. This uses the [`pre_trackback_post` action](https://developer.wordpress.org/reference/hooks/pre_trackback_post/) to disable [trackbacks](https://wordpress.org/support/article/introduction-to-blogging/#trackbacks) sent via the standard HTTP POST method (i.e. not using XML-RPC): ```php add_action( 'pre_trackback_post', 'disallow_external_POST_trackback', 10, 2 ); function disallow_external_POST_trackback( $tb_id, $tb_url ) { if ( false === strpos( $tb_url, home_url() ) ) { // Exit with a proper error. trackback_response( 1, 'Sorry, trackbacks from remote sites are not allowed.' ); } } ``` And BTW, in the code in the question, `$home` is undefined and it should be `$Home` ( note the uppercase "H" and see [this](https://www.php.net/manual/en/language.variables.basics.php) which says, "*variable name is case-sensitive*" :) ).
    395,222
    <p>I have little problem how implement deleting data from database using row actions. I have my custom list which includes data from database table. <a href="https://i.stack.imgur.com/v8EuB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v8EuB.png" alt="List" /></a></p> <pre><code> function column_name( $item ) { $delete_nonce = wp_create_nonce(); $title = '&lt;strong&gt;' . $item['article_name'] . '&lt;/strong&gt;'; $actions = [ 'edit' =&gt; sprintf('&lt;a href=&quot;?page=%s&amp;id=%s&quot;&gt;Edit&lt;/a&gt;', 'edytuj-artykul', $item['article_id']), 'delete' =&gt; sprintf('&lt;a href=&quot;?page=%s&amp;action=%s&amp;article_id=%s&amp;_wpnonce=%s&quot;&gt;Delete&lt;/a&gt;', esc_attr( $_REQUEST['page'] ), 'delete', absint($item['article_id']), $delete_nonce) ]; return $title. $this-&gt;row_actions( $actions ); } function delete_article($item){ $article_id = $item['article_id']; global $wpdb; $table = 'wp_copywriter_articles'; $wpdb-&gt;query(&quot;DELETE FROM $table WHERE article_id = %d&quot;, $article_id); } </code></pre> <p>In the same file I added</p> <pre><code>add_action( 'admin_action_delete', 'delete_article' ); </code></pre> <p>When I click Delete action, nothing happend. I got link http://localhost/wordpress/wp-admin/admin.php?page=Artykuly&amp;action=delete&amp;article_id=26&amp;_wpnonce=60a01b82d7</p> <p>but record is not deleted from database.</p> <p>For testing, I added a specific ID number of article to the delete_article method in the SQL query but still not works, so this method is not used by WP, when I click delete button.</p> <p>Someone can give me any tip what am I doing wrong, because I spent on this few few hours :)</p> <p>Best Regards, Bartek</p> <p>@EDIT</p> <p><strong>SOLVED</strong></p> <p>My mistake was put delete_article() method to my custom list class. When I put my method to functions.php, everything works! :)</p>
    [ { "answer_id": 395224, "author": "Mafnah", "author_id": 104860, "author_profile": "https://wordpress.stackexchange.com/users/104860", "pm_score": 2, "selected": false, "text": "<p>I think it's better to use the <a href=\"https://developer.wordpress.org/reference/classes/wpdb/delete/\" rel=\"nofollow noreferrer\">$wpdb-&gt;delete()</a> function to remove a row.</p>\n<pre><code>$article_id = $item['article_id'];\n$table = 'wp_copywriter_articles';\n$wpdb-&gt;delete( $table, array( 'id' =&gt; $article_id ) );\n</code></pre>\n" }, { "answer_id": 395226, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": true, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/admin_action__requestaction/\" rel=\"nofollow noreferrer\">&quot;admin_action_{$_REQUEST['action']}&quot; hook</a> does not pass any arguments. You would need to get the article_id from the $_REQUEST array. There are also a few other concerns such as:</p>\n<ol>\n<li>You're not assigning an action when you call <code>wp_create_nonce()</code>.</li>\n<li>As <a href=\"https://wordpress.stackexchange.com/a/395224/7355\">Mafnah suggets in their ansewr</a>, you should use $wpdb::delete() as a shortcut for using <code>$wpdb::prepare()</code>.</li>\n</ol>\n<p>Here's how you could rewrite this:</p>\n<pre><code>function column_name( $item ) {\n $delete_nonce = wp_create_nonce( 'delete_article' );\n $actions = [\n 'delete' =&gt; add_query_arg( array(\n 'action' =&gt; 'delete',\n 'article_id' =&gt; $item['article_id'],\n '_wpnonce' =&gt; $delete_nonce,\n ), admin_url( 'admin.php' ) ),\n ];\n /* Etc... */\n}\n\nfunction delete_article() {\n\n global $wpdb;\n\n // Ensure we can verify our nonce.\n if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) {\n wp_die( esc_html__( 'Could not verify request. Please try again.' ) );\n\n // Ensure we have an article ID provided.\n } else if( ! isset( $_REQUEST['article_id'] ) ) {\n wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) );\n\n // Ensure we're able to delete the actual article.\n } else if( false === $wpdb-&gt;delete( 'wp_copywriter_articles', array( 'article_id' =&gt; $_REQUEST['article_id'] ) ) ) {\n wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) );\n }\n\n // Redirect back to original page with 'success' $_GET\n wp_safe_redirect( add_query_arg( array(\n 'page' =&gt; ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404',\n 'success' =&gt; 1,\n ), admin_url( 'admin.php' ) ) );\n exit();\n\n}\n</code></pre>\n" } ]
    2021/09/04
    [ "https://wordpress.stackexchange.com/questions/395222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212087/" ]
    I have little problem how implement deleting data from database using row actions. I have my custom list which includes data from database table. [![List](https://i.stack.imgur.com/v8EuB.png)](https://i.stack.imgur.com/v8EuB.png) ``` function column_name( $item ) { $delete_nonce = wp_create_nonce(); $title = '<strong>' . $item['article_name'] . '</strong>'; $actions = [ 'edit' => sprintf('<a href="?page=%s&id=%s">Edit</a>', 'edytuj-artykul', $item['article_id']), 'delete' => sprintf('<a href="?page=%s&action=%s&article_id=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint($item['article_id']), $delete_nonce) ]; return $title. $this->row_actions( $actions ); } function delete_article($item){ $article_id = $item['article_id']; global $wpdb; $table = 'wp_copywriter_articles'; $wpdb->query("DELETE FROM $table WHERE article_id = %d", $article_id); } ``` In the same file I added ``` add_action( 'admin_action_delete', 'delete_article' ); ``` When I click Delete action, nothing happend. I got link http://localhost/wordpress/wp-admin/admin.php?page=Artykuly&action=delete&article\_id=26&\_wpnonce=60a01b82d7 but record is not deleted from database. For testing, I added a specific ID number of article to the delete\_article method in the SQL query but still not works, so this method is not used by WP, when I click delete button. Someone can give me any tip what am I doing wrong, because I spent on this few few hours :) Best Regards, Bartek @EDIT **SOLVED** My mistake was put delete\_article() method to my custom list class. When I put my method to functions.php, everything works! :)
    The ["admin\_action\_{$\_REQUEST['action']}" hook](https://developer.wordpress.org/reference/hooks/admin_action__requestaction/) does not pass any arguments. You would need to get the article\_id from the $\_REQUEST array. There are also a few other concerns such as: 1. You're not assigning an action when you call `wp_create_nonce()`. 2. As [Mafnah suggets in their ansewr](https://wordpress.stackexchange.com/a/395224/7355), you should use $wpdb::delete() as a shortcut for using `$wpdb::prepare()`. Here's how you could rewrite this: ``` function column_name( $item ) { $delete_nonce = wp_create_nonce( 'delete_article' ); $actions = [ 'delete' => add_query_arg( array( 'action' => 'delete', 'article_id' => $item['article_id'], '_wpnonce' => $delete_nonce, ), admin_url( 'admin.php' ) ), ]; /* Etc... */ } function delete_article() { global $wpdb; // Ensure we can verify our nonce. if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) { wp_die( esc_html__( 'Could not verify request. Please try again.' ) ); // Ensure we have an article ID provided. } else if( ! isset( $_REQUEST['article_id'] ) ) { wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) ); // Ensure we're able to delete the actual article. } else if( false === $wpdb->delete( 'wp_copywriter_articles', array( 'article_id' => $_REQUEST['article_id'] ) ) ) { wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) ); } // Redirect back to original page with 'success' $_GET wp_safe_redirect( add_query_arg( array( 'page' => ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404', 'success' => 1, ), admin_url( 'admin.php' ) ) ); exit(); } ```
    395,419
    <p>I have a load of data as JSON that I am trying to save into a fresh install of WordPress.</p> <p>I am using <a href="https://github.com/puppeteer/puppeteer" rel="nofollow noreferrer">puppeteer</a> to log into and create each page, and <code>wp.blocks.createBlock</code> to programmatically create the blocks.</p> <pre><code>// Input the page title const headingInput = document.querySelector(&quot;#post-title-0&quot;); headingInput.innerHTML = json.data.heading; var changeEvent = new Event(&quot;change&quot;, { bubbles: true, cancelable: true, }); headingInput.dispatchEvent(changeEvent); /** * Next up, create each of the gutenberg blocks */ json.data.blocks.forEach((block) =&gt; { if ( block.className == &quot;feature text-feature&quot; ) { block.content.forEach((element) =&gt; { if (element.hasOwnProperty(&quot;gutenbergBlock&quot;)) { var el = wp.element.createElement; insertedBlock = wp.blocks.createBlock( element.gutenbergBlock, element.attributes ); wp.data.dispatch(&quot;core/editor&quot;).insertBlocks(insertedBlock); } }); } }); // Attempt to trigger the save: document .querySelectorAll(&quot;.editor-post-publish-button&quot;) .forEach((button) =&gt; { console.log(&quot;clicking button!&quot;); var clickEvent = new MouseEvent(&quot;click&quot;, { view: window, bubbles: true, cancelable: false, }); button.dispatchEvent(clickEvent); }); </code></pre> <p>Above, I attempt to click on the save button to save the post, however this part does not work.</p> <p>Is there a way to trigger the saving of page content? Something like: <code>wp.blocks.save()</code>? I have trawled the documentation but can't find anything so niche.</p>
    [ { "answer_id": 395467, "author": "dgwyer", "author_id": 8961, "author_profile": "https://wordpress.stackexchange.com/users/8961", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <code>savePost</code>?</p>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost</a></p>\n" }, { "answer_id": 411100, "author": "Vakarelov", "author_id": 221869, "author_profile": "https://wordpress.stackexchange.com/users/221869", "pm_score": 1, "selected": false, "text": "<p>You can do this with:</p>\n<pre><code>wp.data.dispatch( 'core/editor' ).savePost()\n</code></pre>\n" } ]
    2021/09/09
    [ "https://wordpress.stackexchange.com/questions/395419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27866/" ]
    I have a load of data as JSON that I am trying to save into a fresh install of WordPress. I am using [puppeteer](https://github.com/puppeteer/puppeteer) to log into and create each page, and `wp.blocks.createBlock` to programmatically create the blocks. ``` // Input the page title const headingInput = document.querySelector("#post-title-0"); headingInput.innerHTML = json.data.heading; var changeEvent = new Event("change", { bubbles: true, cancelable: true, }); headingInput.dispatchEvent(changeEvent); /** * Next up, create each of the gutenberg blocks */ json.data.blocks.forEach((block) => { if ( block.className == "feature text-feature" ) { block.content.forEach((element) => { if (element.hasOwnProperty("gutenbergBlock")) { var el = wp.element.createElement; insertedBlock = wp.blocks.createBlock( element.gutenbergBlock, element.attributes ); wp.data.dispatch("core/editor").insertBlocks(insertedBlock); } }); } }); // Attempt to trigger the save: document .querySelectorAll(".editor-post-publish-button") .forEach((button) => { console.log("clicking button!"); var clickEvent = new MouseEvent("click", { view: window, bubbles: true, cancelable: false, }); button.dispatchEvent(clickEvent); }); ``` Above, I attempt to click on the save button to save the post, however this part does not work. Is there a way to trigger the saving of page content? Something like: `wp.blocks.save()`? I have trawled the documentation but can't find anything so niche.
    You can do this with: ``` wp.data.dispatch( 'core/editor' ).savePost() ```
    395,431
    <p>I'm building a webshop with Wordpress and Woocommerce. On the productoverview (archive) of a productcategories I want to show a label if the product has the category 'New'. The following code works on the product-single, but it won't show on the productcategory-page if I add the action in content-product.php.</p> <p>I used the following code to show a label on the single product page and it works as it should.</p> <pre><code>function resign_article_is_new(){ if ( is_product() &amp;&amp; has_term( 'Nieuw', 'product_cat' ) ) { echo '&lt;p class=&quot;new-lable&quot;&gt;New&lt;/p&gt;'; } } add_action( 'resign_new_article', 'resign_article_is_new'); </code></pre> <p>When I want to show the label on the productcategory overview I used this, but the label wouldn't appear.</p> <pre><code>do_action('resign_new_article'); </code></pre> <p>Hope you can tell me what I'm doing wrong</p>
    [ { "answer_id": 395467, "author": "dgwyer", "author_id": 8961, "author_profile": "https://wordpress.stackexchange.com/users/8961", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <code>savePost</code>?</p>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost</a></p>\n" }, { "answer_id": 411100, "author": "Vakarelov", "author_id": 221869, "author_profile": "https://wordpress.stackexchange.com/users/221869", "pm_score": 1, "selected": false, "text": "<p>You can do this with:</p>\n<pre><code>wp.data.dispatch( 'core/editor' ).savePost()\n</code></pre>\n" } ]
    2021/09/09
    [ "https://wordpress.stackexchange.com/questions/395431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/209621/" ]
    I'm building a webshop with Wordpress and Woocommerce. On the productoverview (archive) of a productcategories I want to show a label if the product has the category 'New'. The following code works on the product-single, but it won't show on the productcategory-page if I add the action in content-product.php. I used the following code to show a label on the single product page and it works as it should. ``` function resign_article_is_new(){ if ( is_product() && has_term( 'Nieuw', 'product_cat' ) ) { echo '<p class="new-lable">New</p>'; } } add_action( 'resign_new_article', 'resign_article_is_new'); ``` When I want to show the label on the productcategory overview I used this, but the label wouldn't appear. ``` do_action('resign_new_article'); ``` Hope you can tell me what I'm doing wrong
    You can do this with: ``` wp.data.dispatch( 'core/editor' ).savePost() ```
    395,551
    <p>I have a function in a theme:</p> <pre><code>$category = isset($_GET['category']) ? wp_unslash($_GET['category']) : ''; </code></pre> <p>The problem is that it outputs my categories like this:</p> <p>&quot;test-category&quot;</p> <p>I want, however, to show: <strong>&quot;Test Category&quot;</strong>, just like it's saved in the backend, without the dashes and the smaller letters.</p> <p>Is there a way I can get rid of this slug and use the nicename instead? I tried a lot of things (like the <code>get_term_by()</code> function), but nothing works for me. I guess it's because of the fact that I am using the $category variable.</p> <p>Can someone help me?</p>
    [ { "answer_id": 395467, "author": "dgwyer", "author_id": 8961, "author_profile": "https://wordpress.stackexchange.com/users/8961", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <code>savePost</code>?</p>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost</a></p>\n" }, { "answer_id": 411100, "author": "Vakarelov", "author_id": 221869, "author_profile": "https://wordpress.stackexchange.com/users/221869", "pm_score": 1, "selected": false, "text": "<p>You can do this with:</p>\n<pre><code>wp.data.dispatch( 'core/editor' ).savePost()\n</code></pre>\n" } ]
    2021/09/13
    [ "https://wordpress.stackexchange.com/questions/395551", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34977/" ]
    I have a function in a theme: ``` $category = isset($_GET['category']) ? wp_unslash($_GET['category']) : ''; ``` The problem is that it outputs my categories like this: "test-category" I want, however, to show: **"Test Category"**, just like it's saved in the backend, without the dashes and the smaller letters. Is there a way I can get rid of this slug and use the nicename instead? I tried a lot of things (like the `get_term_by()` function), but nothing works for me. I guess it's because of the fact that I am using the $category variable. Can someone help me?
    You can do this with: ``` wp.data.dispatch( 'core/editor' ).savePost() ```
    395,602
    <p>I'm beginning in PHP and I'm building a little shop with WooCommerce. I'm trying to display the top level parent category of a product in the body class.</p> <p>This code works well :</p> <pre><code>function woo_custom_taxonomy_in_body_class( $classes ){ $custom_terms = get_the_terms(0, 'product_cat'); if ($custom_terms) { foreach ($custom_terms as $custom_term) { // Check if the parent category exists: if( $custom_term-&gt;parent &gt; 0 ) { // Get the parent product category: $parent = get_term( $custom_term-&gt;parent, 'product_cat' ); // Append the parent class: if ( ! is_wp_error( $parent ) ) $classes[] = 'product_parent_cat_' . $parent-&gt;slug; } $classes[] = 'product_cat_' . $custom_term-&gt;slug; } } return $classes; } add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' ); </code></pre> <p>But it just gets the parent category. In a tree like this :</p> <p>&quot;Toplevel cat &gt; Parent cat &gt; Category &gt; My product&quot;</p> <p>It will just get the parent one. However, I'd like to get the top level category.</p> <p>Do you have a solution ? Thank's a lot in advance!</p>
    [ { "answer_id": 395467, "author": "dgwyer", "author_id": 8961, "author_profile": "https://wordpress.stackexchange.com/users/8961", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <code>savePost</code>?</p>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost</a></p>\n" }, { "answer_id": 411100, "author": "Vakarelov", "author_id": 221869, "author_profile": "https://wordpress.stackexchange.com/users/221869", "pm_score": 1, "selected": false, "text": "<p>You can do this with:</p>\n<pre><code>wp.data.dispatch( 'core/editor' ).savePost()\n</code></pre>\n" } ]
    2021/09/14
    [ "https://wordpress.stackexchange.com/questions/395602", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212456/" ]
    I'm beginning in PHP and I'm building a little shop with WooCommerce. I'm trying to display the top level parent category of a product in the body class. This code works well : ``` function woo_custom_taxonomy_in_body_class( $classes ){ $custom_terms = get_the_terms(0, 'product_cat'); if ($custom_terms) { foreach ($custom_terms as $custom_term) { // Check if the parent category exists: if( $custom_term->parent > 0 ) { // Get the parent product category: $parent = get_term( $custom_term->parent, 'product_cat' ); // Append the parent class: if ( ! is_wp_error( $parent ) ) $classes[] = 'product_parent_cat_' . $parent->slug; } $classes[] = 'product_cat_' . $custom_term->slug; } } return $classes; } add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' ); ``` But it just gets the parent category. In a tree like this : "Toplevel cat > Parent cat > Category > My product" It will just get the parent one. However, I'd like to get the top level category. Do you have a solution ? Thank's a lot in advance!
    You can do this with: ``` wp.data.dispatch( 'core/editor' ).savePost() ```
    395,697
    <p>How can I totally disable the wordpress auto-resizing when uploading images, but only for images that have a certain string in its filename.</p> <p>Eg. disable auto-resizing on images in which its filenames contains the string &quot;HD&quot;.</p> <p>image_xyz.jpeg &gt;&gt; auto-resizing function enabled <br>imageHD_xyz.jpeg &gt;&gt; auto-resizing function disabled <br>image_HD.jpeg &gt;&gt; auto-resizing function disabled</p> <p>Whats the reason behind this?</p> <p>I have to work whit images in the best quality on a specific plugin which will send them to another platform and will not be published in the mainsite, so therefore resized versions are not needed</p> <p>The following code works but based on file format.</p> <pre><code>function wpdocs_disable_upload_sizes( $sizes, $image_meta ) { // Get filetype data. $filetype = wp_check_filetype( $image_meta['file'] ); $exclude_file_types = array( 'image/png', ); // Check if file type is on exclude list if ( in_array( $filetype['type'], $exclude_file_types ) ) { $sizes = array(); } // Return sizes you want to create from image (None if image is gif.) return $sizes; } add_filter( 'intermediate_image_sizes_advanced', 'wpdocs_disable_upload_sizes', 10, 2 ); </code></pre>
    [ { "answer_id": 395467, "author": "dgwyer", "author_id": 8961, "author_profile": "https://wordpress.stackexchange.com/users/8961", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <code>savePost</code>?</p>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/data/data-core-editor/#savepost</a></p>\n" }, { "answer_id": 411100, "author": "Vakarelov", "author_id": 221869, "author_profile": "https://wordpress.stackexchange.com/users/221869", "pm_score": 1, "selected": false, "text": "<p>You can do this with:</p>\n<pre><code>wp.data.dispatch( 'core/editor' ).savePost()\n</code></pre>\n" } ]
    2021/09/16
    [ "https://wordpress.stackexchange.com/questions/395697", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212522/" ]
    How can I totally disable the wordpress auto-resizing when uploading images, but only for images that have a certain string in its filename. Eg. disable auto-resizing on images in which its filenames contains the string "HD". image\_xyz.jpeg >> auto-resizing function enabled imageHD\_xyz.jpeg >> auto-resizing function disabled image\_HD.jpeg >> auto-resizing function disabled Whats the reason behind this? I have to work whit images in the best quality on a specific plugin which will send them to another platform and will not be published in the mainsite, so therefore resized versions are not needed The following code works but based on file format. ``` function wpdocs_disable_upload_sizes( $sizes, $image_meta ) { // Get filetype data. $filetype = wp_check_filetype( $image_meta['file'] ); $exclude_file_types = array( 'image/png', ); // Check if file type is on exclude list if ( in_array( $filetype['type'], $exclude_file_types ) ) { $sizes = array(); } // Return sizes you want to create from image (None if image is gif.) return $sizes; } add_filter( 'intermediate_image_sizes_advanced', 'wpdocs_disable_upload_sizes', 10, 2 ); ```
    You can do this with: ``` wp.data.dispatch( 'core/editor' ).savePost() ```
    395,709
    <p>Ok so basically I have this kind of situation.</p> <p>My first step is to filter out the posts using an array, let's say using this:</p> <pre><code>$posts = get_posts(array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 99999999, 'meta_query' =&gt; array( array( 'key' =&gt; 'status', 'value' =&gt; 'active', ), ), 'orderby' =&gt; 'rand' )); </code></pre> <p>So, let' say after the above code I'm left with a 20 random posts.</p> <p>On the second step I use the PHP filter (which is not possible in the above array):</p> <pre><code>&lt;?php $postid = get_the_ID(); $a1=get_post_meta( $postid, 'a1' , true ); $a2=get_post_meta( $postid, 'a2' , true ); if ($a1 &lt; $a2): ?&gt; &lt;?php the_title(); ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>The above filter's out the results, and after that I'm now left with, let's say, 5 post results.</p> <p>My question is, is there a php code that will choose just 1 random post from that list?</p> <p>I don't need 5, I just need 1.</p> <p>Hope I'm clear.</p> <p>Desperately need help here.</p>
    [ { "answer_id": 395728, "author": "Ahmad Ahmad", "author_id": 212539, "author_profile": "https://wordpress.stackexchange.com/users/212539", "pm_score": 2, "selected": true, "text": "<p>I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.</p>\n<p>so you can try to test &quot;<a href=\"https://kinsta.com/knowledgebase/disable-wordpress-plugins/\" rel=\"nofollow noreferrer\">manually disable plugins Wordpress</a>&quot;</p>\n" }, { "answer_id": 395743, "author": "Philtao", "author_id": 212524, "author_profile": "https://wordpress.stackexchange.com/users/212524", "pm_score": 0, "selected": false, "text": "<p>For no apparent reason, this morning I can login again!!!</p>\n<p>A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions</p>\n" } ]
    2021/09/16
    [ "https://wordpress.stackexchange.com/questions/395709", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202740/" ]
    Ok so basically I have this kind of situation. My first step is to filter out the posts using an array, let's say using this: ``` $posts = get_posts(array( 'post_type' => 'post', 'posts_per_page' => 99999999, 'meta_query' => array( array( 'key' => 'status', 'value' => 'active', ), ), 'orderby' => 'rand' )); ``` So, let' say after the above code I'm left with a 20 random posts. On the second step I use the PHP filter (which is not possible in the above array): ``` <?php $postid = get_the_ID(); $a1=get_post_meta( $postid, 'a1' , true ); $a2=get_post_meta( $postid, 'a2' , true ); if ($a1 < $a2): ?> <?php the_title(); ?> <?php endif; ?> ``` The above filter's out the results, and after that I'm now left with, let's say, 5 post results. My question is, is there a php code that will choose just 1 random post from that list? I don't need 5, I just need 1. Hope I'm clear. Desperately need help here.
    I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard. so you can try to test "[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)"
    395,714
    <p>I have a need to capture data in a WordPress plugin and append it into some sort of log.</p> <p>The data I want happens to be slow SQL queries from $wpdb-&gt;queries. I'm hoping to present useful &quot;dirty dozen&quot; SQL queries to my users to help them with optimizations. It's a companion plugin, or maybe a feature set, for <a href="https://wordpress.org/plugins/index-wp-mysql-for-speed/" rel="nofollow noreferrer">this plugin</a>. (I'm aware of the performance issues around this kind of system instrumentation. Capture sessions will be limited in duration. Etc.)</p> <p>In each relevant pageview I will capture some data and log it. Then later my plugin will retrieve, process, and delete the log. How can I do this data capture in a WordPress-friendly way?</p> <p>I'm thinking of using a transient to hold the log. I'm using expiring transients in my hope to avoid unprocessed logs from accumulating. My data flow would look something like this (pseudocode).</p> <pre class="lang-php prettyprint-override"><code>$logdata = get_transient( $tName ); $logdata .= $newdata; set_transient( $tName, $logdata, 86400 ); </code></pre> <p>But, on a busy site multiple php instances will race each other. One instance will do its <code>get_transient()</code>, then another instance will do its get before the first instance does its set. So one of the instances' data will be lost.</p> <p>If I were to do this with plain old MyISAM-compatible SQL I'd do something like this:</p> <pre class="lang-sql prettyprint-override"><code>UPDATE wp_options WHERE option_name='tname' SET option_value = option_value + 'newvalue' </code></pre> <p>That avoids the possible race condition. It would be great if there were an <code>append_transient($name, $val, $timeout)</code> function to do this operation.</p> <p>I could also lock the table, but that would be really rude.</p> <p>If I knew my plugin was on a site with InnoDB in its database I could use an SQL transaction. But I don't know that.</p> <p><strong>Is there a better way?</strong></p>
    [ { "answer_id": 395728, "author": "Ahmad Ahmad", "author_id": 212539, "author_profile": "https://wordpress.stackexchange.com/users/212539", "pm_score": 2, "selected": true, "text": "<p>I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.</p>\n<p>so you can try to test &quot;<a href=\"https://kinsta.com/knowledgebase/disable-wordpress-plugins/\" rel=\"nofollow noreferrer\">manually disable plugins Wordpress</a>&quot;</p>\n" }, { "answer_id": 395743, "author": "Philtao", "author_id": 212524, "author_profile": "https://wordpress.stackexchange.com/users/212524", "pm_score": 0, "selected": false, "text": "<p>For no apparent reason, this morning I can login again!!!</p>\n<p>A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions</p>\n" } ]
    2021/09/16
    [ "https://wordpress.stackexchange.com/questions/395714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13596/" ]
    I have a need to capture data in a WordPress plugin and append it into some sort of log. The data I want happens to be slow SQL queries from $wpdb->queries. I'm hoping to present useful "dirty dozen" SQL queries to my users to help them with optimizations. It's a companion plugin, or maybe a feature set, for [this plugin](https://wordpress.org/plugins/index-wp-mysql-for-speed/). (I'm aware of the performance issues around this kind of system instrumentation. Capture sessions will be limited in duration. Etc.) In each relevant pageview I will capture some data and log it. Then later my plugin will retrieve, process, and delete the log. How can I do this data capture in a WordPress-friendly way? I'm thinking of using a transient to hold the log. I'm using expiring transients in my hope to avoid unprocessed logs from accumulating. My data flow would look something like this (pseudocode). ```php $logdata = get_transient( $tName ); $logdata .= $newdata; set_transient( $tName, $logdata, 86400 ); ``` But, on a busy site multiple php instances will race each other. One instance will do its `get_transient()`, then another instance will do its get before the first instance does its set. So one of the instances' data will be lost. If I were to do this with plain old MyISAM-compatible SQL I'd do something like this: ```sql UPDATE wp_options WHERE option_name='tname' SET option_value = option_value + 'newvalue' ``` That avoids the possible race condition. It would be great if there were an `append_transient($name, $val, $timeout)` function to do this operation. I could also lock the table, but that would be really rude. If I knew my plugin was on a site with InnoDB in its database I could use an SQL transaction. But I don't know that. **Is there a better way?**
    I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard. so you can try to test "[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)"
    395,795
    <p>I have been told that using this in the array:</p> <pre><code>'orderby' =&gt; 'rand' </code></pre> <p>will cause this:</p> <blockquote> <p>Ordering by random is extremely expensive to query, involving creating temporary database tables, and scans, as it has to copy the entire posts table, then randomly re-order the posts, then finally do the actual query on the new table before destroying it.</p> </blockquote> <p>And I have been advised:</p> <blockquote> <p>It's much easier to ask for the first post that occurs after a random date.</p> </blockquote> <p>Can anyone elaborate on this?</p> <p>Is there an array code line that will do the above?</p> <p>Any resource regarding this would be very appreciated.</p>
    [ { "answer_id": 395728, "author": "Ahmad Ahmad", "author_id": 212539, "author_profile": "https://wordpress.stackexchange.com/users/212539", "pm_score": 2, "selected": true, "text": "<p>I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.</p>\n<p>so you can try to test &quot;<a href=\"https://kinsta.com/knowledgebase/disable-wordpress-plugins/\" rel=\"nofollow noreferrer\">manually disable plugins Wordpress</a>&quot;</p>\n" }, { "answer_id": 395743, "author": "Philtao", "author_id": 212524, "author_profile": "https://wordpress.stackexchange.com/users/212524", "pm_score": 0, "selected": false, "text": "<p>For no apparent reason, this morning I can login again!!!</p>\n<p>A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions</p>\n" } ]
    2021/09/18
    [ "https://wordpress.stackexchange.com/questions/395795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202740/" ]
    I have been told that using this in the array: ``` 'orderby' => 'rand' ``` will cause this: > > Ordering by random is extremely expensive to query, involving creating > temporary database tables, and scans, as it has to copy the entire > posts table, then randomly re-order the posts, then finally do the > actual query on the new table before destroying it. > > > And I have been advised: > > It's much easier to ask for the first post that occurs after a random date. > > > Can anyone elaborate on this? Is there an array code line that will do the above? Any resource regarding this would be very appreciated.
    I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard. so you can try to test "[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)"
    395,841
    <p>It's really hilarious but my <code>the_date()</code> and <code>the_time()</code> functions show the current date and time instead of the post's publication time, therefore at each refresh of the page, the time changes according to the actual time and date. I am using these functions in a single template for a custom post in the loop, like so:</p> <pre><code>&lt;?php if(have_posts()): ?&gt; &lt;?php while(have_posts()): the_post(); ?&gt; &lt;h3&gt; &lt;?=&quot;Titre du projet&quot;?&gt; &lt;/h3&gt; &lt;?php the_title(); ?&gt; &lt;h3&gt;&lt;?=&quot;Description&quot;?&gt;&lt;/h3&gt; &lt;?php the_content(); ?&gt; &lt;p&gt; &lt;?php the_date(); ?&gt; à &lt;?php the_time(); ?&gt; &lt;?php endwhile?&gt; &lt;?php endif;?&gt; </code></pre> <p>What's wrong? I tried other similar functions or get post date in the <code>$post</code> object, but in their format, the date and time are inseparable. and I need them separately. Thanks.</p>
    [ { "answer_id": 395728, "author": "Ahmad Ahmad", "author_id": 212539, "author_profile": "https://wordpress.stackexchange.com/users/212539", "pm_score": 2, "selected": true, "text": "<p>I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard.</p>\n<p>so you can try to test &quot;<a href=\"https://kinsta.com/knowledgebase/disable-wordpress-plugins/\" rel=\"nofollow noreferrer\">manually disable plugins Wordpress</a>&quot;</p>\n" }, { "answer_id": 395743, "author": "Philtao", "author_id": 212524, "author_profile": "https://wordpress.stackexchange.com/users/212524", "pm_score": 0, "selected": false, "text": "<p>For no apparent reason, this morning I can login again!!!</p>\n<p>A pity I cannot reproduce, but at least the 8 hours I spent looking for the answer were not completely wasted as I now know a bit more about the workings of Wordpress.\nThank you for the contributions</p>\n" } ]
    2021/09/19
    [ "https://wordpress.stackexchange.com/questions/395841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210079/" ]
    It's really hilarious but my `the_date()` and `the_time()` functions show the current date and time instead of the post's publication time, therefore at each refresh of the page, the time changes according to the actual time and date. I am using these functions in a single template for a custom post in the loop, like so: ``` <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <h3> <?="Titre du projet"?> </h3> <?php the_title(); ?> <h3><?="Description"?></h3> <?php the_content(); ?> <p> <?php the_date(); ?> à <?php the_time(); ?> <?php endwhile?> <?php endif;?> ``` What's wrong? I tried other similar functions or get post date in the `$post` object, but in their format, the date and time are inseparable. and I need them separately. Thanks.
    I think a plugin did update ( if they are set to be auto-updated ), then this plugin may have crushed the dashboard. so you can try to test "[manually disable plugins Wordpress](https://kinsta.com/knowledgebase/disable-wordpress-plugins/)"
    395,953
    <p>I have registered some styles and scripts that should be loaded if a template part is loaded in a template file. For ex:</p> <p>in home.php</p> <pre><code>&lt;?php get_template_part( 'template-parts/external_links'); ?&gt; </code></pre> <p>(this template-part is loaded across different template files) therefore, I want to enqueue (a previously registered file in functions.php)</p> <p>Using template files for example I use:</p> <pre><code>if(is_page_template('admin.php')){ wp_enqueue_script( 'unicorn-admin'); } </code></pre> <p>Is there a way to enqueue a file when get_template_part( 'template-parts/external_links'); is used?</p>
    [ { "answer_id": 396106, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 0, "selected": false, "text": "<p>A question very similar to this has already been <a href=\"https://stackoverflow.com/questions/28332354/how-can-i-enqueue-script-based-on-template-part\">answered here</a>. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.</p>\n<p>First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:</p>\n<pre><code>// Conditional script loading\nfunction conscripts($type) {\n if($type==='blue'):\n // Register blue stylesheet\n wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n elseif($type==='red'):\n // Register red stylesheet\n wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n endif;\n}\n</code></pre>\n<p>Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:</p>\n<pre><code>if( get_field('color') == 'red') {\n\n get_template_part( 'red' ); \n conscripts('red');\n\n} elseif (get_field('color') == 'blue') {\n\n get_template_part('blue' ); \n conscripts('blue');\n}\n</code></pre>\n<p>Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.</p>\n" }, { "answer_id": 396107, "author": "cameronjonesweb", "author_id": 65582, "author_profile": "https://wordpress.stackexchange.com/users/65582", "pm_score": 1, "selected": false, "text": "<p>Just call <code>wp_enqueue_script</code>/<code>wp_enqueue_style</code> in the template part file itself.</p>\n" }, { "answer_id": 396108, "author": "Laloptk", "author_id": 210397, "author_profile": "https://wordpress.stackexchange.com/users/210397", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>get_template_part_{$slug}</code> hook, which fires before a template part is loaded. You can find the reference <a href=\"https://wp-kama.com/hook/get_template_part_(slug)\" rel=\"noreferrer\">here</a>, which I find more useful than the official reference.</p>\n<p>So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the <code>template-parts/content/content-single.php</code> part, and I created a <code>test.js</code> file, with an alert inside it, in the <code>assets/js/</code> folder of the theme. Then, I placed the following code in <code>functions.php</code>.</p>\n<pre><code>function test_template_part_hook($slug, $name, $args) {\n wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n</code></pre>\n<p>And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the <code>wp_enqueue_script</code>function with the rest of the arguments that function uses.</p>\n<p>So, basically what you need to do is what is described above, using <code>get_template_part_slug</code> as the action name, where <code>slug</code> is the path of the template part file you want to use, in your case, for what I read in you question, <code>slug = 'template-parts/external_links'</code>, so the entire hook name should be <code>get_template_part_template-parts/external_links</code>.</p>\n" } ]
    2021/09/21
    [ "https://wordpress.stackexchange.com/questions/395953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/206371/" ]
    I have registered some styles and scripts that should be loaded if a template part is loaded in a template file. For ex: in home.php ``` <?php get_template_part( 'template-parts/external_links'); ?> ``` (this template-part is loaded across different template files) therefore, I want to enqueue (a previously registered file in functions.php) Using template files for example I use: ``` if(is_page_template('admin.php')){ wp_enqueue_script( 'unicorn-admin'); } ``` Is there a way to enqueue a file when get\_template\_part( 'template-parts/external\_links'); is used?
    You can use the `get_template_part_{$slug}` hook, which fires before a template part is loaded. You can find the reference [here](https://wp-kama.com/hook/get_template_part_(slug)), which I find more useful than the official reference. So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the `template-parts/content/content-single.php` part, and I created a `test.js` file, with an alert inside it, in the `assets/js/` folder of the theme. Then, I placed the following code in `functions.php`. ``` function test_template_part_hook($slug, $name, $args) { wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery')); } add_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 ); ``` And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the `wp_enqueue_script`function with the rest of the arguments that function uses. So, basically what you need to do is what is described above, using `get_template_part_slug` as the action name, where `slug` is the path of the template part file you want to use, in your case, for what I read in you question, `slug = 'template-parts/external_links'`, so the entire hook name should be `get_template_part_template-parts/external_links`.
    396,005
    <p>I made a config.php file where I store some arrays for configuration like LDAP and other things. I need to call it on different templates but I also need to require it into function.php.</p> <p>When I do this this, I have warning and all my tables become Undefined.</p> <p><strong>EDIT</strong></p> <p>I found this solution : call my config.php into functions.php with : <code>require ( get_template_directory() . '/config.php' );</code></p> <p>Replaced this require from all my tempate/views by <code>global $ARRAY_NAME;</code></p>
    [ { "answer_id": 396106, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 0, "selected": false, "text": "<p>A question very similar to this has already been <a href=\"https://stackoverflow.com/questions/28332354/how-can-i-enqueue-script-based-on-template-part\">answered here</a>. Essentially, the solution is to write a function to load your scripts conditionally outside of your site's initial enqueue functions.</p>\n<p>First, create the functions with the necessary conditionals to load the scripts or styles you want, something like:</p>\n<pre><code>// Conditional script loading\nfunction conscripts($type) {\n if($type==='blue'):\n // Register blue stylesheet\n wp_enqueue_style( 'blue', get_template_directory_uri() . '/assets/styles/blue.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n elseif($type==='red'):\n // Register red stylesheet\n wp_enqueue_style( 'red', get_template_directory_uri() . '/assets/styles/red.css', array(), filemtime(get_template_directory() . '/assets/styles/scss'), 'all' );\n endif;\n}\n</code></pre>\n<p>Next, use the function to load the correct scripts/styles when the template part you're using is being used. Something like:</p>\n<pre><code>if( get_field('color') == 'red') {\n\n get_template_part( 'red' ); \n conscripts('red');\n\n} elseif (get_field('color') == 'blue') {\n\n get_template_part('blue' ); \n conscripts('blue');\n}\n</code></pre>\n<p>Without seeing your actual code I can't give you a more detailed answer, and while this approach isn't automated, it's a tidy solution to script/style bundling if you're unsure of what templates are being loaded where.</p>\n" }, { "answer_id": 396107, "author": "cameronjonesweb", "author_id": 65582, "author_profile": "https://wordpress.stackexchange.com/users/65582", "pm_score": 1, "selected": false, "text": "<p>Just call <code>wp_enqueue_script</code>/<code>wp_enqueue_style</code> in the template part file itself.</p>\n" }, { "answer_id": 396108, "author": "Laloptk", "author_id": 210397, "author_profile": "https://wordpress.stackexchange.com/users/210397", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>get_template_part_{$slug}</code> hook, which fires before a template part is loaded. You can find the reference <a href=\"https://wp-kama.com/hook/get_template_part_(slug)\" rel=\"noreferrer\">here</a>, which I find more useful than the official reference.</p>\n<p>So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the <code>template-parts/content/content-single.php</code> part, and I created a <code>test.js</code> file, with an alert inside it, in the <code>assets/js/</code> folder of the theme. Then, I placed the following code in <code>functions.php</code>.</p>\n<pre><code>function test_template_part_hook($slug, $name, $args) {\n wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));\n}\n\nadd_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );\n</code></pre>\n<p>And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the <code>wp_enqueue_script</code>function with the rest of the arguments that function uses.</p>\n<p>So, basically what you need to do is what is described above, using <code>get_template_part_slug</code> as the action name, where <code>slug</code> is the path of the template part file you want to use, in your case, for what I read in you question, <code>slug = 'template-parts/external_links'</code>, so the entire hook name should be <code>get_template_part_template-parts/external_links</code>.</p>\n" } ]
    2021/09/22
    [ "https://wordpress.stackexchange.com/questions/396005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194938/" ]
    I made a config.php file where I store some arrays for configuration like LDAP and other things. I need to call it on different templates but I also need to require it into function.php. When I do this this, I have warning and all my tables become Undefined. **EDIT** I found this solution : call my config.php into functions.php with : `require ( get_template_directory() . '/config.php' );` Replaced this require from all my tempate/views by `global $ARRAY_NAME;`
    You can use the `get_template_part_{$slug}` hook, which fires before a template part is loaded. You can find the reference [here](https://wp-kama.com/hook/get_template_part_(slug)), which I find more useful than the official reference. So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the `template-parts/content/content-single.php` part, and I created a `test.js` file, with an alert inside it, in the `assets/js/` folder of the theme. Then, I placed the following code in `functions.php`. ``` function test_template_part_hook($slug, $name, $args) { wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery')); } add_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 ); ``` And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the `wp_enqueue_script`function with the rest of the arguments that function uses. So, basically what you need to do is what is described above, using `get_template_part_slug` as the action name, where `slug` is the path of the template part file you want to use, in your case, for what I read in you question, `slug = 'template-parts/external_links'`, so the entire hook name should be `get_template_part_template-parts/external_links`.
    396,013
    <p>I'm trying to save post id and keyword (Yoast Focus Keyword) to a custom table when post is created or updated via <code>save_post</code> action. It saves everything fine on Publish (first-time) but when I update the post, it gets old value for focus keyword from database and doesn't save the new value.</p> <p>for example Focus Keyword (Publish) = &quot;Hello World&quot; (works fine and keyword is stored properly) Focus Keyword (1st Update) = &quot;Hello&quot; (Doesn't work and keeps &quot;Hello World&quot; in custom table) Focus Keyword (2nd Update) = &quot;Hello again&quot; (It saves &quot;Hello&quot;)</p> <p>So basically the problem is that get_post_meta($post_id, '_yoast_wpseo_focuskw', true) returns which is already in the database and not the new value that is being saved.</p> <p>What is the best way to get the new value while the post is being saved via <code>save_post</code> action?</p> <p>$_POST['_yoast_wpseo_focuskw'] won't work because Yoast Focus Keyword input field doesn't have name set on input field. <a href="https://i.imgur.com/a94kCl8.png" rel="nofollow noreferrer">Screenshot</a></p> <p>Any help would be appreciated. Thanks</p> <p>This is my code.</p> <pre class="lang-php prettyprint-override"><code>add_action('save_post', 'my_custom_table'); function my_custom_table($post_id) { global $wpdb; $table_name = $wpdb-&gt;prefix . &quot;custom_table&quot;; $data = [ 'post_id' =&gt; $post_id, 'keyword' =&gt; get_post_meta( $post_id, '_yoast_wpseo_focuskw', true ) ]; if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) { return; } else { //check if new post so insert if( strpos( wp_get_raw_referer(), 'post-new' ) &gt; 0 ) { if (get_post_status($post_id) === 'publish') { $wpdb-&gt;insert( $table_name, $data ); } } else { $wpdb-&gt;update( $table_name, $data, array( 'post_id' =&gt; $post_id ), array( '%d', '%s' ), array( '%d' ) ); } } } </code></pre>
    [ { "answer_id": 396045, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 0, "selected": false, "text": "<p>It really depends on when <code>_yoast_wpseo_focuskw</code> is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around <code>WPSEO_Meta::set_value()</code> <a href=\"https://github.com/Yoast/wordpress-seo/blob/1e151dbd01c1f1484a5713223acbb69801c8174f/inc/class-wpseo-meta.php#L692\" rel=\"nofollow noreferrer\">#</a>, can backtrace from there.</p>\n<p>Then adapt your code to that, queuing whatever you're doing <em>after</em> the new value has been written.</p>\n" }, { "answer_id": 396050, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 3, "selected": true, "text": "<p>WordPress fires the <a href=\"https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/\" rel=\"nofollow noreferrer\">updated_{$meta_type}_meta</a> hook which fires after the metadata is updated. In your case, the hook would be <code>updated_post_meta</code> and you could have your function run on that hook instead of the <code>save_post</code> hook.</p>\n" } ]
    2021/09/22
    [ "https://wordpress.stackexchange.com/questions/396013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161037/" ]
    I'm trying to save post id and keyword (Yoast Focus Keyword) to a custom table when post is created or updated via `save_post` action. It saves everything fine on Publish (first-time) but when I update the post, it gets old value for focus keyword from database and doesn't save the new value. for example Focus Keyword (Publish) = "Hello World" (works fine and keyword is stored properly) Focus Keyword (1st Update) = "Hello" (Doesn't work and keeps "Hello World" in custom table) Focus Keyword (2nd Update) = "Hello again" (It saves "Hello") So basically the problem is that get\_post\_meta($post\_id, '\_yoast\_wpseo\_focuskw', true) returns which is already in the database and not the new value that is being saved. What is the best way to get the new value while the post is being saved via `save_post` action? $\_POST['\_yoast\_wpseo\_focuskw'] won't work because Yoast Focus Keyword input field doesn't have name set on input field. [Screenshot](https://i.imgur.com/a94kCl8.png) Any help would be appreciated. Thanks This is my code. ```php add_action('save_post', 'my_custom_table'); function my_custom_table($post_id) { global $wpdb; $table_name = $wpdb->prefix . "custom_table"; $data = [ 'post_id' => $post_id, 'keyword' => get_post_meta( $post_id, '_yoast_wpseo_focuskw', true ) ]; if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) { return; } else { //check if new post so insert if( strpos( wp_get_raw_referer(), 'post-new' ) > 0 ) { if (get_post_status($post_id) === 'publish') { $wpdb->insert( $table_name, $data ); } } else { $wpdb->update( $table_name, $data, array( 'post_id' => $post_id ), array( '%d', '%s' ), array( '%d' ) ); } } } ```
    WordPress fires the [updated\_{$meta\_type}\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook.
    396,024
    <p>Here's my meta query:</p> <pre><code>$taxonomy_term = 1494; $args['meta_query'] = array( 'relation' =&gt; 'OR', 'mp_exists' =&gt; array( 'key' =&gt; 'tdlrm_mp_'.$taxonomy_term, 'type' =&gt; 'NUMERIC', ), 'mp_not_exists' =&gt; array( 'key' =&gt; 'tdlrm_mp_'.$taxonomy_term, 'compare' =&gt; 'NOT EXISTS' ) ); $args['orderby'] = array( 'meta_value_num' =&gt; 'ASC', 'title' =&gt; 'ASC' ); </code></pre> <p>The posts where <code>'tdlrm_mp_'.$taxonomy</code> key exists get placed first as expected. Hovewer, the rest do not get ordered by their title (actually, I can't figure out what they are ordered by). What am I doing wrong?</p> <p><a href="https://wordpress.stackexchange.com/questions/311227/wp-query-orderby-custom-field-then-post-date-in-one-query">This answer</a> doesn't help. I wrote my query according to <a href="https://developer.wordpress.org/reference/classes/wp_query/#:%7E:text=%27orderby%27%C2%A0%20%3D%3E%20array(%20%27meta_value_num%27%20%3D%3E%20%27DESC%27%2C%20%27title%27%20%3D%3E%20%27ASC%27%20)%2C" rel="nofollow noreferrer">this manual</a>.</p> <p><strong>Update</strong></p> <p>I ran WP's MySQL query in my database and saw the postmeta table joined twice. The posts that have no tdlrm_mp_{term} meta key still have some other meta key in the resulting table and the rest of the posts get ordered by the value of that meta. (<code>mp_exists</code> adds the first postmeta table, <code>mp_not_exists</code> adds the second one, where <code>mp_exists</code> does not exist. Still some other meta key exists in the first joined table, so the posts keep getting ordered by that column).</p>
    [ { "answer_id": 396045, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 0, "selected": false, "text": "<p>It really depends on when <code>_yoast_wpseo_focuskw</code> is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around <code>WPSEO_Meta::set_value()</code> <a href=\"https://github.com/Yoast/wordpress-seo/blob/1e151dbd01c1f1484a5713223acbb69801c8174f/inc/class-wpseo-meta.php#L692\" rel=\"nofollow noreferrer\">#</a>, can backtrace from there.</p>\n<p>Then adapt your code to that, queuing whatever you're doing <em>after</em> the new value has been written.</p>\n" }, { "answer_id": 396050, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 3, "selected": true, "text": "<p>WordPress fires the <a href=\"https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/\" rel=\"nofollow noreferrer\">updated_{$meta_type}_meta</a> hook which fires after the metadata is updated. In your case, the hook would be <code>updated_post_meta</code> and you could have your function run on that hook instead of the <code>save_post</code> hook.</p>\n" } ]
    2021/09/23
    [ "https://wordpress.stackexchange.com/questions/396024", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190417/" ]
    Here's my meta query: ``` $taxonomy_term = 1494; $args['meta_query'] = array( 'relation' => 'OR', 'mp_exists' => array( 'key' => 'tdlrm_mp_'.$taxonomy_term, 'type' => 'NUMERIC', ), 'mp_not_exists' => array( 'key' => 'tdlrm_mp_'.$taxonomy_term, 'compare' => 'NOT EXISTS' ) ); $args['orderby'] = array( 'meta_value_num' => 'ASC', 'title' => 'ASC' ); ``` The posts where `'tdlrm_mp_'.$taxonomy` key exists get placed first as expected. Hovewer, the rest do not get ordered by their title (actually, I can't figure out what they are ordered by). What am I doing wrong? [This answer](https://wordpress.stackexchange.com/questions/311227/wp-query-orderby-custom-field-then-post-date-in-one-query) doesn't help. I wrote my query according to [this manual](https://developer.wordpress.org/reference/classes/wp_query/#:%7E:text=%27orderby%27%C2%A0%20%3D%3E%20array(%20%27meta_value_num%27%20%3D%3E%20%27DESC%27%2C%20%27title%27%20%3D%3E%20%27ASC%27%20)%2C). **Update** I ran WP's MySQL query in my database and saw the postmeta table joined twice. The posts that have no tdlrm\_mp\_{term} meta key still have some other meta key in the resulting table and the rest of the posts get ordered by the value of that meta. (`mp_exists` adds the first postmeta table, `mp_not_exists` adds the second one, where `mp_exists` does not exist. Still some other meta key exists in the first joined table, so the posts keep getting ordered by that column).
    WordPress fires the [updated\_{$meta\_type}\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook.
    396,039
    <p>I try tu run wp form with ajax but console return Wordpress admin-ajax.php 400 bad request.</p> <pre><code> jQuery(function ($) { $(document).ready(function () { jQuery('#form_add_to_cart').on('submit', function () { jQuery.ajax({ url: 'https://domain.com/wp-admin/admin-ajax.php', method: 'post', contentType : 'application/json; charset=utf-8', data: $(&quot;#form_add_to_cart&quot;).serializeArray(), success: function (response) { alert(response); }, fail: function (err) { alert(&quot;There was an error: &quot; + err); } }); return false; }); }); }); </code></pre> <p>here is my functions.php file:</p> <pre><code>add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users add_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users. function send_form(){ if (isset($_POST['send_form'])){ echo'ok'; } else{ echo 'bad'; } } </code></pre> <p>and my form:</p> <pre><code> &lt;form name=&quot;form_add_to_cart&quot; method=&quot;POST&quot; class=&quot;form_product&quot; id=&quot;form_add_to_cart&quot; action=&quot;&quot;&gt; &lt;input hidden=&quot;hidden&quot; name=&quot;action&quot; id=&quot;add_product_to_cart&quot; value=&quot;send_form&quot;&gt; &lt;input class=&quot;btn btn-primary&quot; type=&quot;submit&quot; name=&quot;add_to_cart-&lt;?php echo $product_id; ?&gt;&quot; id=&quot;add_to_cart&quot; value=&quot;Dodaj&quot;&gt; </code></pre> <p>all form : <a href="https://pastebin.com/YJXTjGjJ" rel="nofollow noreferrer">https://pastebin.com/YJXTjGjJ</a></p> <p>WORKING:</p> <pre><code>jQuery(function ($) { $(document).ready(function () { jQuery('#form_add_to_cart').on('submit', function () { jQuery.ajax({ url: 'https://domain.com/wp-admin/admin-ajax.php', method: 'post', data: $(&quot;#form_add_to_cart&quot;).serializeArray(), success: function (response) { alert(response); }, fail: function (err) { alert(&quot;There was an error: &quot; + err); } }); return false; }); }); }); </code></pre>
    [ { "answer_id": 396045, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 0, "selected": false, "text": "<p>It really depends on when <code>_yoast_wpseo_focuskw</code> is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around <code>WPSEO_Meta::set_value()</code> <a href=\"https://github.com/Yoast/wordpress-seo/blob/1e151dbd01c1f1484a5713223acbb69801c8174f/inc/class-wpseo-meta.php#L692\" rel=\"nofollow noreferrer\">#</a>, can backtrace from there.</p>\n<p>Then adapt your code to that, queuing whatever you're doing <em>after</em> the new value has been written.</p>\n" }, { "answer_id": 396050, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 3, "selected": true, "text": "<p>WordPress fires the <a href=\"https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/\" rel=\"nofollow noreferrer\">updated_{$meta_type}_meta</a> hook which fires after the metadata is updated. In your case, the hook would be <code>updated_post_meta</code> and you could have your function run on that hook instead of the <code>save_post</code> hook.</p>\n" } ]
    2021/09/23
    [ "https://wordpress.stackexchange.com/questions/396039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212803/" ]
    I try tu run wp form with ajax but console return Wordpress admin-ajax.php 400 bad request. ``` jQuery(function ($) { $(document).ready(function () { jQuery('#form_add_to_cart').on('submit', function () { jQuery.ajax({ url: 'https://domain.com/wp-admin/admin-ajax.php', method: 'post', contentType : 'application/json; charset=utf-8', data: $("#form_add_to_cart").serializeArray(), success: function (response) { alert(response); }, fail: function (err) { alert("There was an error: " + err); } }); return false; }); }); }); ``` here is my functions.php file: ``` add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users add_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users. function send_form(){ if (isset($_POST['send_form'])){ echo'ok'; } else{ echo 'bad'; } } ``` and my form: ``` <form name="form_add_to_cart" method="POST" class="form_product" id="form_add_to_cart" action=""> <input hidden="hidden" name="action" id="add_product_to_cart" value="send_form"> <input class="btn btn-primary" type="submit" name="add_to_cart-<?php echo $product_id; ?>" id="add_to_cart" value="Dodaj"> ``` all form : <https://pastebin.com/YJXTjGjJ> WORKING: ``` jQuery(function ($) { $(document).ready(function () { jQuery('#form_add_to_cart').on('submit', function () { jQuery.ajax({ url: 'https://domain.com/wp-admin/admin-ajax.php', method: 'post', data: $("#form_add_to_cart").serializeArray(), success: function (response) { alert(response); }, fail: function (err) { alert("There was an error: " + err); } }); return false; }); }); }); ```
    WordPress fires the [updated\_{$meta\_type}\_meta](https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/) hook which fires after the metadata is updated. In your case, the hook would be `updated_post_meta` and you could have your function run on that hook instead of the `save_post` hook.
    396,105
    <p>I would like to use the rest API to take a username and a password sent in a request and use it in wp_authenticate() then send back if the credentials were correct. How would I do this.</p>
    [ { "answer_id": 396119, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 1, "selected": false, "text": "<p>There are 3 ways to authenticate a user using a REST api end-point request,</p>\n<p>1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the <code>wp_signon()</code> <a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">function</a> to sign-in your user, and if successful you set the authentication cookie using wp_set_auth_cookie() <a href=\"https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/\" rel=\"nofollow noreferrer\">function</a>,</p>\n<pre><code>$creds = array(\n 'user_login' =&gt; 'example',\n 'user_password' =&gt; 'plaintextpw',\n 'remember' =&gt; true\n);\n\n$user = wp_signon( $creds, false );\n\nif ( is_wp_error( $user ) ) {\n $msg = $user-&gt;get_error_message();\n}else{\n wp_clear_auth_cookie();\n wp_set_current_user ( $user-&gt;ID ); // Set the current user detail\n wp_set_auth_cookie ( $user-&gt;ID ); // Set auth details in cookie\n $msg = &quot;Logged in successfully&quot;; \n}\n</code></pre>\n<p>You can find a discussion on this WordPress forum <a href=\"https://wordpress.org/support/topic/login-a-wp-user-via-rest-api/\" rel=\"nofollow noreferrer\">thread</a>.</p>\n<p>2- Using Basic Authentication requests to your own server</p>\n<p>the idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">plugin</a> on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server,</p>\n<pre><code>let user='...', pw='...';\njQuery.ajax({\n url: 'http://your-domain/wp-json/wp/v2/posts/50',\n method: 'DELETE',\n crossDomain: true,\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) );\n },\n success: function( data, txtStatus, xhr ) {\n console.log( data );\n console.log( xhr.status );\n }\n});\n</code></pre>\n<p>For more details see this detailed <a href=\"https://www.cloudways.com/blog/setup-basic-authentication-in-wordpress-rest-api/#Send-Authenticated-Requests-Using-JavaScript\" rel=\"nofollow noreferrer\">tutorial</a></p>\n<p>3- using a third party authentication such the open <a href=\"https://en.wikipedia.org/wiki/OAuth\" rel=\"nofollow noreferrer\">OAuth</a>.</p>\n<p>This is what Google uses, and allows your site to identify users based on their Google login credentials. <a href=\"https://developer.wordpress.com/docs/oauth2/\" rel=\"nofollow noreferrer\">WordPress.com</a> also uses this method for its blog service authentication.</p>\n<p>The idea is that your users logs-in a server which identifies them (using cookies on their browser).</p>\n<p>Once authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward.</p>\n<p>You could use a third party authentication service, such Google, in which case you can follow this youtube <a href=\"https://www.youtube.com/watch?v=0UcayuC_Ay8\" rel=\"nofollow noreferrer\">tutorial</a> which walks you through the basics to setting up a Google API project to allow your application to make authentication requests.</p>\n<p>Alternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as <a href=\"https://wordpress.org/plugins/oauth2-provider/\" rel=\"nofollow noreferrer\">WP-OAuth Server</a>, and its extensive <a href=\"https://wp-oauth.com/docs/general/main-concepts/\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n" }, { "answer_id": 396120, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The best way to &quot;login&quot; a user on a site is to use the wordpress login form. As other comments and answers suggest, to do it in the way the title of the question implies requires some reinvention of the wheel. The login form in addition to doing the actual login also provides feedback when the login fails and provides a flow to reset the password.</p>\n<p>Even if you are going for a fully &quot;headless&quot; wordpress experiance you probably should be 100% sure the effort of reinventing the login form is worth it.</p>\n<p>Now if you mean to authenticate user from a different domain it is just not going to work as cookies will be set only on the site's domain IIRC.</p>\n<p>So the only valid use case is server to server communication in which you need to store the cookies you recieve from your &quot;login&quot; request and reuse them in the next requests, but this implies you store the user and password on your server in which case using <a href=\"https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/\" rel=\"nofollow noreferrer\">application passwords</a> might actually be a better solution.</p>\n" } ]
    2021/09/24
    [ "https://wordpress.stackexchange.com/questions/396105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212716/" ]
    I would like to use the rest API to take a username and a password sent in a request and use it in wp\_authenticate() then send back if the credentials were correct. How would I do this.
    There are 3 ways to authenticate a user using a REST api end-point request, 1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the `wp_signon()` [function](https://developer.wordpress.org/reference/functions/wp_signon/) to sign-in your user, and if successful you set the authentication cookie using wp\_set\_auth\_cookie() [function](https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/), ``` $creds = array( 'user_login' => 'example', 'user_password' => 'plaintextpw', 'remember' => true ); $user = wp_signon( $creds, false ); if ( is_wp_error( $user ) ) { $msg = $user->get_error_message(); }else{ wp_clear_auth_cookie(); wp_set_current_user ( $user->ID ); // Set the current user detail wp_set_auth_cookie ( $user->ID ); // Set auth details in cookie $msg = "Logged in successfully"; } ``` You can find a discussion on this WordPress forum [thread](https://wordpress.org/support/topic/login-a-wp-user-via-rest-api/). 2- Using Basic Authentication requests to your own server the idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a [plugin](https://github.com/WP-API/Basic-Auth) on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server, ``` let user='...', pw='...'; jQuery.ajax({ url: 'http://your-domain/wp-json/wp/v2/posts/50', method: 'DELETE', crossDomain: true, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) ); }, success: function( data, txtStatus, xhr ) { console.log( data ); console.log( xhr.status ); } }); ``` For more details see this detailed [tutorial](https://www.cloudways.com/blog/setup-basic-authentication-in-wordpress-rest-api/#Send-Authenticated-Requests-Using-JavaScript) 3- using a third party authentication such the open [OAuth](https://en.wikipedia.org/wiki/OAuth). This is what Google uses, and allows your site to identify users based on their Google login credentials. [WordPress.com](https://developer.wordpress.com/docs/oauth2/) also uses this method for its blog service authentication. The idea is that your users logs-in a server which identifies them (using cookies on their browser). Once authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward. You could use a third party authentication service, such Google, in which case you can follow this youtube [tutorial](https://www.youtube.com/watch?v=0UcayuC_Ay8) which walks you through the basics to setting up a Google API project to allow your application to make authentication requests. Alternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as [WP-OAuth Server](https://wordpress.org/plugins/oauth2-provider/), and its extensive [documentation](https://wp-oauth.com/docs/general/main-concepts/).
    396,171
    <p>How to display the number of articles published per user excluding users who do not publish articles. My message type is recipe. I would like to receive a code to get there in wp-query thank you very much for your help</p> <p>I give you a piece of code. Thanks to this code I am able to display the total number of recipes, but I would have liked to have this: User A posted 14 cooking recipes, User B posted 2 cooking recipes ect.. user member1 should have 2 recipes</p> <pre><code>&lt;?php // 1. We define the arguments to define what we want to recover $args = array ( 'post_type' =&gt; 'recipe', 'posts_per_page' =&gt; '16', ); // 2. We run the WP Query // The Query $the_query = new WP_Query ($args); // 3. we display the number of messages and the authors! // The Loop if ($the_query-&gt; have_posts ()) { echo count_user_posts (2, $args); echo 'recipes for'; echo get_the_author (2, $args); echo '&lt;br&gt;'; echo count_user_posts (1, $args); echo 'recipes for'; echo get_the_author (1, $args); // 3. We launch the loop to display the articles and the authors! // The Loop echo '&lt;ul&gt;'; while ($the_query-&gt; have_posts ()) ​{ $the_query-&gt; the_post (); echo '&lt;li&gt;'. get_the_title (). '&lt;li&gt;'; echo '&lt;li&gt;'. get_the_author (). '&lt;li&gt;'; ​} ​echo '&lt;ul&gt;'; ​} ​else { // no posts found } / * Restore original Post Data * / wp_reset_postdata (); ​?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/x40WN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x40WN.jpg" alt="enter image description here" /></a></p>
    [ { "answer_id": 396189, "author": "Joe", "author_id": 34273, "author_profile": "https://wordpress.stackexchange.com/users/34273", "pm_score": 1, "selected": true, "text": "<p>If you have access to user IDs, you can use the <a href=\"https://developer.wordpress.org/reference/functions/count_user_posts/\" rel=\"nofollow noreferrer\">count_user_posts()</a> function.</p>\n<p>You would get the number of posts by a user like this:</p>\n<pre><code>//Assume the variable $thisUser is equal to a valid user ID\n$ThisUserCount = count_user_posts($thisUser, 'recipe');\n</code></pre>\n<p>EDIT:\nWhere you're calling the count_user_posts() function, you're passing it the array $args instead of the post type, 'recipe'.</p>\n<pre><code>&lt;?php\n// 1. We define the arguments to define what we want to recover\n$args = array (\n 'post_type' =&gt; 'recipe',\n 'posts_per_page' =&gt; '16',\n);\n\n// 2. We run the WP Query\n// The Query\n$the_query = new WP_Query ($args);\n\n// 3. we display the number of messages and the authors!\n// The Loop\nif ($the_query-&gt; have_posts()) {\n //Set arguments to grab all authors with published recipes, and order them by user ID\n $authorArgs = array(\n 'orderby' =&gt; 'ID',\n 'has_published_posts' =&gt; array('recipe'),\n );\n\n //Create an array of all authors with recipes published\n $recipeAuthors = get_users($authorArgs);\n\n //Loop through each recipe author\n foreach($recipeAuthors as $user){\n //Output user post count for recipes\n echo count_user_posts($user-&gt;ID, 'recipe');\n echo ' recipes for ';\n\n //Output user's display name\n echo $user-&gt;display_name;\n echo '&lt;br /&gt;';\n }\n\n // 3. We launch the loop to display the articles and the authors!\n // The Loop\n echo '&lt;ul&gt;';\n while ($the_query-&gt; have_posts()) {\n $the_query-&gt; the_post();\n echo '&lt;li&gt;'. get_the_title(). '&lt;/li&gt;';\n echo '&lt;li&gt;'. get_the_author(). '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n} else {\n // no posts found\n}\nwp_reset_postdata ();​?&gt;\n</code></pre>\n<p>Also, your get_the_author(2,$args) function calls are not correct. get_the_author() does not accept any parameters anymore, and it only returns the Display Name of the author of the current post in the Loop.</p>\n" }, { "answer_id": 396205, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 1, "selected": false, "text": "<p>If you're just looking to display authors who have posted at least one article in your custom post type you can ignore the above code and just do this:</p>\n<pre><code>// Array of WP_User objects.\n$authors = get_users();\n\n// Loop thru the array and get the post count for each user\nforeach ( $authors as $author ) {\n $posts = count_user_posts($author-&gt;ID, 'movies');\n\n // Only return users who have at least one post \n if ($posts &gt; 0):\n echo '&lt;p&gt;&lt;span&gt;' . esc_html( $author-&gt;display_name ) . ': ' . $posts . '&lt;/span&gt;';\n endif; \n}\n\n// Only Necessary if you're running another loop or query on the page\nwp_reset_postdata ();​\n</code></pre>\n<p>Good luck!</p>\n" } ]
    2021/09/27
    [ "https://wordpress.stackexchange.com/questions/396171", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212622/" ]
    How to display the number of articles published per user excluding users who do not publish articles. My message type is recipe. I would like to receive a code to get there in wp-query thank you very much for your help I give you a piece of code. Thanks to this code I am able to display the total number of recipes, but I would have liked to have this: User A posted 14 cooking recipes, User B posted 2 cooking recipes ect.. user member1 should have 2 recipes ``` <?php // 1. We define the arguments to define what we want to recover $args = array ( 'post_type' => 'recipe', 'posts_per_page' => '16', ); // 2. We run the WP Query // The Query $the_query = new WP_Query ($args); // 3. we display the number of messages and the authors! // The Loop if ($the_query-> have_posts ()) { echo count_user_posts (2, $args); echo 'recipes for'; echo get_the_author (2, $args); echo '<br>'; echo count_user_posts (1, $args); echo 'recipes for'; echo get_the_author (1, $args); // 3. We launch the loop to display the articles and the authors! // The Loop echo '<ul>'; while ($the_query-> have_posts ()) ​{ $the_query-> the_post (); echo '<li>'. get_the_title (). '<li>'; echo '<li>'. get_the_author (). '<li>'; ​} ​echo '<ul>'; ​} ​else { // no posts found } / * Restore original Post Data * / wp_reset_postdata (); ​?> ``` [![enter image description here](https://i.stack.imgur.com/x40WN.jpg)](https://i.stack.imgur.com/x40WN.jpg)
    If you have access to user IDs, you can use the [count\_user\_posts()](https://developer.wordpress.org/reference/functions/count_user_posts/) function. You would get the number of posts by a user like this: ``` //Assume the variable $thisUser is equal to a valid user ID $ThisUserCount = count_user_posts($thisUser, 'recipe'); ``` EDIT: Where you're calling the count\_user\_posts() function, you're passing it the array $args instead of the post type, 'recipe'. ``` <?php // 1. We define the arguments to define what we want to recover $args = array ( 'post_type' => 'recipe', 'posts_per_page' => '16', ); // 2. We run the WP Query // The Query $the_query = new WP_Query ($args); // 3. we display the number of messages and the authors! // The Loop if ($the_query-> have_posts()) { //Set arguments to grab all authors with published recipes, and order them by user ID $authorArgs = array( 'orderby' => 'ID', 'has_published_posts' => array('recipe'), ); //Create an array of all authors with recipes published $recipeAuthors = get_users($authorArgs); //Loop through each recipe author foreach($recipeAuthors as $user){ //Output user post count for recipes echo count_user_posts($user->ID, 'recipe'); echo ' recipes for '; //Output user's display name echo $user->display_name; echo '<br />'; } // 3. We launch the loop to display the articles and the authors! // The Loop echo '<ul>'; while ($the_query-> have_posts()) { $the_query-> the_post(); echo '<li>'. get_the_title(). '</li>'; echo '<li>'. get_the_author(). '</li>'; } echo '</ul>'; } else { // no posts found } wp_reset_postdata ();​?> ``` Also, your get\_the\_author(2,$args) function calls are not correct. get\_the\_author() does not accept any parameters anymore, and it only returns the Display Name of the author of the current post in the Loop.
    396,277
    <p>I am trying to use a tax query in my <code>pre_get_posts</code> function. All is working but not when the array has multiple IDs. Let's say my URL looks like: ?listing_cat[]=1&amp;listing_cat[]=2</p> <p>Now I am trying to filter out posts that are in those 2 categories. But my filter only gets the posts from the first category ID. I guess I will need a foreach function, but I am not sure how to implement this. Currently I have the code below. Now I know I can use filter by multiple terms with a comma, like : <code>'terms' =&gt; array($rt_cat_id[0], $rt_cat_id[1])</code>, but I just need it to automatically get all the terms from the array <code>$rt_cat_id</code> and use those to filter the posts. How to accomplish that? Thanks</p> <pre><code>add_action( 'pre_get_posts', 'rt_tax_archive' ); function rt_tax_archive($query) { $rt_cat_id = $_GET['listing_cat']; if( isset( $rt_cat_id ) &amp;&amp; ! empty( $rt_cat_id[0] ) ) { $tax_query[] = array( 'taxonomy' =&gt; 'listing_category', 'field' =&gt; 'id', 'terms' =&gt; array($rt_cat_id[0]), ); } } </code></pre>
    [ { "answer_id": 396314, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 2, "selected": true, "text": "<p>Just use:</p>\n<p><code>'terms' =&gt; $rt_cat_id</code></p>\n<p>I'll work for both array and single-based values.</p>\n<p>Or you can simplify your code as follows:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if( isset( $_GET[ 'listing_cat' ] ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'listing_category',\n 'field' =&gt; 'id',\n 'terms' =&gt; $_GET[ 'listing_cat' ]\n );\n}\n</code></pre>\n" }, { "answer_id": 396316, "author": "RobbTe", "author_id": 124244, "author_profile": "https://wordpress.stackexchange.com/users/124244", "pm_score": 0, "selected": false, "text": "<p>So, the working code can be found below:</p>\n<pre><code>add_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) &amp;&amp; ! empty( $rt_cat_id[0] ) ) {\n $tax_query[] = array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'listing_category',\n 'field' =&gt; 'id',\n 'terms' =&gt; $rt_cat_id,\n ),\n );\n } \n\n\n}\n</code></pre>\n" } ]
    2021/09/29
    [ "https://wordpress.stackexchange.com/questions/396277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124244/" ]
    I am trying to use a tax query in my `pre_get_posts` function. All is working but not when the array has multiple IDs. Let's say my URL looks like: ?listing\_cat[]=1&listing\_cat[]=2 Now I am trying to filter out posts that are in those 2 categories. But my filter only gets the posts from the first category ID. I guess I will need a foreach function, but I am not sure how to implement this. Currently I have the code below. Now I know I can use filter by multiple terms with a comma, like : `'terms' => array($rt_cat_id[0], $rt_cat_id[1])`, but I just need it to automatically get all the terms from the array `$rt_cat_id` and use those to filter the posts. How to accomplish that? Thanks ``` add_action( 'pre_get_posts', 'rt_tax_archive' ); function rt_tax_archive($query) { $rt_cat_id = $_GET['listing_cat']; if( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) { $tax_query[] = array( 'taxonomy' => 'listing_category', 'field' => 'id', 'terms' => array($rt_cat_id[0]), ); } } ```
    Just use: `'terms' => $rt_cat_id` I'll work for both array and single-based values. Or you can simplify your code as follows: ```php if( isset( $_GET[ 'listing_cat' ] ) ) { $tax_query[] = array( 'taxonomy' => 'listing_category', 'field' => 'id', 'terms' => $_GET[ 'listing_cat' ] ); } ```
    396,282
    <p>My website has a few .PNG images animated at the very start of my Contact page. Those images are a bit heavy (because they have transparent background), so the animation starts with some of them loading during the animation, looking pretty bad.</p> <p>So, to fix it, I must add this line <code>&lt;link rel=&quot;preload&quot; as=&quot;image&quot; href=&quot;url-of-the-image.png&quot;/&gt;</code> to the <code>&lt;head&gt;</code>.</p> <p>To achieve it, I'm using <strong>Snippets plugin</strong>. If I'm not mistaken, the snippet should like this:</p> <pre><code>add_action( 'wp_head', function () { ?&gt; function my_custom_js() { echo '&lt;link rel=&quot;preload&quot; as=&quot;image&quot; href=href=&quot;url-of-the-image.png&quot;/&gt;'; } &lt;?php } ); </code></pre> <p>The thing is that the very same page (my Contact page) is different for mobile devices: it doesn't use those .PNG images because it would be too much loading time for a phone.</p> <p>This leads to my question: <strong>Is there a way to exclude mobile devices from the preloading tag I must add to the head?</strong></p>
    [ { "answer_id": 396314, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 2, "selected": true, "text": "<p>Just use:</p>\n<p><code>'terms' =&gt; $rt_cat_id</code></p>\n<p>I'll work for both array and single-based values.</p>\n<p>Or you can simplify your code as follows:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if( isset( $_GET[ 'listing_cat' ] ) ) {\n $tax_query[] = array(\n 'taxonomy' =&gt; 'listing_category',\n 'field' =&gt; 'id',\n 'terms' =&gt; $_GET[ 'listing_cat' ]\n );\n}\n</code></pre>\n" }, { "answer_id": 396316, "author": "RobbTe", "author_id": 124244, "author_profile": "https://wordpress.stackexchange.com/users/124244", "pm_score": 0, "selected": false, "text": "<p>So, the working code can be found below:</p>\n<pre><code>add_action( 'pre_get_posts', 'rt_tax_archive' );\nfunction rt_tax_archive($query) {\n$rt_cat_id = $_GET['listing_cat'];\n\nif( isset( $rt_cat_id ) &amp;&amp; ! empty( $rt_cat_id[0] ) ) {\n $tax_query[] = array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'listing_category',\n 'field' =&gt; 'id',\n 'terms' =&gt; $rt_cat_id,\n ),\n );\n } \n\n\n}\n</code></pre>\n" } ]
    2021/09/29
    [ "https://wordpress.stackexchange.com/questions/396282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203472/" ]
    My website has a few .PNG images animated at the very start of my Contact page. Those images are a bit heavy (because they have transparent background), so the animation starts with some of them loading during the animation, looking pretty bad. So, to fix it, I must add this line `<link rel="preload" as="image" href="url-of-the-image.png"/>` to the `<head>`. To achieve it, I'm using **Snippets plugin**. If I'm not mistaken, the snippet should like this: ``` add_action( 'wp_head', function () { ?> function my_custom_js() { echo '<link rel="preload" as="image" href=href="url-of-the-image.png"/>'; } <?php } ); ``` The thing is that the very same page (my Contact page) is different for mobile devices: it doesn't use those .PNG images because it would be too much loading time for a phone. This leads to my question: **Is there a way to exclude mobile devices from the preloading tag I must add to the head?**
    Just use: `'terms' => $rt_cat_id` I'll work for both array and single-based values. Or you can simplify your code as follows: ```php if( isset( $_GET[ 'listing_cat' ] ) ) { $tax_query[] = array( 'taxonomy' => 'listing_category', 'field' => 'id', 'terms' => $_GET[ 'listing_cat' ] ); } ```
    396,286
    <p>Is it possible to show ONLY the first 300 words (or even 50 lines) of every blog post for anonymous users? Instead of show the whole article on the page? And after registration all the post would show.</p> <p>Thanks!!!</p>
    [ { "answer_id": 396293, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 1, "selected": false, "text": "<p>It wasn't quite as easy as @Pat J made it sound, especially if you want <code>HTML</code> formatting with your copy. I cribbed from <a href=\"https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words\">this answer</a> and came up with the following code for you. I've tested it and it works:</p>\n<pre><code> // If the user is logged in, display the full content\n if(is_user_logged_in()):\n the_content();\n else: // The user isn't logged in and should only see the first 300 words\n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n endif;\n</code></pre>\n<p><strong>UPDATE</strong></p>\n<p>There are 2 errors in your code. One is the <code>;</code> after the initial <code>if</code> statement, and the <code>arrays</code> don't match: <code>$roles</code> v <code>$role</code>.</p>\n<p>The following code integrates the original answer (logged in/out) with your modifications (if is array):</p>\n<pre><code> if(is_user_logged_in()): \n if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): \n the_content();\n else: \n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) );\n endif; \n else:\n echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) );\n endif;\n</code></pre>\n<p>Good luck!</p>\n" }, { "answer_id": 396509, "author": "Alexandro Giles", "author_id": 206371, "author_profile": "https://wordpress.stackexchange.com/users/206371", "pm_score": 0, "selected": false, "text": "<p>You can use the excerpt to accomplish this, nonetheless the excerpt by default filter all HTML tags. To fix this, we need to filter and add new logic to it.</p>\n<p>This will work filteryng the excerpt to change according to your needs:</p>\n<p>You have to add this function in your theme's <strong>functions.php</strong></p>\n<p><strong>functions.php</strong></p>\n<pre><code>function wpse_allowedtags() {\n //The Tags you put here will not be removed, therefore if you want to include strong HTML tag, you should add it here as shown:\n return '&lt;strong&gt;'; \n }\n\nif ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) : \n\n function wpse_custom_wp_trim_excerpt($wpse_excerpt) {\n $raw_excerpt = $wpse_excerpt;\n if ( '' == $wpse_excerpt ) {\n\n $wpse_excerpt = get_the_content('');\n $wpse_excerpt = strip_shortcodes( $wpse_excerpt );\n $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);\n $wpse_excerpt = str_replace(']]&gt;', ']]&amp;gt;', $wpse_excerpt);\n $wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */\n\n /*Set the excerpt word count and only break after sentence is complete.\n You can set this to any number you want in this case we'll use 300 \n words. */\n $excerpt_word_count = 300;\n $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); \n $tokens = array();\n $excerptOutput = '';\n $count = 0;\n\n // Divide the string into tokens; HTML tags, or words, followed by any whitespace in order to clean the not allowed HTML tags.\n preg_match_all('/(&lt;[^&gt;]+&gt;|[^&lt;&gt;\\s]+)\\s*/u', $wpse_excerpt, $tokens);\n\n foreach ($tokens[0] as $token) { \n\n if ($count &gt;= $excerpt_length &amp;&amp; preg_match('/[\\,\\;\\?\\.\\!]\\s*$/uS', $token)) { \n // Limit reached, continue until , ; ? . or ! occur at the end\n $excerptOutput .= trim($token);\n break;\n }\n\n // Add words to complete sentence\n $count++;\n\n // Append what's left of the token\n $excerptOutput .= $token;\n }\n\n $wpse_excerpt = trim(force_balance_tags($excerptOutput));\n\n if ( $count &lt; 0) { \n $excerpt_end = ' &lt;a href=&quot;'. esc_url( get_permalink() ) . '&quot;&gt;' . '&amp;nbsp;&amp;raquo;&amp;nbsp;' . sprintf(__( 'Reed more: %s &amp;nbsp;&amp;raquo;', 'wpse' ), get_the_title()) . '&lt;/a&gt;'; \n $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); \n $wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */\n } \n $wpse_excerpt .= ' [...]';\n\n return $wpse_excerpt; \n\n }\n return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);\n }\n\nendif; \n\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt'); \n</code></pre>\n<p>After that, you only need to call the_excerpt to non registered users in the desired template file of your theme:\n(remember that it has been previously filtered to include 300 words)</p>\n<pre><code> // The user is logged in, display the full content\n if(is_user_logged_in()){\n the_content();\n }else{\n // show the_excerpt\n &lt;?php echo get_the_excerpt() ?&gt;\n }\n \n</code></pre>\n" } ]
    2021/09/29
    [ "https://wordpress.stackexchange.com/questions/396286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213060/" ]
    Is it possible to show ONLY the first 300 words (or even 50 lines) of every blog post for anonymous users? Instead of show the whole article on the page? And after registration all the post would show. Thanks!!!
    It wasn't quite as easy as @Pat J made it sound, especially if you want `HTML` formatting with your copy. I cribbed from [this answer](https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words) and came up with the following code for you. I've tested it and it works: ``` // If the user is logged in, display the full content if(is_user_logged_in()): the_content(); else: // The user isn't logged in and should only see the first 300 words echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) ); endif; ``` **UPDATE** There are 2 errors in your code. One is the `;` after the initial `if` statement, and the `arrays` don't match: `$roles` v `$role`. The following code integrates the original answer (logged in/out) with your modifications (if is array): ``` if(is_user_logged_in()): if( in_array( 'administrator', $roles ) || in_array( 'pmpro_role_2', $roles ) || in_array( 'pmpro_role_1', $roles )): the_content(); else: echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 300, '...' ) ) ); endif; else: echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 100, '...' ) ) ); endif; ``` Good luck!
    396,304
    <p>At the moment I'm using Postman to hit the endpoints and I have a successful Basic Authentication but so far I'm unable to get all the registered users. My request:</p> <pre><code>https://example.com/wp-json/wp/v2/users </code></pre> <p>returns only users that have posts even though I have inserted:</p> <pre><code>add_filter( 'rest_user_query' , 'custom_rest_user_query' ); function custom_rest_user_query( $prepared_args, $request = null ) { unset($prepared_args['has_published_posts']); return $prepared_args; } </code></pre> <p>in my functions file. I have also tried applying a filter:</p> <pre><code>https://example.com/wp-json/wp/v2/users?filter[per_page]=0 </code></pre> <p>But I still get the same result: Only users with posts. I have been banging my head on for days now...</p>
    [ { "answer_id": 396306, "author": "billybadass", "author_id": 194672, "author_profile": "https://wordpress.stackexchange.com/users/194672", "pm_score": 0, "selected": false, "text": "<p>WP has nice build in tools to work with db, my suggestion would be to register your endpoint and use for a callback function something like this:</p>\n<pre><code>function getAllUsers(){\n global $wpdb;\n $query = $wpdb-&gt;get_results( &quot; SELECT `ID` FROM `wp_users` &quot; , OBJECT);\n $ids = array();\n foreach($query as $id){\n array_push($ids, $id-&gt;ID);\n }\n return $ids; \n}\n</code></pre>\n<p>It will return all the ID's. Then you can use <code>get_post_meta</code> to gather meta info about the user. Of course consider protecting your endpoint since it hands over user information.</p>\n" }, { "answer_id": 396317, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p><strong>The problem may be pagination</strong></p>\n<p>The API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100.</p>\n<p>So your missing users may be on page 2 or 3 etc</p>\n<p>I strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination:</p>\n<p><a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/</a></p>\n" } ]
    2021/09/30
    [ "https://wordpress.stackexchange.com/questions/396304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213074/" ]
    At the moment I'm using Postman to hit the endpoints and I have a successful Basic Authentication but so far I'm unable to get all the registered users. My request: ``` https://example.com/wp-json/wp/v2/users ``` returns only users that have posts even though I have inserted: ``` add_filter( 'rest_user_query' , 'custom_rest_user_query' ); function custom_rest_user_query( $prepared_args, $request = null ) { unset($prepared_args['has_published_posts']); return $prepared_args; } ``` in my functions file. I have also tried applying a filter: ``` https://example.com/wp-json/wp/v2/users?filter[per_page]=0 ``` But I still get the same result: Only users with posts. I have been banging my head on for days now...
    **The problem may be pagination** The API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100. So your missing users may be on page 2 or 3 etc I strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination: <https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/>
    396,325
    <p>I tried hooking the <code>upload_mimes</code> hook in order to add support for ttf files to be uploaded, however this didn't immediately work (.ttf files were still blocked).</p> <p>The reason isn't entirely clear to me but I assume Wordpress's calculated MIME type for the file I'm trying to upload and the MIME type I'm adding to the <code>upload_files</code> hook don't match.</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/09/30
    [ "https://wordpress.stackexchange.com/questions/396325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176814/" ]
    I tried hooking the `upload_mimes` hook in order to add support for ttf files to be uploaded, however this didn't immediately work (.ttf files were still blocked). The reason isn't entirely clear to me but I assume Wordpress's calculated MIME type for the file I'm trying to upload and the MIME type I'm adding to the `upload_files` hook don't match.
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,337
    <p>How do I allow a specific user or a specific role to view drafts and previews, but not allow them to edit posts or have any other admin capabilities? I can add a custom capability to a role, but don't know the logic for allowing them to view drafts and previews. Any thoughts?</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/09/30
    [ "https://wordpress.stackexchange.com/questions/396337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42925/" ]
    How do I allow a specific user or a specific role to view drafts and previews, but not allow them to edit posts or have any other admin capabilities? I can add a custom capability to a role, but don't know the logic for allowing them to view drafts and previews. Any thoughts?
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,397
    <p>Very new to PHP and I'm trying to do the following through a snippets plugin but keep getting critical errors:</p> <ul> <li>Restrict all non-logged in users to home, about and pricing pages. If attempting to access other pages, redirect to &quot;no-permission&quot; message page.</li> <li>If user is logged in, allow them to only view posts on the front end if they are the post author. If attempted, redirect to &quot;no-permission&quot; page.</li> <li>Admin has full read access on front end.</li> </ul> <p>I've tried with plugins but nothing quite gives me what I want,</p> <p>Any help is much appreciated, code below:</p> <pre><code>add_action( 'template_redirect', 'redirect_non_permitted_users' ); function redirect_non_permitted_users () { $userID = get_user_id(); $authorID = get_the_author_meta(ID); if(current_user_can('manage_options')){ } elseif( $userID &lt;&gt; $authorID || ! is_user_logged_in() || ! is_front_page() || ! is_page('about') || ! is_page('pricing')){ wp_redirect('https://www.example.com/no-permission/'); exit; } } </code></pre>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/02
    [ "https://wordpress.stackexchange.com/questions/396397", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213142/" ]
    Very new to PHP and I'm trying to do the following through a snippets plugin but keep getting critical errors: * Restrict all non-logged in users to home, about and pricing pages. If attempting to access other pages, redirect to "no-permission" message page. * If user is logged in, allow them to only view posts on the front end if they are the post author. If attempted, redirect to "no-permission" page. * Admin has full read access on front end. I've tried with plugins but nothing quite gives me what I want, Any help is much appreciated, code below: ``` add_action( 'template_redirect', 'redirect_non_permitted_users' ); function redirect_non_permitted_users () { $userID = get_user_id(); $authorID = get_the_author_meta(ID); if(current_user_can('manage_options')){ } elseif( $userID <> $authorID || ! is_user_logged_in() || ! is_front_page() || ! is_page('about') || ! is_page('pricing')){ wp_redirect('https://www.example.com/no-permission/'); exit; } } ```
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,411
    <p>I am currently using the wp-members wordpress plugin. I just learned that they have no functionality to redirect the user to the last page viewed after login or registration .. which has a solution thank you</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/02
    [ "https://wordpress.stackexchange.com/questions/396411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212622/" ]
    I am currently using the wp-members wordpress plugin. I just learned that they have no functionality to redirect the user to the last page viewed after login or registration .. which has a solution thank you
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,416
    <p>I have a website with several custom fields, however when using the following code to search for a post, it only searches for the title or for the content, excluding the custom fields associated with the post or entry.</p> <pre><code>&lt;form method=&quot;get&quot; id=&quot;searchform&quot; action=&quot;&lt;?php bloginfo('url'); ?&gt;/&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;&lt;?php the_search_query(); ?&gt;&quot; name=&quot;s&quot; id=&quot;s&quot; placeholder=&quot;&lt;?php esc_attr_e( 'Buscar por título, actor, año...', 'twentyeleven' ); ?&gt;&quot; /&gt; &lt;input type=&quot;submit&quot; class=&quot;submit&quot; name=&quot;submit&quot; id=&quot;boton&quot; value=&quot;&quot; /&gt; &lt;/form&gt; </code></pre> <p>any way to include custom fields in the search?</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/03
    [ "https://wordpress.stackexchange.com/questions/396416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162329/" ]
    I have a website with several custom fields, however when using the following code to search for a post, it only searches for the title or for the content, excluding the custom fields associated with the post or entry. ``` <form method="get" id="searchform" action="<?php bloginfo('url'); ?>/"> <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" placeholder="<?php esc_attr_e( 'Buscar por título, actor, año...', 'twentyeleven' ); ?>" /> <input type="submit" class="submit" name="submit" id="boton" value="" /> </form> ``` any way to include custom fields in the search?
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,485
    <p>I am writing a custom (bespoke, for 1 client, not for publication and general consumption) plugin, that needs to access custom tables.</p> <p>In general with WP,I follow the principle of using the higher level APIs where possible, so rarely have to work with \wpdb. Now that i do have a need, i am discovering how archaic it is!</p> <p>Looking through the source code, it seems I can be sure that it is using mysqli (since the plugin requires php 7.1, and we also control the server) so I thought why not use that for my custom tables logic?</p> <p>I wrote a tiny wrapper:</p> <pre><code>&lt;?php namespace PluginNamespaceHere\DB; use mysqli; use wpdb; /** * A small wrapper class that contains, and provides direct access to, the $wpdb object, * as well as the underlying MYSQLI object, so we can do real prepared statements etc */ class DB { /** @var wpdb */ public $wpdb; /** @var mysqli */ public $mysqli; /** * @param wpdb $wpdb */ public function __construct(wpdb $wpdb) { $this-&gt;wpdb = $wpdb; //$wpdb is protected, but accessible via magic __get() wp-db.php line: 643 $this-&gt;mysqli = $wpdb-&gt;dbh; } /** * Run an SQL query. If $params are provided, prepared statements are used. If $bind_types are provided, they will be * used in the prepared statement, if not, all params will be treated as strings * * @param string $sql The SQL string, unprefixed table names should be wrapped in curly braces eg SELECT * FROM {posts} * @param array $params Optional parameters for prepared statements * @param string $bind_types Optional bind types for prepared statements, defaults to string * @retun bool|mysqli_result */ public function run($sql, $params=[], $bind_types='') { $sql = $this-&gt;prefixTableNamesInSqlString($sql); if(!is_array($params) || empty($params)){ return $this-&gt;mysqli-&gt;query($sql); } if($bind_types == ''){ $bind_types = str_repeat(&quot;s&quot;, count($params)); } $stmt = $this-&gt;mysqli-&gt;prepare($sql); $stmt-&gt;bind_param($bind_types, ...$params); $stmt-&gt;execute(); return $stmt-&gt;get_result(); } /** * Replaces curly brace table names with their actual, prefixed name * Eg &quot;SELECT * from {table_name}&quot; =&gt; &quot;SELECT * from wp_table_name&quot; * @param string $sql * @return string */ private function prefixTableNamesInSqlString($sql) { return str_replace([&quot;{&quot;, &quot;}&quot;], [$this-&gt;wpdb-&gt;prefix, &quot;&quot;], $sql); } } </code></pre> <p>This would allow me to use real prepared queries, and have nice readable code like:</p> <pre><code>&lt;?php $sql = &quot; SELECT DISTINCT c.ID AS course_id, c.post_title AS course_title FROM {posts} c JOIN {tmsc_course_product} cp ON c.id = cp.course_id WHERE cp.product_id IN(?,?) &quot;; //Yes, i know DB::run() can return bool! Out of scope for this question $courses = $db-&gt;run($sql, [57,4761])-&gt;fetch_all(MYSQLI_ASSOC); </code></pre> <p>My only concern is if this is going to have any knock on effects with wpdb and its dependents. The wpdb class is not exactly easy to read, and appears holds a lot of state.</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/05
    [ "https://wordpress.stackexchange.com/questions/396485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120700/" ]
    I am writing a custom (bespoke, for 1 client, not for publication and general consumption) plugin, that needs to access custom tables. In general with WP,I follow the principle of using the higher level APIs where possible, so rarely have to work with \wpdb. Now that i do have a need, i am discovering how archaic it is! Looking through the source code, it seems I can be sure that it is using mysqli (since the plugin requires php 7.1, and we also control the server) so I thought why not use that for my custom tables logic? I wrote a tiny wrapper: ``` <?php namespace PluginNamespaceHere\DB; use mysqli; use wpdb; /** * A small wrapper class that contains, and provides direct access to, the $wpdb object, * as well as the underlying MYSQLI object, so we can do real prepared statements etc */ class DB { /** @var wpdb */ public $wpdb; /** @var mysqli */ public $mysqli; /** * @param wpdb $wpdb */ public function __construct(wpdb $wpdb) { $this->wpdb = $wpdb; //$wpdb is protected, but accessible via magic __get() wp-db.php line: 643 $this->mysqli = $wpdb->dbh; } /** * Run an SQL query. If $params are provided, prepared statements are used. If $bind_types are provided, they will be * used in the prepared statement, if not, all params will be treated as strings * * @param string $sql The SQL string, unprefixed table names should be wrapped in curly braces eg SELECT * FROM {posts} * @param array $params Optional parameters for prepared statements * @param string $bind_types Optional bind types for prepared statements, defaults to string * @retun bool|mysqli_result */ public function run($sql, $params=[], $bind_types='') { $sql = $this->prefixTableNamesInSqlString($sql); if(!is_array($params) || empty($params)){ return $this->mysqli->query($sql); } if($bind_types == ''){ $bind_types = str_repeat("s", count($params)); } $stmt = $this->mysqli->prepare($sql); $stmt->bind_param($bind_types, ...$params); $stmt->execute(); return $stmt->get_result(); } /** * Replaces curly brace table names with their actual, prefixed name * Eg "SELECT * from {table_name}" => "SELECT * from wp_table_name" * @param string $sql * @return string */ private function prefixTableNamesInSqlString($sql) { return str_replace(["{", "}"], [$this->wpdb->prefix, ""], $sql); } } ``` This would allow me to use real prepared queries, and have nice readable code like: ``` <?php $sql = " SELECT DISTINCT c.ID AS course_id, c.post_title AS course_title FROM {posts} c JOIN {tmsc_course_product} cp ON c.id = cp.course_id WHERE cp.product_id IN(?,?) "; //Yes, i know DB::run() can return bool! Out of scope for this question $courses = $db->run($sql, [57,4761])->fetch_all(MYSQLI_ASSOC); ``` My only concern is if this is going to have any knock on effects with wpdb and its dependents. The wpdb class is not exactly easy to read, and appears holds a lot of state.
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,517
    <p>I am following the official WordPress &quot;Create a Block Tutorial&quot; located here: <a href="https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/</a></p> <p>I used this as a starting point for the plugin: <code>npx @wordpress/create-block</code></p> <p>I am using it in conjunction with Local by Flywheel for my dev environment. Mostly everything seems to be working except when I try to include other files in the block's CSS like a custom font file or an image. This is part of the tutorial: <a href="https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/block-code/" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/block-code/</a></p> <p>Example:</p> <pre><code>@font-face { font-family: Gilbert; src: url(./Gilbert-color.otf); font-weight: bold; } .wp-block-create-block-tdblocks { font-family: Gilbert; font-size: 64px; font-weight: bold; background-image: url(./map_bg.png); background-repeat: repeat; } </code></pre> <p>So after I insert the recommended code and run <code>npm run build</code>, the css file generated by the build process leaves the links to these files relative to the current web page's URL and not a link to its file location in the proper plugin folder.</p> <p>Here is what it gives me for the image file for instance (which shows as a 404 error naturally):</p> <pre><code>https://taylor-design-starter-theme.local/sample-page/images/map_bg.f0104819.png </code></pre> <p>I'd expect it to give me this:</p> <pre><code>https://taylor-design-starter-theme.local/wp-content/plugins/tdblocks/build/images/map_bg.f0104819.png </code></pre> <p>I have tried adjusting the &quot;url&quot; value in the scss file to see if that would help. Like <code>src: url(../map_bg.png);</code> or <code>src: url(map_bg.png);</code> and that didn't seem to do anything.</p> <p>Am I missing something? Or is there a way to get it to use the plugin directory?</p> <p>Thank you.</p> <p>EDIT: Here is the CSS generated by the build process when I run <code>npm run build</code></p> <pre><code>@font-face{font-family:Gilbert;font-weight:700;src:url(fonts/Gilbert-color.02d3d364.otf)}.wp-block-create-block-tdblocks{background-image:url(images/map_bg.f0104819.png);background-repeat:repeat;font-family:sans-serif;font-size:64px;font-weight:700} </code></pre>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/05
    [ "https://wordpress.stackexchange.com/questions/396517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213256/" ]
    I am following the official WordPress "Create a Block Tutorial" located here: <https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/> I used this as a starting point for the plugin: `npx @wordpress/create-block` I am using it in conjunction with Local by Flywheel for my dev environment. Mostly everything seems to be working except when I try to include other files in the block's CSS like a custom font file or an image. This is part of the tutorial: <https://developer.wordpress.org/block-editor/handbook/tutorials/create-block/block-code/> Example: ``` @font-face { font-family: Gilbert; src: url(./Gilbert-color.otf); font-weight: bold; } .wp-block-create-block-tdblocks { font-family: Gilbert; font-size: 64px; font-weight: bold; background-image: url(./map_bg.png); background-repeat: repeat; } ``` So after I insert the recommended code and run `npm run build`, the css file generated by the build process leaves the links to these files relative to the current web page's URL and not a link to its file location in the proper plugin folder. Here is what it gives me for the image file for instance (which shows as a 404 error naturally): ``` https://taylor-design-starter-theme.local/sample-page/images/map_bg.f0104819.png ``` I'd expect it to give me this: ``` https://taylor-design-starter-theme.local/wp-content/plugins/tdblocks/build/images/map_bg.f0104819.png ``` I have tried adjusting the "url" value in the scss file to see if that would help. Like `src: url(../map_bg.png);` or `src: url(map_bg.png);` and that didn't seem to do anything. Am I missing something? Or is there a way to get it to use the plugin directory? Thank you. EDIT: Here is the CSS generated by the build process when I run `npm run build` ``` @font-face{font-family:Gilbert;font-weight:700;src:url(fonts/Gilbert-color.02d3d364.otf)}.wp-block-create-block-tdblocks{background-image:url(images/map_bg.f0104819.png);background-repeat:repeat;font-family:sans-serif;font-size:64px;font-weight:700} ```
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,518
    <p>Is there a way to check which files are part of vanilla Wordpress? I am working on a custom Wordpress project that has a lot of added parts to it and I was wondering if there was an easy way to check which files were added.</p> <p>Inside of root there's a folder website.com, among other things, and inside website.com there's a folder called public, among other things, and then inside folder we have the folders wp-admin, wp-content and wp-includes. So I am wondering if every other folders are not part of the vanilla Wordpress. Also, what folders should vanilla Wordpress have inside wp-admin, wp-content and wp-includes and can other non-Wordpress files use files inside those folders?</p>
    [ { "answer_id": 396326, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension <em>and</em> then hooks <code>upload_mimes</code> for exactly our specified MIME type. Part of this answer taken from <a href=\"https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/\" rel=\"nofollow noreferrer\">https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/</a></p>\n<p>First massage the way Wordpress detects/reports TTF file types:</p>\n<pre><code>function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) {\n\nif ( ! empty( $data['ext'] ) &amp;&amp; ! empty( $data['type'] ) ) {\nreturn $data;\n}\n\n$wp_file_type = wp_check_filetype( $filename, $mimes );\n\n// Check for the file type you want to enable, e.g. 'svg'.\nif ( 'ttf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'ttf';\n$data['type'] = 'font/ttf';\n}\n\nif ( 'otf' === $wp_file_type['ext'] ) {\n$data['ext'] = 'otf';\n$data['type'] = 'font/otf';\n}\n\nreturn $data;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 );\n</code></pre>\n<p>Then hook <code>upload_mimes</code> for exactly this extension/mime-type:</p>\n<pre><code>\nfunction allow_custom_mime_types( $mimes ) {\n \n // New allowed mime types.\n $mimes['ttf'] = 'font/ttf'; \n\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'allow_custom_mime_types' );\n</code></pre>\n" }, { "answer_id": 396330, "author": "dig99", "author_id": 171719, "author_profile": "https://wordpress.stackexchange.com/users/171719", "pm_score": 1, "selected": false, "text": "<p>If you're not in production or i.e. working in development env you can use:</p>\n<p>define('ALLOW_UNFILTERED_UPLOADS', true);</p>\n<p>in wp-config.php</p>\n" } ]
    2021/10/05
    [ "https://wordpress.stackexchange.com/questions/396518", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212733/" ]
    Is there a way to check which files are part of vanilla Wordpress? I am working on a custom Wordpress project that has a lot of added parts to it and I was wondering if there was an easy way to check which files were added. Inside of root there's a folder website.com, among other things, and inside website.com there's a folder called public, among other things, and then inside folder we have the folders wp-admin, wp-content and wp-includes. So I am wondering if every other folders are not part of the vanilla Wordpress. Also, what folders should vanilla Wordpress have inside wp-admin, wp-content and wp-includes and can other non-Wordpress files use files inside those folders?
    This is an imperfect solution which forces the way Wordpress detects TTF files to use the file extension *and* then hooks `upload_mimes` for exactly our specified MIME type. Part of this answer taken from <https://diviengine.com/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/> First massage the way Wordpress detects/reports TTF file types: ``` function divi_engine_font_correct_filetypes( $data, $file, $filename, $mimes, $real_mime ) { if ( ! empty( $data['ext'] ) && ! empty( $data['type'] ) ) { return $data; } $wp_file_type = wp_check_filetype( $filename, $mimes ); // Check for the file type you want to enable, e.g. 'svg'. if ( 'ttf' === $wp_file_type['ext'] ) { $data['ext'] = 'ttf'; $data['type'] = 'font/ttf'; } if ( 'otf' === $wp_file_type['ext'] ) { $data['ext'] = 'otf'; $data['type'] = 'font/otf'; } return $data; } add_filter( 'wp_check_filetype_and_ext', 'divi_engine_font_correct_filetypes', 10, 5 ); ``` Then hook `upload_mimes` for exactly this extension/mime-type: ``` function allow_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['ttf'] = 'font/ttf'; return $mimes; } add_filter( 'upload_mimes', 'allow_custom_mime_types' ); ```
    396,540
    <p>On button click, I want user to download a file which is an apk file. On that same click, at the same time, I want to scroll to a div.</p> <p>Is it possible to add two actions in a button? Note: I'm using elementor.</p>
    [ { "answer_id": 396543, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 0, "selected": false, "text": "<p>Try this code</p>\n<pre><code>$('.download-btn').click(function(){\n $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n</code></pre>\n" }, { "answer_id": 396574, "author": "Sean Sr", "author_id": 206158, "author_profile": "https://wordpress.stackexchange.com/users/206158", "pm_score": 2, "selected": false, "text": "<p>Demo: <a href=\"https://codepen.io/livehelp/pen/MWoNPqX?editors=1010\" rel=\"nofollow noreferrer\">https://codepen.io/livehelp/pen/MWoNPqX?editors=1010</a></p>\n<p>Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.</p>\n<pre><code>&lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n e.preventDefault();\n const href = this.getAttribute(&quot;href&quot;);\n const offsetTop = document.querySelector(href).offsetTop;\n\n scroll({\n top: offsetTop,\n behavior: &quot;smooth&quot;\n });\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/10/06
    [ "https://wordpress.stackexchange.com/questions/396540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182718/" ]
    On button click, I want user to download a file which is an apk file. On that same click, at the same time, I want to scroll to a div. Is it possible to add two actions in a button? Note: I'm using elementor.
    Demo: <https://codepen.io/livehelp/pen/MWoNPqX?editors=1010> Just use an HTML or Code element in Elementor to paste in the code instead of a Button element. ``` <h2><a href="#smooth" onclick="window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')";>Click to Download + Smooth Scroll</a></h2> <p>Insert enough text here to have a scoll bar.</p> <div id="smooth"><h1>Tadaa! Jumps to this div based on the id #smooth onClick.<h1></div> <script> const links = document.querySelectorAll("a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } </script> ```
    396,542
    <pre><code>&lt;?php the_post_thumbnail( 'medium-thumbnail', array( 'loading' =&gt; false ), [ 'alt' =&gt; esc_html ( get_the_title() ) ] ); ?&gt; </code></pre> <p>Get Diagnostics info on pagespeed</p> <p>Largest Contentful Paint image was not lazily loaded</p> <p>what I wrong?</p>
    [ { "answer_id": 396543, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 0, "selected": false, "text": "<p>Try this code</p>\n<pre><code>$('.download-btn').click(function(){\n $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n</code></pre>\n" }, { "answer_id": 396574, "author": "Sean Sr", "author_id": 206158, "author_profile": "https://wordpress.stackexchange.com/users/206158", "pm_score": 2, "selected": false, "text": "<p>Demo: <a href=\"https://codepen.io/livehelp/pen/MWoNPqX?editors=1010\" rel=\"nofollow noreferrer\">https://codepen.io/livehelp/pen/MWoNPqX?editors=1010</a></p>\n<p>Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.</p>\n<pre><code>&lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n e.preventDefault();\n const href = this.getAttribute(&quot;href&quot;);\n const offsetTop = document.querySelector(href).offsetTop;\n\n scroll({\n top: offsetTop,\n behavior: &quot;smooth&quot;\n });\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/10/06
    [ "https://wordpress.stackexchange.com/questions/396542", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194551/" ]
    ``` <?php the_post_thumbnail( 'medium-thumbnail', array( 'loading' => false ), [ 'alt' => esc_html ( get_the_title() ) ] ); ?> ``` Get Diagnostics info on pagespeed Largest Contentful Paint image was not lazily loaded what I wrong?
    Demo: <https://codepen.io/livehelp/pen/MWoNPqX?editors=1010> Just use an HTML or Code element in Elementor to paste in the code instead of a Button element. ``` <h2><a href="#smooth" onclick="window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')";>Click to Download + Smooth Scroll</a></h2> <p>Insert enough text here to have a scoll bar.</p> <div id="smooth"><h1>Tadaa! Jumps to this div based on the id #smooth onClick.<h1></div> <script> const links = document.querySelectorAll("a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } </script> ```
    396,598
    <p>One of my sites is used as a personal diary with &gt;5000 videos uploaded within the media library.</p> <p>Each post uses the following shortcode, disabling pre-load and assigning a manual poster. This reduces server load and speed for the default preload='metadata', should the post contain lots of videos. The posters are manually uploaded.</p> <pre><code>[video preload=&quot;none&quot; mp4=&quot;/wp-content/Videos/001.mp4&quot; poster=&quot;/wp-content/Pictures/Posters/001.mp4.jpg&quot;][/video] </code></pre> <p>This works great for posts, however; should I view videos via their tags through the archive, it displays via the default settings as found in /wp-includes/media.php which uses the standard preload='metadata'.</p> <p>My question: &quot;Is there a way to set the default 'poster' to &quot;/wp-content/Pictures/Posters/<em>filename</em>.mp4.jpg&quot; So, taking the name of the video, prepending with &quot;/wp-content/Pictures/Posters/&quot; and then appending with &quot;.jpg&quot; ?</p> <p>Any help would be greatly appreciated.</p>
    [ { "answer_id": 396543, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 0, "selected": false, "text": "<p>Try this code</p>\n<pre><code>$('.download-btn').click(function(){\n $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n</code></pre>\n" }, { "answer_id": 396574, "author": "Sean Sr", "author_id": 206158, "author_profile": "https://wordpress.stackexchange.com/users/206158", "pm_score": 2, "selected": false, "text": "<p>Demo: <a href=\"https://codepen.io/livehelp/pen/MWoNPqX?editors=1010\" rel=\"nofollow noreferrer\">https://codepen.io/livehelp/pen/MWoNPqX?editors=1010</a></p>\n<p>Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.</p>\n<pre><code>&lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n e.preventDefault();\n const href = this.getAttribute(&quot;href&quot;);\n const offsetTop = document.querySelector(href).offsetTop;\n\n scroll({\n top: offsetTop,\n behavior: &quot;smooth&quot;\n });\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/10/07
    [ "https://wordpress.stackexchange.com/questions/396598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213345/" ]
    One of my sites is used as a personal diary with >5000 videos uploaded within the media library. Each post uses the following shortcode, disabling pre-load and assigning a manual poster. This reduces server load and speed for the default preload='metadata', should the post contain lots of videos. The posters are manually uploaded. ``` [video preload="none" mp4="/wp-content/Videos/001.mp4" poster="/wp-content/Pictures/Posters/001.mp4.jpg"][/video] ``` This works great for posts, however; should I view videos via their tags through the archive, it displays via the default settings as found in /wp-includes/media.php which uses the standard preload='metadata'. My question: "Is there a way to set the default 'poster' to "/wp-content/Pictures/Posters/*filename*.mp4.jpg" So, taking the name of the video, prepending with "/wp-content/Pictures/Posters/" and then appending with ".jpg" ? Any help would be greatly appreciated.
    Demo: <https://codepen.io/livehelp/pen/MWoNPqX?editors=1010> Just use an HTML or Code element in Elementor to paste in the code instead of a Button element. ``` <h2><a href="#smooth" onclick="window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')";>Click to Download + Smooth Scroll</a></h2> <p>Insert enough text here to have a scoll bar.</p> <div id="smooth"><h1>Tadaa! Jumps to this div based on the id #smooth onClick.<h1></div> <script> const links = document.querySelectorAll("a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } </script> ```
    396,661
    <br> <p><strong>Targets : Show Locations (sub-districts &amp; cities) on the customized shop page &amp; on tab additional information - Show on line 5</strong></p> <p>I'm building a property site using wordpress and woocommerce.</p> <p>In my country has 7 islands, 34 provinces, 514 Cities, 7041 Districts, 82194 Sub-districts.</p> <p>Then I grouped the data and added it to :</p> <p>On category</p> <ul> <li>Verified (parent)</li> <li>Sold (parent)</li> <li>Rent (parent)</li> <li>Island #1 (parent) <ul> <li>province #1 (child) <ul> <li>City #1(sub-child)<br></li> </ul> </li> </ul> </li> <li>Island #2 (parent) <ul> <li>province #2 (child) <ul> <li>City #2(sub-child)<br></li> </ul> </li> </ul> </li> <li>Island #7 (parent) <ul> <li>province #34 (child) <ul> <li>City #514(sub-child)<br></li> </ul> </li> </ul> </li> </ul> <p>and on product attribute :</p> <p>pa_area : city (514)</p> <p>pa_kecamatan : districts (7041)</p> <p>pa_lokasi : sub-districts (82194)</p> <p>So, I can customize the shop page as desired/needed and <a href="http://prnt.sc/1w2v1b6" rel="nofollow noreferrer">looks like this</a>.</p> <p>In the Additional Information tab, I also added the sub-district and the city <a href="http://prnt.sc/1w2w4tj" rel="nofollow noreferrer">looks like this</a>.</p> <p>I also display links using permalinks, for example:</p> <p>https://mydomain/product-categories/island1/provinces3/cities8 (categories)</p> <p>https://mydomain/product-categories/island5/provinces1/cities12 (categories)</p> <p>https://mydomain/districts1492 (pa_attributtes)</p> <p>https://mydomain/districts5630 (pa_attributtes)</p> <p>https://mydomain/subdistricts11596 (pa_attributtes)</p> <p>https://mydomain/subdistricts52630 (pa_attributtes)</p> <p>So far everything seems fine.</p> <hr> <p>My mind changed when I created a demo site (with current product counts at 10k.)</p> <p>Loading slowly on entering/selecting attributes is starting to feel.<br> (I know one of the causes is CPU, RAM/Hosting).</p> <p>This made me think whether display the city only in one place.<br> (eg city in category or city in product attribute) can help reduce server load?</p> <p>Please correct me if I misunderstood this.</p> <p>But if it's true, i using the first way is to delete the city in the category and save the city in the product attribute.</p> <p>However this will cut the scope, for example :</p> <p>Previously :</p> <p>https://mydomain/product-categories/island1/provinces3/cities8 (categories)</p> <p>https://mydomain/product-categories/island5/provinces1/cities12 (categories)</p> <p>will be :</p> <p>https://mydomain/product-categories/island1/provinces3/ (categories)</p> <p>https://mydomain/product-categories/island5/provinces1/ (categories)</p> <p>To keep showing the same thing, i can just edit the permalink to:</p> <p>https://mydomain/product-categories/island1/provinces3/&amp;cities8 (categories &amp; pa_area)</p> <p>https://mydomain/product-categories/island5/provinces1/&amp;cities12 (categories &amp; pa_area)</p> <p>But is that way I'm already on the right track?</p> <hr> <p>Meanwhile, if I use the second method, namely removing the city from the product attribute, I have trouble displaying city information on the shop page and additional information tab.</p> <p>The achievement so far is to add the code snippet below with a <a href="http://prnt.sc/1w2z1ah" rel="nofollow noreferrer">view like this</a>.</p> <p>When the product only has the category :</p> <ul> <li>Island (parent) <ul> <li>Province (child) <ul> <li>City (subChild)</li> </ul> </li> </ul> </li> </ul> <p>View works well (Rumah Cluster Pondok Aren).</p> <p>However, when the product has the category :</p> <ul> <li>Verified (parent)</li> <li>Island (parent) <ul> <li>Province (child) <ul> <li>City (subChild)</li> </ul> </li> </ul> </li> </ul> <p>What is displayed is the Verified category, not cities (Townhouse Premium Daerah Cileungsi).</p> <p>What have I missed?</p> <hr> Besides that, I also don't know how to display these subchild categories on the additional information tab.<br> I'm stuck here for days, so please help me out of this hassle... <p>Thanks a lot</p>
    [ { "answer_id": 396543, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 0, "selected": false, "text": "<p>Try this code</p>\n<pre><code>$('.download-btn').click(function(){\n $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n</code></pre>\n" }, { "answer_id": 396574, "author": "Sean Sr", "author_id": 206158, "author_profile": "https://wordpress.stackexchange.com/users/206158", "pm_score": 2, "selected": false, "text": "<p>Demo: <a href=\"https://codepen.io/livehelp/pen/MWoNPqX?editors=1010\" rel=\"nofollow noreferrer\">https://codepen.io/livehelp/pen/MWoNPqX?editors=1010</a></p>\n<p>Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.</p>\n<pre><code>&lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n e.preventDefault();\n const href = this.getAttribute(&quot;href&quot;);\n const offsetTop = document.querySelector(href).offsetTop;\n\n scroll({\n top: offsetTop,\n behavior: &quot;smooth&quot;\n });\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/10/09
    [ "https://wordpress.stackexchange.com/questions/396661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210665/" ]
    **Targets : Show Locations (sub-districts & cities) on the customized shop page & on tab additional information - Show on line 5** I'm building a property site using wordpress and woocommerce. In my country has 7 islands, 34 provinces, 514 Cities, 7041 Districts, 82194 Sub-districts. Then I grouped the data and added it to : On category * Verified (parent) * Sold (parent) * Rent (parent) * Island #1 (parent) + province #1 (child) - City #1(sub-child) * Island #2 (parent) + province #2 (child) - City #2(sub-child) * Island #7 (parent) + province #34 (child) - City #514(sub-child) and on product attribute : pa\_area : city (514) pa\_kecamatan : districts (7041) pa\_lokasi : sub-districts (82194) So, I can customize the shop page as desired/needed and [looks like this](http://prnt.sc/1w2v1b6). In the Additional Information tab, I also added the sub-district and the city [looks like this](http://prnt.sc/1w2w4tj). I also display links using permalinks, for example: https://mydomain/product-categories/island1/provinces3/cities8 (categories) https://mydomain/product-categories/island5/provinces1/cities12 (categories) https://mydomain/districts1492 (pa\_attributtes) https://mydomain/districts5630 (pa\_attributtes) https://mydomain/subdistricts11596 (pa\_attributtes) https://mydomain/subdistricts52630 (pa\_attributtes) So far everything seems fine. --- My mind changed when I created a demo site (with current product counts at 10k.) Loading slowly on entering/selecting attributes is starting to feel. (I know one of the causes is CPU, RAM/Hosting). This made me think whether display the city only in one place. (eg city in category or city in product attribute) can help reduce server load? Please correct me if I misunderstood this. But if it's true, i using the first way is to delete the city in the category and save the city in the product attribute. However this will cut the scope, for example : Previously : https://mydomain/product-categories/island1/provinces3/cities8 (categories) https://mydomain/product-categories/island5/provinces1/cities12 (categories) will be : https://mydomain/product-categories/island1/provinces3/ (categories) https://mydomain/product-categories/island5/provinces1/ (categories) To keep showing the same thing, i can just edit the permalink to: https://mydomain/product-categories/island1/provinces3/&cities8 (categories & pa\_area) https://mydomain/product-categories/island5/provinces1/&cities12 (categories & pa\_area) But is that way I'm already on the right track? --- Meanwhile, if I use the second method, namely removing the city from the product attribute, I have trouble displaying city information on the shop page and additional information tab. The achievement so far is to add the code snippet below with a [view like this](http://prnt.sc/1w2z1ah). When the product only has the category : * Island (parent) + Province (child) - City (subChild) View works well (Rumah Cluster Pondok Aren). However, when the product has the category : * Verified (parent) * Island (parent) + Province (child) - City (subChild) What is displayed is the Verified category, not cities (Townhouse Premium Daerah Cileungsi). What have I missed? --- Besides that, I also don't know how to display these subchild categories on the additional information tab. I'm stuck here for days, so please help me out of this hassle... Thanks a lot
    Demo: <https://codepen.io/livehelp/pen/MWoNPqX?editors=1010> Just use an HTML or Code element in Elementor to paste in the code instead of a Button element. ``` <h2><a href="#smooth" onclick="window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')";>Click to Download + Smooth Scroll</a></h2> <p>Insert enough text here to have a scoll bar.</p> <div id="smooth"><h1>Tadaa! Jumps to this div based on the id #smooth onClick.<h1></div> <script> const links = document.querySelectorAll("a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } </script> ```
    396,663
    <p>Everything worked fine a week ago. Lets Encrypt certificate on the site is valid. I am currently getting the following error while creating a product:</p> <pre><code>{&quot;code&quot;:&quot;woocommerce_product_image_upload_error&quot;,&quot;message&quot;:&quot;Error getting remote image https:\/\/mysite.com\/wp-content\/uploads\/2021\/10\/60c739fd1-1.jpg. Error: cURL error 60: SSL certificate problem: certificate has expired&quot;,&quot;data&quot;:{&quot;status&quot;:400}} </code></pre> <p>In this case, the picture is available by the URL. Tried these solutions (<a href="https://wp-kama.com/note/error-making-request-wordpress%5Benter" rel="nofollow noreferrer">https://wp-kama.com/note/error-making-request-wordpress[enter</a> link description here]<a href="https://wp-kama.com/note/error-making-request-wordpress" rel="nofollow noreferrer">1</a>) but doesn't help.</p>
    [ { "answer_id": 396543, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": 0, "selected": false, "text": "<p>Try this code</p>\n<pre><code>$('.download-btn').click(function(){\n $('html, body').animate({scrollTop : $('body').height() }, 800);\n});\n</code></pre>\n" }, { "answer_id": 396574, "author": "Sean Sr", "author_id": 206158, "author_profile": "https://wordpress.stackexchange.com/users/206158", "pm_score": 2, "selected": false, "text": "<p>Demo: <a href=\"https://codepen.io/livehelp/pen/MWoNPqX?editors=1010\" rel=\"nofollow noreferrer\">https://codepen.io/livehelp/pen/MWoNPqX?editors=1010</a></p>\n<p>Just use an HTML or Code element in Elementor to paste in the code instead of a Button element.</p>\n<pre><code>&lt;h2&gt;&lt;a href=&quot;#smooth&quot; onclick=&quot;window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')&quot;;&gt;Click to Download + Smooth Scroll&lt;/a&gt;&lt;/h2&gt;\n\n&lt;p&gt;Insert enough text here to have a scoll bar.&lt;/p&gt;\n\n&lt;div id=&quot;smooth&quot;&gt;&lt;h1&gt;Tadaa! Jumps to this div based on the id #smooth onClick.&lt;h1&gt;&lt;/div&gt;\n\n&lt;script&gt;\nconst links = document.querySelectorAll(&quot;a&quot;);\n\nfor (const link of links) {\n link.addEventListener(&quot;click&quot;, clickHandler);\n}\n\nfunction clickHandler(e) {\n e.preventDefault();\n const href = this.getAttribute(&quot;href&quot;);\n const offsetTop = document.querySelector(href).offsetTop;\n\n scroll({\n top: offsetTop,\n behavior: &quot;smooth&quot;\n });\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/10/09
    [ "https://wordpress.stackexchange.com/questions/396663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89603/" ]
    Everything worked fine a week ago. Lets Encrypt certificate on the site is valid. I am currently getting the following error while creating a product: ``` {"code":"woocommerce_product_image_upload_error","message":"Error getting remote image https:\/\/mysite.com\/wp-content\/uploads\/2021\/10\/60c739fd1-1.jpg. Error: cURL error 60: SSL certificate problem: certificate has expired","data":{"status":400}} ``` In this case, the picture is available by the URL. Tried these solutions ([https://wp-kama.com/note/error-making-request-wordpress[enter](https://wp-kama.com/note/error-making-request-wordpress%5Benter) link description here][1](https://wp-kama.com/note/error-making-request-wordpress)) but doesn't help.
    Demo: <https://codepen.io/livehelp/pen/MWoNPqX?editors=1010> Just use an HTML or Code element in Elementor to paste in the code instead of a Button element. ``` <h2><a href="#smooth" onclick="window.open('https://downloads.wordpress.org/plugin/apk-downloader.zip')";>Click to Download + Smooth Scroll</a></h2> <p>Insert enough text here to have a scoll bar.</p> <div id="smooth"><h1>Tadaa! Jumps to this div based on the id #smooth onClick.<h1></div> <script> const links = document.querySelectorAll("a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } </script> ```
    396,768
    <p>I registered a custom post type called <code>wasb_message</code> with <code>show_in_rest</code> set to <code>true</code> and <code>rest_base</code> set to <code>'messages'</code> so the resource is reachable at endpoint <em>https://mydomain/wp-json/wp/v2/messages</em> (using the <code>WP_REST_Posts_Controller</code> class). The custom post type has a custom meta field called <code>wasb_status</code> with an integer value, how can I add a custom parameter so when I do a get request to endpoint <em>https://mydomain/wp-json/wp/v2/messages?status=2</em> I retrieve messages with <code>wasb_status</code> equal to 2 without register a new route?</p> <p>I read <a href="https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/" rel="nofollow noreferrer">this code reference page</a> and <a href="https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route">this old question</a> but I can't get it working, using Postman to send get request I get:</p> <pre><code>{ &quot;code&quot;: &quot;rest_invalid_param&quot;, &quot;message&quot;: &quot;Parametro(i) non valido(i): status&quot;, &quot;data&quot;: { &quot;status&quot;: 400, &quot;params&quot;: { &quot;status&quot;: &quot;Stato non consentito.&quot; }, &quot;details&quot;: { &quot;status&quot;: { &quot;code&quot;: &quot;rest_forbidden_status&quot;, &quot;message&quot;: &quot;Stato non consentito.&quot;, &quot;data&quot;: { &quot;status&quot;: 401 } } } } } </code></pre>
    [ { "answer_id": 396769, "author": "Tami", "author_id": 181119, "author_profile": "https://wordpress.stackexchange.com/users/181119", "pm_score": 0, "selected": false, "text": "<p>As per the reply by Haris it should be something like this:</p>\n<pre><code>function wasb_rest_parameter($args, $request) {\n if( isset($request[&quot;wasb_status&quot;]) &amp;&amp; is_numeric($request[&quot;wasb_status&quot;]) ) {\n $args['meta_key'] = 'wasb_status';\n $args['meta_value'] = intval($request[&quot;wasb_status&quot;]);\n } \n \n return $args;\n}\nadd_filter('rest_wasb_message_query', 'wasb_rest_parameter', 10, 2);\n</code></pre>\n<p>Not yet tested. If it does not work, will update the answer.</p>\n" }, { "answer_id": 396774, "author": "icolumbro", "author_id": 178523, "author_profile": "https://wordpress.stackexchange.com/users/178523", "pm_score": 1, "selected": false, "text": "<p>I solved following <a href=\"https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route\">this answer</a> and writing:</p>\n<pre><code>public function query_wasb_messages_by_status( $args, $request ) {\n\n if ( ! is_null( $request-&gt;get_param( 'message_status' ) ) ) {\n $args['meta_query'] = array(\n '_wasb_message_status' =&gt; array(\n 'key' =&gt; '_wasb_message_status',\n 'value' =&gt; (int) $request-&gt;get_param( 'message_status' ),\n 'compare' =&gt; '=',\n 'type' =&gt; 'numeric'\n )\n );\n }\n\n return $args;\n\n }\nadd_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 );\n</code></pre>\n<p>My problem is I used <code>status</code> as parameter name but <code>status</code> already exists for posts ('draft', 'published', etc...) so I changed the name to <code>message_status</code>...</p>\n" } ]
    2021/10/12
    [ "https://wordpress.stackexchange.com/questions/396768", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/178523/" ]
    I registered a custom post type called `wasb_message` with `show_in_rest` set to `true` and `rest_base` set to `'messages'` so the resource is reachable at endpoint *https://mydomain/wp-json/wp/v2/messages* (using the `WP_REST_Posts_Controller` class). The custom post type has a custom meta field called `wasb_status` with an integer value, how can I add a custom parameter so when I do a get request to endpoint *https://mydomain/wp-json/wp/v2/messages?status=2* I retrieve messages with `wasb_status` equal to 2 without register a new route? I read [this code reference page](https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/) and [this old question](https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route) but I can't get it working, using Postman to send get request I get: ``` { "code": "rest_invalid_param", "message": "Parametro(i) non valido(i): status", "data": { "status": 400, "params": { "status": "Stato non consentito." }, "details": { "status": { "code": "rest_forbidden_status", "message": "Stato non consentito.", "data": { "status": 401 } } } } } ```
    I solved following [this answer](https://wordpress.stackexchange.com/questions/300316/how-to-add-a-custom-parameter-to-a-wp-api-default-route) and writing: ``` public function query_wasb_messages_by_status( $args, $request ) { if ( ! is_null( $request->get_param( 'message_status' ) ) ) { $args['meta_query'] = array( '_wasb_message_status' => array( 'key' => '_wasb_message_status', 'value' => (int) $request->get_param( 'message_status' ), 'compare' => '=', 'type' => 'numeric' ) ); } return $args; } add_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 ); ``` My problem is I used `status` as parameter name but `status` already exists for posts ('draft', 'published', etc...) so I changed the name to `message_status`...
    396,902
    <p>I try to <code>require_once()</code> a file, if the condition of a specific tag is met, on a woocommerce single product page.</p> <p>I've added following to my <code>functions.php</code></p> <pre><code>if(has_term('xyz', 'product_tag')){ require_once WP_CONTENT_DIR . '/path/file.php'; } </code></pre> <p>It doesn't load my file, but if I take it out of my condition, it does load.</p> <p>What can I do to achieve this logic?</p>
    [ { "answer_id": 396904, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>require_once is a function, try this way.</p>\n<pre class=\"lang-php prettyprint-override\"><code>if(has_term('xyz', 'product_tag')){\n require_once( WP_CONTENT_DIR.'/path/file.php');\n}\n</code></pre>\n<p>also require_once() in functions.php, dont know what to say. give feedback if the code above had work has intended.</p>\n" }, { "answer_id": 396940, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 2, "selected": true, "text": "<p><code>has_term()</code> is a template function therefore it does not work if you use it straight in functions.php which is loaded well before knowing if the current object is a product page.\nSo if you use it in <code>functions.php</code> you could do:</p>\n<pre><code>add_action('template_redirect','my_inclusion_function');\nfunction my_inclusion_function(){\n if(is_product() &amp;&amp; has_term('xyz', 'product_tag')){\n require_once( WP_CONTENT_DIR.'/path/file.php');\n }\n}\n</code></pre>\n<p><code>is_product()</code> checks if you are in a single product and then if the product has tag xyz</p>\n<p>If the inclusion has layout implications such as print additional information or so, then this approach is not ideal since the inclusion occurs at the very beginning of the content jsut after the <code>&lt;body&gt;</code> tag opening. In this case you can just modify the single-product.php template file (as suggested in the comment by <a href=\"https://wordpress.stackexchange.com/users/198152/tiago-calado\">tiago calado</a>)</p>\n<p>Also you can use one of the available hooks in the single-product page check <a href=\"https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/\" rel=\"nofollow noreferrer\">this useful resource</a> and use it directly in functions.php. The advantage of this last approach is that you don't have to review the layout pages in case of future theme switch.</p>\n" } ]
    2021/10/14
    [ "https://wordpress.stackexchange.com/questions/396902", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213621/" ]
    I try to `require_once()` a file, if the condition of a specific tag is met, on a woocommerce single product page. I've added following to my `functions.php` ``` if(has_term('xyz', 'product_tag')){ require_once WP_CONTENT_DIR . '/path/file.php'; } ``` It doesn't load my file, but if I take it out of my condition, it does load. What can I do to achieve this logic?
    `has_term()` is a template function therefore it does not work if you use it straight in functions.php which is loaded well before knowing if the current object is a product page. So if you use it in `functions.php` you could do: ``` add_action('template_redirect','my_inclusion_function'); function my_inclusion_function(){ if(is_product() && has_term('xyz', 'product_tag')){ require_once( WP_CONTENT_DIR.'/path/file.php'); } } ``` `is_product()` checks if you are in a single product and then if the product has tag xyz If the inclusion has layout implications such as print additional information or so, then this approach is not ideal since the inclusion occurs at the very beginning of the content jsut after the `<body>` tag opening. In this case you can just modify the single-product.php template file (as suggested in the comment by [tiago calado](https://wordpress.stackexchange.com/users/198152/tiago-calado)) Also you can use one of the available hooks in the single-product page check [this useful resource](https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/) and use it directly in functions.php. The advantage of this last approach is that you don't have to review the layout pages in case of future theme switch.
    396,908
    <p>Unless I type the URL of my site as example.com/wp-login.php, with URL typed as example.com, the front page is automatically directed to the following unknown site:</p> <pre><code>https://elementonfor.live/?utm_campaign=pEv9cTd8QNHYzqqr5UNFx2COHvnp_JE3r8uVIhm3Qww1&amp;t=main9 </code></pre> <p>The above website is unknown, and it is not clear where it has come from. I have scanned my website for malware. The malware plugin I am using shows the website as clean. Not sure what I should do to resolve the issue.</p>
    [ { "answer_id": 396911, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>have you installed any new plugin recently. that can be a cause.\nif so try to deactivate them and check if the site still does that.\ndeactive all plugins not essential to home page. and check if it still does that. if so, activate one by one until you get the one is making that.</p>\n<p>this is just one probably cause.\nafter you make sure any plugin is doing this. and the problem goes on. now you are sure is not a plugin.\nlook on your functions.php and look for any function that can be making you to be redirect.\ncheck also if other pages load properly like exanple.com/wp-login or example.com/somepageYouKnowExistes if this only happens on your front page can be an issue with your font-page.php, or with elementor on that page once your are being redirect to a supposed elementor page.\nif any of this gives you a clue. there are many more ways to go on debuging manually.</p>\n" }, { "answer_id": 396939, "author": "Reza", "author_id": 170049, "author_profile": "https://wordpress.stackexchange.com/users/170049", "pm_score": 1, "selected": false, "text": "<p>Finally, I had to contact my web host. They cleared the server cache and everything is back to normal. Thanks to @tiago-calado and @Rup for their response.</p>\n" } ]
    2021/10/14
    [ "https://wordpress.stackexchange.com/questions/396908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170049/" ]
    Unless I type the URL of my site as example.com/wp-login.php, with URL typed as example.com, the front page is automatically directed to the following unknown site: ``` https://elementonfor.live/?utm_campaign=pEv9cTd8QNHYzqqr5UNFx2COHvnp_JE3r8uVIhm3Qww1&t=main9 ``` The above website is unknown, and it is not clear where it has come from. I have scanned my website for malware. The malware plugin I am using shows the website as clean. Not sure what I should do to resolve the issue.
    Finally, I had to contact my web host. They cleared the server cache and everything is back to normal. Thanks to @tiago-calado and @Rup for their response.
    396,944
    <p>hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr_fingerprint_default so please give me correct command line to run thanks in advance</p>
    [ { "answer_id": 396945, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>First, make sure you back up your database. :)</p>\n<p>If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be</p>\n<p><code>DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'</code></p>\n" }, { "answer_id": 396948, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n</code></pre>\n<p>{PREFIX} is the string <code>$table_prefix</code> defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result</p>\n<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n</code></pre>\n" } ]
    2021/10/15
    [ "https://wordpress.stackexchange.com/questions/396944", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175359/" ]
    hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp\_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr\_fingerprint\_default so please give me correct command line to run thanks in advance
    ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' ``` {PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 ```
    396,962
    <p>I'm new to the Wordpress/PHP world. I want my page be able to communicate with an API that I build myself. So for this I have a form on my Wordpress Page using a HTML code widget which looks like this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; &lt;form id=&quot;myform&quot; action=&quot;submit_shortcode&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;input&quot; placeholder=&quot;Input&quot; required&gt; &lt;input type=&quot;submit&quot; value=&quot;Enter&quot;&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And I have added this code to functions.php of the current theme:</p> <pre><code>function get_shortcode($sc) { $response = wp_remote_get('http://localhost:9000/shortcode/'.$sc); if (is_array($response)) { $body = $response['body']; $data = json_decode($body); echo $data; if (! is_wp_error($data)) { echo &quot;error&quot;; } } return; } add_action('submit_shortcode', 'get_shortcode'); </code></pre> <p>But I can't see how to integrate the function with the form. When I submit my form, it sends me to mypage/submit_shortcode. How can I trigger the function get_shortcode when submitting the form?</p> <p>PS: This &quot;shortcode&quot; has nothing to do with the Shortcode widget of Elementor</p>
    [ { "answer_id": 396945, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>First, make sure you back up your database. :)</p>\n<p>If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be</p>\n<p><code>DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'</code></p>\n" }, { "answer_id": 396948, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n</code></pre>\n<p>{PREFIX} is the string <code>$table_prefix</code> defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result</p>\n<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n</code></pre>\n" } ]
    2021/10/15
    [ "https://wordpress.stackexchange.com/questions/396962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213571/" ]
    I'm new to the Wordpress/PHP world. I want my page be able to communicate with an API that I build myself. So for this I have a form on my Wordpress Page using a HTML code widget which looks like this: ``` <html> <body> <div> <form id="myform" action="submit_shortcode"> <input type="text" id="input" placeholder="Input" required> <input type="submit" value="Enter"> </form> </div> </body> </html> ``` And I have added this code to functions.php of the current theme: ``` function get_shortcode($sc) { $response = wp_remote_get('http://localhost:9000/shortcode/'.$sc); if (is_array($response)) { $body = $response['body']; $data = json_decode($body); echo $data; if (! is_wp_error($data)) { echo "error"; } } return; } add_action('submit_shortcode', 'get_shortcode'); ``` But I can't see how to integrate the function with the form. When I submit my form, it sends me to mypage/submit\_shortcode. How can I trigger the function get\_shortcode when submitting the form? PS: This "shortcode" has nothing to do with the Shortcode widget of Elementor
    ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' ``` {PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 ```
    397,015
    <p>I recently migrated the site from a subdomain back to the main domain using WP All-in-One Migration Tool. The migration was successful and I can see the wp-admin panel just fine and even view the site while logged in.</p> <p>But... when logging out the visitors just see the white screen of death. I have tried every fix in the book on Google, any tips would be appreciated.</p> <p>Thanks!</p>
    [ { "answer_id": 396945, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>First, make sure you back up your database. :)</p>\n<p>If you're wanting to run a SQL command directly - perhaps using phpMyAdmin - the query would be</p>\n<p><code>DELETE FROM wp_postmeta WHERE meta_key = 'kksr_fingerprint_default'</code></p>\n" }, { "answer_id": 396948, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n</code></pre>\n<p>{PREFIX} is the string <code>$table_prefix</code> defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result</p>\n<pre><code>DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 \n</code></pre>\n" } ]
    2021/10/18
    [ "https://wordpress.stackexchange.com/questions/397015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213737/" ]
    I recently migrated the site from a subdomain back to the main domain using WP All-in-One Migration Tool. The migration was successful and I can see the wp-admin panel just fine and even view the site while logged in. But... when logging out the visitors just see the white screen of death. I have tried every fix in the book on Google, any tips would be appreciated. Thanks!
    ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' ``` {PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result ``` DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1 ```
    397,120
    <p>Checking the <code>editor-blocks.css</code> file found in some themes, I see the following CSS classes added before some of the individual block classes:</p> <pre><code>.edit-post-visual-editor .editor-block-list__layout .editor-block-list__block .block-library-list </code></pre> <p>An example:</p> <pre><code>.editor-block-list__block .wp-block-latest-comments { margin-left: 0; margin-right: 0; } </code></pre> <p>And then others, don't have them:</p> <pre><code>.wp-block-quote.is-large, .wp-block-quote.is-style-large { font-size: 1.5rem; margin: 0 0.8em 0.8em; padding: 0; border: 0; } </code></pre> <p>What's the use of these CSS classes? Which elements in the block editor do they target? Why do some of the block CSS classes have them added before and why others don't? Are they really necessary? Why some themes have an <code>editor-blocks.css</code> file and a <code>blocks.css</code> file and why others just the <code>blocks.css</code> one?</p> <p>Thanks in advance</p>
    [ { "answer_id": 397155, "author": "Kalimah", "author_id": 35871, "author_profile": "https://wordpress.stackexchange.com/users/35871", "pm_score": 0, "selected": false, "text": "<p>Searching the editor source code: <a href=\"https://github.com/WordPress/gutenberg\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg</a> does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/register_block_type/\" rel=\"nofollow noreferrer\"><code>register_block_type</code></a> is used to add the block date in WordPress. Typically with these arguments:</p>\n<pre class=\"lang-php prettyprint-override\"><code> register_block_type( 'custom-plugin/custom-block', array(\n 'editor_script' =&gt; 'editor-script.js',\n 'editor_style' =&gt; 'editor-style.css',\n 'style' =&gt; 'frontend.css',\n ) );\n</code></pre>\n<p><code>editor_script</code> and <code>editor_style</code> add files to editor admin. <code>style</code> is meant to add CSS to frontend.</p>\n<p>What documentation does not mention is that <code>style</code> is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.</p>\n" }, { "answer_id": 397574, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": -1, "selected": false, "text": "<p>The <code>editor-block-list__block</code> class in only rendered in the Gutenberg editor, while the <code>wp-block-[blockname]</code> class is rendered on both the front end and the editor. So classes prepended with <code>editor-block-list__block</code> are targeting the backend only.</p>\n" }, { "answer_id": 402084, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 1, "selected": true, "text": "<p>In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.</p>\n<p>Both <code>.editor-block-list__layout</code> and <code>.editor-block-list__block</code> classes are deprecated since WordPress 5.4 and have been renamed to <code>.block-editor-block-list__layout</code> and <code>.block-editor-block-list__block</code>, respectively. The <code>.block-editor-block-list__layout</code> class targets all the blocks found in the post content and <code>.block-editor-block-list__block</code> class targets individual block types in the post content, so the latter is equivalent to using the specific <code>.wp-block-***</code> classes.</p>\n<p>I have not seen the <code>.block-library-list</code> class used anywhere in the block editor, so I assume it makes no sense targeting it.</p>\n<p>Finally, the <code>.edit-post-visual-editor</code> class targets the whole block editor.</p>\n<p>In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the <code>.wp-block-***</code> classes to style individual block types in the block editor.</p>\n" } ]
    2021/10/20
    [ "https://wordpress.stackexchange.com/questions/397120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
    Checking the `editor-blocks.css` file found in some themes, I see the following CSS classes added before some of the individual block classes: ``` .edit-post-visual-editor .editor-block-list__layout .editor-block-list__block .block-library-list ``` An example: ``` .editor-block-list__block .wp-block-latest-comments { margin-left: 0; margin-right: 0; } ``` And then others, don't have them: ``` .wp-block-quote.is-large, .wp-block-quote.is-style-large { font-size: 1.5rem; margin: 0 0.8em 0.8em; padding: 0; border: 0; } ``` What's the use of these CSS classes? Which elements in the block editor do they target? Why do some of the block CSS classes have them added before and why others don't? Are they really necessary? Why some themes have an `editor-blocks.css` file and a `blocks.css` file and why others just the `blocks.css` one? Thanks in advance
    In case anyone is interested, these are the conclusions I reached after studying the block editor for some time. Both `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes. I have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it. Finally, the `.edit-post-visual-editor` class targets the whole block editor. In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor.
    397,145
    <p>In this project, there are custom posts with a variety of titles. In each post with the title that is the name of a person (first name, last name), there is a custom field (custom_title) that can hold an alternate name (last name, first name).</p> <p>In order to display the names in a useful way in the custom archive page, the object is to check for a value in the custom_title field and if present update the post title with the custom title. After all of the applicable titles have been updated, the query must sort all of the posts by title, all the while recognizing the updated titles.</p> <p>Using the code below, the original titles of the name articles are updated with the custom titles, but the sort order doesn't change--it still sorts by the original title.</p> <p>Thanks for taking the time to help!</p> <pre><code> function cchs_swap_title( $updatedTitle) { $customTitle = get_post_meta( get_the_ID(), 'custom_title', true); if(!empty($customTitle)) { $updatedTitle = $customTitle; } return $updatedTitle; } add_filter( 'the_title', 'cchs_swap_title'); function cchs_archives_orderby( $the_query ) { if(!is_admin() &amp;&amp; $the_query-&gt;is_main_query()) { $the_query-&gt;set( 'orderby', 'title' ); $the_query-&gt;set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'cchs_archives_orderby', 99999 ); $args = array( 'post_type' =&gt; 'cchs_article', 'posts_per_page' =&gt; -1 ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); get_template_part( 'template-parts/content', 'archive-cchs_article'); endwhile; wp_reset_postdata(); else : get_template_part( 'template-parts/content', 'none' ); endif; </code></pre>
    [ { "answer_id": 397155, "author": "Kalimah", "author_id": 35871, "author_profile": "https://wordpress.stackexchange.com/users/35871", "pm_score": 0, "selected": false, "text": "<p>Searching the editor source code: <a href=\"https://github.com/WordPress/gutenberg\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg</a> does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/register_block_type/\" rel=\"nofollow noreferrer\"><code>register_block_type</code></a> is used to add the block date in WordPress. Typically with these arguments:</p>\n<pre class=\"lang-php prettyprint-override\"><code> register_block_type( 'custom-plugin/custom-block', array(\n 'editor_script' =&gt; 'editor-script.js',\n 'editor_style' =&gt; 'editor-style.css',\n 'style' =&gt; 'frontend.css',\n ) );\n</code></pre>\n<p><code>editor_script</code> and <code>editor_style</code> add files to editor admin. <code>style</code> is meant to add CSS to frontend.</p>\n<p>What documentation does not mention is that <code>style</code> is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.</p>\n" }, { "answer_id": 397574, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": -1, "selected": false, "text": "<p>The <code>editor-block-list__block</code> class in only rendered in the Gutenberg editor, while the <code>wp-block-[blockname]</code> class is rendered on both the front end and the editor. So classes prepended with <code>editor-block-list__block</code> are targeting the backend only.</p>\n" }, { "answer_id": 402084, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 1, "selected": true, "text": "<p>In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.</p>\n<p>Both <code>.editor-block-list__layout</code> and <code>.editor-block-list__block</code> classes are deprecated since WordPress 5.4 and have been renamed to <code>.block-editor-block-list__layout</code> and <code>.block-editor-block-list__block</code>, respectively. The <code>.block-editor-block-list__layout</code> class targets all the blocks found in the post content and <code>.block-editor-block-list__block</code> class targets individual block types in the post content, so the latter is equivalent to using the specific <code>.wp-block-***</code> classes.</p>\n<p>I have not seen the <code>.block-library-list</code> class used anywhere in the block editor, so I assume it makes no sense targeting it.</p>\n<p>Finally, the <code>.edit-post-visual-editor</code> class targets the whole block editor.</p>\n<p>In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the <code>.wp-block-***</code> classes to style individual block types in the block editor.</p>\n" } ]
    2021/10/20
    [ "https://wordpress.stackexchange.com/questions/397145", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213871/" ]
    In this project, there are custom posts with a variety of titles. In each post with the title that is the name of a person (first name, last name), there is a custom field (custom\_title) that can hold an alternate name (last name, first name). In order to display the names in a useful way in the custom archive page, the object is to check for a value in the custom\_title field and if present update the post title with the custom title. After all of the applicable titles have been updated, the query must sort all of the posts by title, all the while recognizing the updated titles. Using the code below, the original titles of the name articles are updated with the custom titles, but the sort order doesn't change--it still sorts by the original title. Thanks for taking the time to help! ``` function cchs_swap_title( $updatedTitle) { $customTitle = get_post_meta( get_the_ID(), 'custom_title', true); if(!empty($customTitle)) { $updatedTitle = $customTitle; } return $updatedTitle; } add_filter( 'the_title', 'cchs_swap_title'); function cchs_archives_orderby( $the_query ) { if(!is_admin() && $the_query->is_main_query()) { $the_query->set( 'orderby', 'title' ); $the_query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'cchs_archives_orderby', 99999 ); $args = array( 'post_type' => 'cchs_article', 'posts_per_page' => -1 ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); get_template_part( 'template-parts/content', 'archive-cchs_article'); endwhile; wp_reset_postdata(); else : get_template_part( 'template-parts/content', 'none' ); endif; ```
    In case anyone is interested, these are the conclusions I reached after studying the block editor for some time. Both `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes. I have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it. Finally, the `.edit-post-visual-editor` class targets the whole block editor. In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor.
    397,316
    <p>I want to change WooCommerce pagination links from:</p> <ul> <li>example.com/category/page/3/ to:</li> <li>example.com/category/3/</li> </ul> <p>I found many examples of how to change '/page/' to '/something/' but I want only the number of the current page. I also tried this:</p> <pre class="lang-php prettyprint-override"><code>$wp_rewrite-&gt;pagination_base = ''; </code></pre> <p>But then my url looks like this:</p> <p><code>example.com/category//3/</code></p> <p>And that's not good either. Is it even possible to remove 'pagination base' from url structure?</p>
    [ { "answer_id": 397155, "author": "Kalimah", "author_id": 35871, "author_profile": "https://wordpress.stackexchange.com/users/35871", "pm_score": 0, "selected": false, "text": "<p>Searching the editor source code: <a href=\"https://github.com/WordPress/gutenberg\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg</a> does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/register_block_type/\" rel=\"nofollow noreferrer\"><code>register_block_type</code></a> is used to add the block date in WordPress. Typically with these arguments:</p>\n<pre class=\"lang-php prettyprint-override\"><code> register_block_type( 'custom-plugin/custom-block', array(\n 'editor_script' =&gt; 'editor-script.js',\n 'editor_style' =&gt; 'editor-style.css',\n 'style' =&gt; 'frontend.css',\n ) );\n</code></pre>\n<p><code>editor_script</code> and <code>editor_style</code> add files to editor admin. <code>style</code> is meant to add CSS to frontend.</p>\n<p>What documentation does not mention is that <code>style</code> is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.</p>\n" }, { "answer_id": 397574, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": -1, "selected": false, "text": "<p>The <code>editor-block-list__block</code> class in only rendered in the Gutenberg editor, while the <code>wp-block-[blockname]</code> class is rendered on both the front end and the editor. So classes prepended with <code>editor-block-list__block</code> are targeting the backend only.</p>\n" }, { "answer_id": 402084, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 1, "selected": true, "text": "<p>In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.</p>\n<p>Both <code>.editor-block-list__layout</code> and <code>.editor-block-list__block</code> classes are deprecated since WordPress 5.4 and have been renamed to <code>.block-editor-block-list__layout</code> and <code>.block-editor-block-list__block</code>, respectively. The <code>.block-editor-block-list__layout</code> class targets all the blocks found in the post content and <code>.block-editor-block-list__block</code> class targets individual block types in the post content, so the latter is equivalent to using the specific <code>.wp-block-***</code> classes.</p>\n<p>I have not seen the <code>.block-library-list</code> class used anywhere in the block editor, so I assume it makes no sense targeting it.</p>\n<p>Finally, the <code>.edit-post-visual-editor</code> class targets the whole block editor.</p>\n<p>In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the <code>.wp-block-***</code> classes to style individual block types in the block editor.</p>\n" } ]
    2021/10/25
    [ "https://wordpress.stackexchange.com/questions/397316", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214037/" ]
    I want to change WooCommerce pagination links from: * example.com/category/page/3/ to: * example.com/category/3/ I found many examples of how to change '/page/' to '/something/' but I want only the number of the current page. I also tried this: ```php $wp_rewrite->pagination_base = ''; ``` But then my url looks like this: `example.com/category//3/` And that's not good either. Is it even possible to remove 'pagination base' from url structure?
    In case anyone is interested, these are the conclusions I reached after studying the block editor for some time. Both `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes. I have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it. Finally, the `.edit-post-visual-editor` class targets the whole block editor. In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor.
    397,380
    <p>I'm performing an <code>wpdb-&gt;insert()</code>. When a field includes a special the insert is not done and I get the error</p> <blockquote> <p>Error in Wordpress database for query SHOW FULL COLUMNS FROM <code>wp_my_table</code></p> </blockquote> <p>If I don't use special characters the insert is done correctly.</p> <p>Apparently, the column collations are correct, but something is wrong. I saw this <a href="https://wordpress.stackexchange.com/questions/246503/wpdb-insert-with-special-characters">post answers</a> but as I said my collations seem to be correct.</p> <p>This is my table definition:</p> <pre><code>SHOW CREATE TABLE wp_my_table; CREATE TABLE `wp_my_table` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c_name` varchar(50) COLLATE utf8mb4_unicode_520_ci NOT NULL, `creation_date` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; </code></pre> <p>And this is the insert statement:</p> <pre><code>$wpdb-&gt;insert('wp_my_table', ['c_name' =&gt; $_POST['c_name'], 'creation_date' =&gt; date('Y-m-d H:i:s') ]); </code></pre> <p>Adding <code>esc_sql</code> or <code>esc_html</code> didn't help.</p> <p>Actually, error is not in the query or insert itself, but in $_POST['c_name'], because if I call with a hard coded string, the query works properly:</p> <pre><code>$wpdb-&gt;insert('wp_my_table', ['c_name' =&gt; '1º áá', 'creation_date' =&gt; date('Y-m-d H:i:s') ]); </code></pre>
    [ { "answer_id": 397155, "author": "Kalimah", "author_id": 35871, "author_profile": "https://wordpress.stackexchange.com/users/35871", "pm_score": 0, "selected": false, "text": "<p>Searching the editor source code: <a href=\"https://github.com/WordPress/gutenberg\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg</a> does not show much results. I suggest search the theme source code these classes to see where they are applied. (If you press . while viewing the code on github you will get a VSCode editor)</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/register_block_type/\" rel=\"nofollow noreferrer\"><code>register_block_type</code></a> is used to add the block date in WordPress. Typically with these arguments:</p>\n<pre class=\"lang-php prettyprint-override\"><code> register_block_type( 'custom-plugin/custom-block', array(\n 'editor_script' =&gt; 'editor-script.js',\n 'editor_style' =&gt; 'editor-style.css',\n 'style' =&gt; 'frontend.css',\n ) );\n</code></pre>\n<p><code>editor_script</code> and <code>editor_style</code> add files to editor admin. <code>style</code> is meant to add CSS to frontend.</p>\n<p>What documentation does not mention is that <code>style</code> is also loaded in backend. So it is possible those theme are using one file for bother backend and frontend to minimize the code they write.</p>\n" }, { "answer_id": 397574, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": -1, "selected": false, "text": "<p>The <code>editor-block-list__block</code> class in only rendered in the Gutenberg editor, while the <code>wp-block-[blockname]</code> class is rendered on both the front end and the editor. So classes prepended with <code>editor-block-list__block</code> are targeting the backend only.</p>\n" }, { "answer_id": 402084, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 1, "selected": true, "text": "<p>In case anyone is interested, these are the conclusions I reached after studying the block editor for some time.</p>\n<p>Both <code>.editor-block-list__layout</code> and <code>.editor-block-list__block</code> classes are deprecated since WordPress 5.4 and have been renamed to <code>.block-editor-block-list__layout</code> and <code>.block-editor-block-list__block</code>, respectively. The <code>.block-editor-block-list__layout</code> class targets all the blocks found in the post content and <code>.block-editor-block-list__block</code> class targets individual block types in the post content, so the latter is equivalent to using the specific <code>.wp-block-***</code> classes.</p>\n<p>I have not seen the <code>.block-library-list</code> class used anywhere in the block editor, so I assume it makes no sense targeting it.</p>\n<p>Finally, the <code>.edit-post-visual-editor</code> class targets the whole block editor.</p>\n<p>In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the <code>.wp-block-***</code> classes to style individual block types in the block editor.</p>\n" } ]
    2021/10/27
    [ "https://wordpress.stackexchange.com/questions/397380", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17141/" ]
    I'm performing an `wpdb->insert()`. When a field includes a special the insert is not done and I get the error > > Error in Wordpress database for query SHOW FULL COLUMNS FROM `wp_my_table` > > > If I don't use special characters the insert is done correctly. Apparently, the column collations are correct, but something is wrong. I saw this [post answers](https://wordpress.stackexchange.com/questions/246503/wpdb-insert-with-special-characters) but as I said my collations seem to be correct. This is my table definition: ``` SHOW CREATE TABLE wp_my_table; CREATE TABLE `wp_my_table` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c_name` varchar(50) COLLATE utf8mb4_unicode_520_ci NOT NULL, `creation_date` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; ``` And this is the insert statement: ``` $wpdb->insert('wp_my_table', ['c_name' => $_POST['c_name'], 'creation_date' => date('Y-m-d H:i:s') ]); ``` Adding `esc_sql` or `esc_html` didn't help. Actually, error is not in the query or insert itself, but in $\_POST['c\_name'], because if I call with a hard coded string, the query works properly: ``` $wpdb->insert('wp_my_table', ['c_name' => '1º áá', 'creation_date' => date('Y-m-d H:i:s') ]); ```
    In case anyone is interested, these are the conclusions I reached after studying the block editor for some time. Both `.editor-block-list__layout` and `.editor-block-list__block` classes are deprecated since WordPress 5.4 and have been renamed to `.block-editor-block-list__layout` and `.block-editor-block-list__block`, respectively. The `.block-editor-block-list__layout` class targets all the blocks found in the post content and `.block-editor-block-list__block` class targets individual block types in the post content, so the latter is equivalent to using the specific `.wp-block-***` classes. I have not seen the `.block-library-list` class used anywhere in the block editor, so I assume it makes no sense targeting it. Finally, the `.edit-post-visual-editor` class targets the whole block editor. In summary, in the most recent versions of WordPress (5.4 onwards) it's safe to just use the `.wp-block-***` classes to style individual block types in the block editor.
    397,571
    <p>brand new to WordPress and StackExchange so excuse my poor etiquette. I am making a custom WordPress theme for a class, and somewhere along the line made an error so tiny neither me nor my professor could find it, but it's specifically caused my entire CSS page to not load whatsoever. Through troubleshooting, we figured out it's probably an issue somewhere in the .php files. Does anybody see anything that could be causing such a huge problem? I regret asking so cluelessly for help, but we're stumped!</p> <p><strong>index.html</strong></p> <pre><code> &lt;?php get_header(); ?&gt; &lt;?php get_sidebar(); ?&gt; &lt;div id=&quot;content1&quot;&gt; &lt;article&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;h1 id=&quot;post-&lt;?php the_ID(); ?&gt;&quot;&gt;&lt;a href=&quot;&lt;?php the_permalink() ?&gt;&quot; rel=&quot;bookmark&quot; title=&quot;Permanent link to &lt;?php the_title(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;/article&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; --- </code></pre> <p><strong>header.php</strong></p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;title&gt; Portfolio&lt;/title&gt; &lt;!-- &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Raleway:wght@300&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;meta name=&quot;description&quot; content=&quot;Our first page&quot;&gt; &lt;meta name=&quot;keywords&quot; content=&quot;html tutorial template&quot;&gt; --&gt; &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; </code></pre> <p><strong>footer.php</strong>, which doesn't have anything especially important</p> <pre><code>&lt;footer&gt;&lt;/footer&gt; &lt;/div&gt; &lt;!-- close wrapper --&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    [ { "answer_id": 397572, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><em><strong>Because you're using relative URLs.</strong></em></p>\n<p>When you are on <code>example.com</code> it will load <code>example.com/style.css</code></p>\n<p>When you are on <code>example.com/test</code> it will load <code>example.com/test/style.css</code> etc etc</p>\n<p>As you move around the site, it will change where it's looking. None of your pages ever referenced your <code>style.css</code>, it's probably returning an empty 404 page instead.</p>\n<hr />\n<p>Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.</p>\n" }, { "answer_id": 397576, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": 2, "selected": false, "text": "<p>As stated, <code>href=&quot;style.css&quot;</code> is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.</p>\n<p>So in your contexts, that would be:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><code>get_stylesheet_uri()</code> will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it <code>style.css</code>.</p>\n<p>But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your <code>header.php</code> file, you'd enqueue in your <code>functions.php</code> file like this:</p>\n<pre><code>function my_custom_enqueue_function(){\n wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n</code></pre>\n<p>There are more attributes, not in that example, to the <code>wp_enqueue_style()</code> function that make it even more useful, so it's worth looking up and getting to know.</p>\n" }, { "answer_id": 397578, "author": "Majid A.", "author_id": 214325, "author_profile": "https://wordpress.stackexchange.com/users/214325", "pm_score": 0, "selected": false, "text": "<p>Check this:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p>If your <code>style.css</code> file on the theme's root directory.</p>\n" } ]
    2021/11/01
    [ "https://wordpress.stackexchange.com/questions/397571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214321/" ]
    brand new to WordPress and StackExchange so excuse my poor etiquette. I am making a custom WordPress theme for a class, and somewhere along the line made an error so tiny neither me nor my professor could find it, but it's specifically caused my entire CSS page to not load whatsoever. Through troubleshooting, we figured out it's probably an issue somewhere in the .php files. Does anybody see anything that could be causing such a huge problem? I regret asking so cluelessly for help, but we're stumped! **index.html** ``` <?php get_header(); ?> <?php get_sidebar(); ?> <div id="content1"> <article> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1 id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent link to <?php the_title(); ?>"><?php the_title(); ?></a></h1> <?php the_content(); ?> <?php wp_link_pages(); ?> <?php endwhile; ?> <?php endif; ?> </article> </div> <?php get_footer(); ?> --- ``` **header.php** ``` <html> <head> <title> Portfolio</title> <!-- <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet"> <meta name="description" content="Our first page"> <meta name="keywords" content="html tutorial template"> --> <link href="style.css" rel="stylesheet"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> ``` **footer.php**, which doesn't have anything especially important ``` <footer></footer> </div> <!-- close wrapper --> <?php wp_footer(); ?> </body> </html> ```
    ``` <link href="style.css" rel="stylesheet"> ``` ***Because you're using relative URLs.*** When you are on `example.com` it will load `example.com/style.css` When you are on `example.com/test` it will load `example.com/test/style.css` etc etc As you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead. --- Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.
    397,644
    <p>I ask if it is possible to wrap a specific sidebar within a <code>&lt;div class=&quot;customdiv&quot;&gt;&lt;/div&gt;</code>. Are there any instructions to add in the function.php file? Thank you.</p> <p>Like this:</p> <pre><code>I've created this sidebar (which contains widgets): // ATTIVITA - widgets register_sidebar( array ( 'name' =&gt; __( 'ATTIVITA prenotabili', 'your-theme-domain' ), 'id' =&gt; '&lt;div id=&quot;testimonial-slider&quot;&gt;', 'description' =&gt; __( 'ATTIVITA prenotabili', 'your-theme-domain' ), 'before_widget' =&gt; '&lt;div class=&quot;widget-content&quot;&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3 class=&quot;widget-title&quot;&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); //fine </code></pre> <p>I would like to wrap it into a Do you think could it be possible? Many thanks.</p>
    [ { "answer_id": 397572, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><em><strong>Because you're using relative URLs.</strong></em></p>\n<p>When you are on <code>example.com</code> it will load <code>example.com/style.css</code></p>\n<p>When you are on <code>example.com/test</code> it will load <code>example.com/test/style.css</code> etc etc</p>\n<p>As you move around the site, it will change where it's looking. None of your pages ever referenced your <code>style.css</code>, it's probably returning an empty 404 page instead.</p>\n<hr />\n<p>Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.</p>\n" }, { "answer_id": 397576, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": 2, "selected": false, "text": "<p>As stated, <code>href=&quot;style.css&quot;</code> is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.</p>\n<p>So in your contexts, that would be:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><code>get_stylesheet_uri()</code> will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it <code>style.css</code>.</p>\n<p>But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your <code>header.php</code> file, you'd enqueue in your <code>functions.php</code> file like this:</p>\n<pre><code>function my_custom_enqueue_function(){\n wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n</code></pre>\n<p>There are more attributes, not in that example, to the <code>wp_enqueue_style()</code> function that make it even more useful, so it's worth looking up and getting to know.</p>\n" }, { "answer_id": 397578, "author": "Majid A.", "author_id": 214325, "author_profile": "https://wordpress.stackexchange.com/users/214325", "pm_score": 0, "selected": false, "text": "<p>Check this:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p>If your <code>style.css</code> file on the theme's root directory.</p>\n" } ]
    2021/11/03
    [ "https://wordpress.stackexchange.com/questions/397644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214375/" ]
    I ask if it is possible to wrap a specific sidebar within a `<div class="customdiv"></div>`. Are there any instructions to add in the function.php file? Thank you. Like this: ``` I've created this sidebar (which contains widgets): // ATTIVITA - widgets register_sidebar( array ( 'name' => __( 'ATTIVITA prenotabili', 'your-theme-domain' ), 'id' => '<div id="testimonial-slider">', 'description' => __( 'ATTIVITA prenotabili', 'your-theme-domain' ), 'before_widget' => '<div class="widget-content">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); //fine ``` I would like to wrap it into a Do you think could it be possible? Many thanks.
    ``` <link href="style.css" rel="stylesheet"> ``` ***Because you're using relative URLs.*** When you are on `example.com` it will load `example.com/style.css` When you are on `example.com/test` it will load `example.com/test/style.css` etc etc As you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead. --- Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.
    397,668
    <p>I am having a bit of a weird glitch happening to me and I am not sure how I have produced it or whether it is the norm.</p> <p>I am developing my own plugin and when a football/soccer team is typed into a box it will check if its in the database already or not.</p> <p>Here are my lines of code</p> <pre><code>add_action( 'admin_footer', 'fws_teamcheck_javascript' ); function fws_teamcheck_javascript() { ?&gt; &lt;script type=&quot;text/javascript&quot;&gt; jQuery(document).on('focusout', '.name', function () { var name = this.value; //alert(name); jQuery.ajax({ type: 'POST', url: ajaxurl, data: {&quot;action&quot;: &quot;fws_check_name&quot;, &quot;name&quot;: name}, success: function (data) { alert(data); if(data=='true') { $(&quot;.name&quot;).css(&quot;border&quot;, &quot;solid 1px red&quot;); } if(data=='false') { $(&quot;.name&quot;).css(&quot;border&quot;, &quot;solid 1px green&quot;); } } }); }); &lt;/script&gt; &lt;? } function fws_check_name(){ global $wpdb; $dbtable = $wpdb-&gt;prefix . 'fws_team_data'; $name = $_POST['name']; $data = $wpdb-&gt;get_results($wpdb-&gt;prepare(&quot;SELECT * FROM $dbtable WHERE name = $name&quot;)); if($data) { echo 'true'; }else{ echo 'false'; } } add_action( 'wp_ajax_fws_check_name', 'fws_check_name' ); add_action( 'wp_ajax_nopriv_fws_check_name', 'fws_check_name' ); </code></pre> <p>When i move away from the input it will bring up the alert as either <code>true0</code> or <code>false0</code> is there a reason why it is adding the 0 at the end?</p> <p>Thanks for your input.</p>
    [ { "answer_id": 397572, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><em><strong>Because you're using relative URLs.</strong></em></p>\n<p>When you are on <code>example.com</code> it will load <code>example.com/style.css</code></p>\n<p>When you are on <code>example.com/test</code> it will load <code>example.com/test/style.css</code> etc etc</p>\n<p>As you move around the site, it will change where it's looking. None of your pages ever referenced your <code>style.css</code>, it's probably returning an empty 404 page instead.</p>\n<hr />\n<p>Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.</p>\n" }, { "answer_id": 397576, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": 2, "selected": false, "text": "<p>As stated, <code>href=&quot;style.css&quot;</code> is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.</p>\n<p>So in your contexts, that would be:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><code>get_stylesheet_uri()</code> will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it <code>style.css</code>.</p>\n<p>But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your <code>header.php</code> file, you'd enqueue in your <code>functions.php</code> file like this:</p>\n<pre><code>function my_custom_enqueue_function(){\n wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n</code></pre>\n<p>There are more attributes, not in that example, to the <code>wp_enqueue_style()</code> function that make it even more useful, so it's worth looking up and getting to know.</p>\n" }, { "answer_id": 397578, "author": "Majid A.", "author_id": 214325, "author_profile": "https://wordpress.stackexchange.com/users/214325", "pm_score": 0, "selected": false, "text": "<p>Check this:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p>If your <code>style.css</code> file on the theme's root directory.</p>\n" } ]
    2021/11/03
    [ "https://wordpress.stackexchange.com/questions/397668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214284/" ]
    I am having a bit of a weird glitch happening to me and I am not sure how I have produced it or whether it is the norm. I am developing my own plugin and when a football/soccer team is typed into a box it will check if its in the database already or not. Here are my lines of code ``` add_action( 'admin_footer', 'fws_teamcheck_javascript' ); function fws_teamcheck_javascript() { ?> <script type="text/javascript"> jQuery(document).on('focusout', '.name', function () { var name = this.value; //alert(name); jQuery.ajax({ type: 'POST', url: ajaxurl, data: {"action": "fws_check_name", "name": name}, success: function (data) { alert(data); if(data=='true') { $(".name").css("border", "solid 1px red"); } if(data=='false') { $(".name").css("border", "solid 1px green"); } } }); }); </script> <? } function fws_check_name(){ global $wpdb; $dbtable = $wpdb->prefix . 'fws_team_data'; $name = $_POST['name']; $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM $dbtable WHERE name = $name")); if($data) { echo 'true'; }else{ echo 'false'; } } add_action( 'wp_ajax_fws_check_name', 'fws_check_name' ); add_action( 'wp_ajax_nopriv_fws_check_name', 'fws_check_name' ); ``` When i move away from the input it will bring up the alert as either `true0` or `false0` is there a reason why it is adding the 0 at the end? Thanks for your input.
    ``` <link href="style.css" rel="stylesheet"> ``` ***Because you're using relative URLs.*** When you are on `example.com` it will load `example.com/style.css` When you are on `example.com/test` it will load `example.com/test/style.css` etc etc As you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead. --- Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.
    397,814
    <p>I have 4 roles in my platform : administrator, author, editor, external</p> <p>I need to restrict WordPress media library access to the user’s own uploads only for one users role (<strong>external</strong>) on my platform. <strong>The External user role can only see/select his own media</strong>.</p> <p>All others roles still have access to all medias in the library.</p> <p>I found the below snippets but it works for all the users :</p> <pre><code>&lt;?php // Limit access to media library (users can only see/select own media) // add_filter( 'ajax_query_attachments_args', 'wpsnippet_show_current_user_attachments' ); function wpsnippet_show_current_user_attachments( $query ) { $user_id = get_current_user_id(); if ( $user_id &amp;&amp; !current_user_can('activate_plugins') &amp;&amp; !current_user_can('edit_others_posts')) { $query['author'] = $user_id; } return $query; } ?&gt; </code></pre> <p>Thanks in advance for your reply.</p>
    [ { "answer_id": 397572, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><em><strong>Because you're using relative URLs.</strong></em></p>\n<p>When you are on <code>example.com</code> it will load <code>example.com/style.css</code></p>\n<p>When you are on <code>example.com/test</code> it will load <code>example.com/test/style.css</code> etc etc</p>\n<p>As you move around the site, it will change where it's looking. None of your pages ever referenced your <code>style.css</code>, it's probably returning an empty 404 page instead.</p>\n<hr />\n<p>Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.</p>\n" }, { "answer_id": 397576, "author": "StudioAl", "author_id": 37377, "author_profile": "https://wordpress.stackexchange.com/users/37377", "pm_score": 2, "selected": false, "text": "<p>As stated, <code>href=&quot;style.css&quot;</code> is the problem. But it's probably worth pointing out that, in Wordpress your best approach to link to the file is to use its built-in functions to point to the stylesheet, even if your server file structure or domain name changes.</p>\n<p>So in your contexts, that would be:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_uri();?&gt;&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p><code>get_stylesheet_uri()</code> will return the full path to your stylesheet, assuming you've placed it in the top-leve of your theme folder and named it <code>style.css</code>.</p>\n<p>But, in Wordpress, the best practice would be to enqueue the stylesheet, instead, so that Wordpress knows it's being called and can call its dependencies, and other styles dependent on it can also be called. In this case, rather than actually including the code in your <code>header.php</code> file, you'd enqueue in your <code>functions.php</code> file like this:</p>\n<pre><code>function my_custom_enqueue_function(){\n wp_enqueue_style('my-style', get_stylesheet_uri());\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_enqueue_function' );\n</code></pre>\n<p>There are more attributes, not in that example, to the <code>wp_enqueue_style()</code> function that make it even more useful, so it's worth looking up and getting to know.</p>\n" }, { "answer_id": 397578, "author": "Majid A.", "author_id": 214325, "author_profile": "https://wordpress.stackexchange.com/users/214325", "pm_score": 0, "selected": false, "text": "<p>Check this:</p>\n<pre><code>&lt;link href=&quot;&lt;?php echo get_stylesheet_directory_uri();?&gt;/style.css&quot; rel=&quot;stylesheet&quot;&gt;\n</code></pre>\n<p>If your <code>style.css</code> file on the theme's root directory.</p>\n" } ]
    2021/11/07
    [ "https://wordpress.stackexchange.com/questions/397814", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119785/" ]
    I have 4 roles in my platform : administrator, author, editor, external I need to restrict WordPress media library access to the user’s own uploads only for one users role (**external**) on my platform. **The External user role can only see/select his own media**. All others roles still have access to all medias in the library. I found the below snippets but it works for all the users : ``` <?php // Limit access to media library (users can only see/select own media) // add_filter( 'ajax_query_attachments_args', 'wpsnippet_show_current_user_attachments' ); function wpsnippet_show_current_user_attachments( $query ) { $user_id = get_current_user_id(); if ( $user_id && !current_user_can('activate_plugins') && !current_user_can('edit_others_posts')) { $query['author'] = $user_id; } return $query; } ?> ``` Thanks in advance for your reply.
    ``` <link href="style.css" rel="stylesheet"> ``` ***Because you're using relative URLs.*** When you are on `example.com` it will load `example.com/style.css` When you are on `example.com/test` it will load `example.com/test/style.css` etc etc As you move around the site, it will change where it's looking. None of your pages ever referenced your `style.css`, it's probably returning an empty 404 page instead. --- Instead enqueue it properly with a full absolute URL that points to your theme, instead of using a relative URL in a hardcoded link tag.
    397,860
    <p>Not sure the best way to describe this, but basically I am defining a variable ($cat) which chooses a taxonomy based on a number defined just before the query is called, but as the number is defined AFTER the args I can't figure out how to get it to work. I know I could just duplicate the whole query for each taxonomy I want, but I was hoping there was a less character-heavy way to do this.</p> <p>Current code:</p> <pre><code>//cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage) if ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; } if ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; } if ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; } if ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; } if ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; } if ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; } if ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; } if ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; } if ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; } if ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; } if ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; } if ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; } if ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; } //that 'get_option' outputs as the plain ID of the taxonomy //args &amp; query $args_cat = array( 'post_type' =&gt; $post_types, 'posts_per_page' =&gt; 3, 'fields' =&gt; 'ids', 'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ), 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'sector', 'field' =&gt; 'id', 'terms' =&gt; $sector ) ) ); $cat_query = new WP_Query( $args_cat ); //choosing the category and hoping to run the query with it (not working) $cat = 1; while ( $cat_query-&gt;have_posts() ) { $cat_query-&gt;the_post(); get_template_part( 'template-parts/posts/content', get_post_type() ); wp_reset_postdata(); } </code></pre> <p>So it's like I'm wanting it to go back up to the top of the page and choose the cat based on the number, then run the query with that option, but I just can't figure it out. Running it as-is returns 'terms' =&gt; NULL. Do I need a reset or a return or something?</p> <p>Any help greatly appreciated.</p> <p>By the way, I know I could do it like this for each tax/query:</p> <pre><code>$sector = get_option('b4_settings_homepage_category_1')[0]; $args_cat = array( 'post_type' =&gt; $post_types, 'posts_per_page' =&gt; 3, 'fields' =&gt; 'ids', 'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ), 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'sector', 'field' =&gt; 'id', 'terms' =&gt; $sector ) ) ); $cat_query = new WP_Query( $args_cat ); while ( $cat_query-&gt;have_posts() ) { $cat_query-&gt;the_post(); etc etc </code></pre> <p>But I really don't want to have that query replicated a bunch of times if it can be avoided...</p>
    [ { "answer_id": 397864, "author": "Peter Petrov", "author_id": 124071, "author_profile": "https://wordpress.stackexchange.com/users/124071", "pm_score": 0, "selected": false, "text": "<p>To reduce code repetition, you could introduce a function. The below code example is a reworked version of the code you provided, but it uses a function. If you want to use this for category <code>2</code>, simply call the function with the argument <code>2</code>.</p>\n<p>Please note, that you'll need to declare the variables you're using at the beginning of the function. Also - the <code>get_option</code> function, could return more than just an array, which would cause a notice.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$cat_query = prefix_get_wp_query(1);\nwhile ( $cat_query-&gt;have_posts() ) {\n $cat_query-&gt;the_post();\n get_template_part( 'template-parts/posts/content', get_post_type() );\n wp_reset_postdata();\n}\n\nfunction prefix_get_wp_query( $cat ) {\n // declare $post_types, $feat_ids, $latest_ids and $trend_ids below this line\n\n //cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage)\n if ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; }\n if ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; }\n if ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; }\n if ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; }\n if ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; }\n if ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; }\n if ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; }\n if ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; }\n if ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; }\n if ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; }\n if ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; }\n if ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; }\n if ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; }\n //that 'get_option' outputs as the plain ID of the taxonomy\n\n //args &amp; query\n $args_cat = array(\n 'post_type' =&gt; $post_types,\n 'posts_per_page' =&gt; 3,\n 'fields' =&gt; 'ids',\n 'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'sector',\n 'field' =&gt; 'id',\n 'terms' =&gt; $sector\n )\n )\n );\n\n return new WP_Query( $args_cat );\n}\n</code></pre>\n" }, { "answer_id": 397990, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>if your second code works correctly, just do this</p>\n<pre class=\"lang-php prettyprint-override\"><code>$option = &quot;b4_settings_homepage_category_&quot;.$cat;\n$sector = get_option($option)[0];\n</code></pre>\n<p>this will make your option with the cat variable, for example b4_settings_homepage_category_7 , is the same as the if statment but more elegant. also your first code probably isnt working just because the $cat variable should be before the if statments, not after.</p>\n<p>so the inteire code should be:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$cat = 7;\n$option = &quot;b4_settings_homepage_category_&quot;.$cat;\n$sector = get_option($option)[0];\n$args_cat = array(\n 'post_type' =&gt; $post_types,\n 'posts_per_page' =&gt; 3,\n 'fields' =&gt; 'ids',\n 'post__not_in' =&gt; array( $feat_ids, $latest_ids, $trend_ids ),\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'sector',\n 'field' =&gt; 'id',\n 'terms' =&gt; $sector\n )\n )\n);\n$cat_query = new WP_Query( $args_cat );\nwhile ( $cat_query-&gt;have_posts() ) {\n $cat_query-&gt;the_post();\n // etc etc\n}\n</code></pre>\n" }, { "answer_id": 398002, "author": "ukijake", "author_id": 214570, "author_profile": "https://wordpress.stackexchange.com/users/214570", "pm_score": 2, "selected": true, "text": "<p>Combining Petar's function and Tiago's shortened option syntax, this works:</p>\n<p>In template:</p>\n<pre><code>//once, in header:\n$i = 0;\n\n//anytime I want to run the query:\n$i++;\n$cat_query = prefix_get_wp_query($i);\n while ( $cat_query-&gt;have_posts() ) {\n $cat_query-&gt;the_post();\n get_template_part( 'template-parts/posts/content', get_post_type() );\n wp_reset_postdata();\n}\n</code></pre>\n<p>In functions:</p>\n<pre><code>function prefix_get_wp_query( $i ) {\n if ( $i &gt; 0 ) { \n $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n $sector = get_option($cat)[0];\n }\n $cat_args = [\n 'post_type' =&gt; $post_types,\n 'posts_per_page' =&gt; 3,\n 'fields' =&gt; 'ids',\n 'post__not_in' =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n 'tax_query' =&gt; [\n 'relation' =&gt; 'AND',\n [ 'taxonomy' =&gt; 'sector',\n 'field' =&gt; 'id',\n 'terms' =&gt; $sector\n ]\n ]\n ];\n return new WP_Query( $cat_args );\n}\n</code></pre>\n<p>Thanks very much!!</p>\n" }, { "answer_id": 398006, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>your right answer could find an issue, when $i is less or equal to zero will trow an error, that $sector is being used by the first time, so one way to prevent that is</p>\n<pre class=\"lang-php prettyprint-override\"><code>function prefix_get_wp_query( $i ) {\n if ( $i &gt; 0 ) { \n $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n $sector = get_option($cat)[0];\n $cat_args = [\n 'post_type' =&gt; $post_types,\n 'posts_per_page' =&gt; 3,\n 'fields' =&gt; 'ids',\n 'post__not_in' =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n 'tax_query' =&gt; [\n 'relation' =&gt; 'AND',\n [ 'taxonomy' =&gt; 'sector',\n 'field' =&gt; 'id',\n 'terms' =&gt; $sector\n ]\n ]\n ];\n return new WP_Query( $cat_args );\n } else {\n return 0;\n }\n}\n</code></pre>\n<p>if you know it will always be greater than 0, the if can be simply removed</p>\n<pre class=\"lang-php prettyprint-override\"><code>function prefix_get_wp_query( $i ) {\n $cat = &quot;b4_settings_homepage_category_&quot;.$i;\n $sector = get_option($cat)[0];\n $cat_args = [\n 'post_type' =&gt; $post_types,\n 'posts_per_page' =&gt; 3,\n 'fields' =&gt; 'ids',\n 'post__not_in' =&gt; [ $feat_ids, $latest_ids, $trend_ids ],\n 'tax_query' =&gt; [\n 'relation' =&gt; 'AND',\n [ 'taxonomy' =&gt; 'sector',\n 'field' =&gt; 'id',\n 'terms' =&gt; $sector\n ]\n ]\n ];\n return new WP_Query( $cat_args );\n}\n</code></pre>\n" } ]
    2021/11/08
    [ "https://wordpress.stackexchange.com/questions/397860", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214570/" ]
    Not sure the best way to describe this, but basically I am defining a variable ($cat) which chooses a taxonomy based on a number defined just before the query is called, but as the number is defined AFTER the args I can't figure out how to get it to work. I know I could just duplicate the whole query for each taxonomy I want, but I was hoping there was a less character-heavy way to do this. Current code: ``` //cat changer (using a settings page so non-dev colleagues can switch taxonomies on the homepage) if ( $cat == 1 ) { $sector = get_option('b4_settings_homepage_category_1')[0]; } if ( $cat == 2 ) { $sector = get_option('b4_settings_homepage_category_2')[0]; } if ( $cat == 3 ) { $sector = get_option('b4_settings_homepage_category_3')[0]; } if ( $cat == 4 ) { $sector = get_option('b4_settings_homepage_category_4')[0]; } if ( $cat == 5 ) { $sector = get_option('b4_settings_homepage_category_5')[0]; } if ( $cat == 6 ) { $sector = get_option('b4_settings_homepage_category_6')[0]; } if ( $cat == 8 ) { $sector = get_option('b4_settings_homepage_category_7')[0]; } if ( $cat == 9 ) { $sector = get_option('b4_settings_homepage_category_8')[0]; } if ( $cat == 10 ) { $sector = get_option('b4_settings_homepage_category_9')[0]; } if ( $cat == 11 ) { $sector = get_option('b4_settings_homepage_category_10')[0]; } if ( $cat == 12 ) { $sector = get_option('b4_settings_homepage_category_11')[0]; } if ( $cat == 13 ) { $sector = get_option('b4_settings_homepage_category_12')[0]; } if ( $cat == 14 ) { $sector = get_option('b4_settings_homepage_category_13')[0]; } //that 'get_option' outputs as the plain ID of the taxonomy //args & query $args_cat = array( 'post_type' => $post_types, 'posts_per_page' => 3, 'fields' => 'ids', 'post__not_in' => array( $feat_ids, $latest_ids, $trend_ids ), 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'sector', 'field' => 'id', 'terms' => $sector ) ) ); $cat_query = new WP_Query( $args_cat ); //choosing the category and hoping to run the query with it (not working) $cat = 1; while ( $cat_query->have_posts() ) { $cat_query->the_post(); get_template_part( 'template-parts/posts/content', get_post_type() ); wp_reset_postdata(); } ``` So it's like I'm wanting it to go back up to the top of the page and choose the cat based on the number, then run the query with that option, but I just can't figure it out. Running it as-is returns 'terms' => NULL. Do I need a reset or a return or something? Any help greatly appreciated. By the way, I know I could do it like this for each tax/query: ``` $sector = get_option('b4_settings_homepage_category_1')[0]; $args_cat = array( 'post_type' => $post_types, 'posts_per_page' => 3, 'fields' => 'ids', 'post__not_in' => array( $feat_ids, $latest_ids, $trend_ids ), 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'sector', 'field' => 'id', 'terms' => $sector ) ) ); $cat_query = new WP_Query( $args_cat ); while ( $cat_query->have_posts() ) { $cat_query->the_post(); etc etc ``` But I really don't want to have that query replicated a bunch of times if it can be avoided...
    Combining Petar's function and Tiago's shortened option syntax, this works: In template: ``` //once, in header: $i = 0; //anytime I want to run the query: $i++; $cat_query = prefix_get_wp_query($i); while ( $cat_query->have_posts() ) { $cat_query->the_post(); get_template_part( 'template-parts/posts/content', get_post_type() ); wp_reset_postdata(); } ``` In functions: ``` function prefix_get_wp_query( $i ) { if ( $i > 0 ) { $cat = "b4_settings_homepage_category_".$i; $sector = get_option($cat)[0]; } $cat_args = [ 'post_type' => $post_types, 'posts_per_page' => 3, 'fields' => 'ids', 'post__not_in' => [ $feat_ids, $latest_ids, $trend_ids ], 'tax_query' => [ 'relation' => 'AND', [ 'taxonomy' => 'sector', 'field' => 'id', 'terms' => $sector ] ] ]; return new WP_Query( $cat_args ); } ``` Thanks very much!!
    397,862
    <p>When WordPress is installed, it sends a notification</p> <pre><code>New WordPress Site Your new WordPress site has been successfully set up at: ... </code></pre> <p>I would like to change the text of the e-mail but am not successfull. Here is what I tried:</p> <p>I added the following code to the main file of a plugin which I add before the installation</p> <pre><code>function changed_install_mail($installed_email, $user, $blog_title, $blog_url, $password ) { $installed_email['subject'] = 'test'; return $installed_email; } add_filter( 'wp_installed_email', 'changed_install_mail', 10, 5 ); </code></pre> <p>I tried to play around with the priority, but the filter never gets added. But other code in this plugin file is executed.</p> <p>This filter gets applied in upgrade.php</p> <pre><code>$installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password ); </code></pre> <p>Maybe it's the wrong time or wrong location I'm trying it?</p>
    [ { "answer_id": 397988, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php</p>\n" }, { "answer_id": 398046, "author": "parvaneh", "author_id": 132518, "author_profile": "https://wordpress.stackexchange.com/users/132518", "pm_score": 3, "selected": true, "text": "<p>I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\n<a href=\"https://wordpress.org/support/article/must-use-plugins/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/must-use-plugins/</a>\nThis did the trick.</p>\n" } ]
    2021/11/08
    [ "https://wordpress.stackexchange.com/questions/397862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132518/" ]
    When WordPress is installed, it sends a notification ``` New WordPress Site Your new WordPress site has been successfully set up at: ... ``` I would like to change the text of the e-mail but am not successfull. Here is what I tried: I added the following code to the main file of a plugin which I add before the installation ``` function changed_install_mail($installed_email, $user, $blog_title, $blog_url, $password ) { $installed_email['subject'] = 'test'; return $installed_email; } add_filter( 'wp_installed_email', 'changed_install_mail', 10, 5 ); ``` I tried to play around with the priority, but the filter never gets added. But other code in this plugin file is executed. This filter gets applied in upgrade.php ``` $installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password ); ``` Maybe it's the wrong time or wrong location I'm trying it?
    I found a solution: mu-plugins. My code isn't executed in this early state, but that's what mu-plugins are for. <https://wordpress.org/support/article/must-use-plugins/> This did the trick.
    397,873
    <p>I'm taking a Udemy class to learn how to make Wordpress plugins and themes. The video I'm on is having me override the default search widget with a custom one via searchform.php. From what I've gathered, this file should automatically be loaded with the rest of the theme as long as I have followed these steps:</p> <p>/theme_dir/functions.php</p> <pre><code>/* Some other code */ include ( get_theme_file_path('/includes/widgets.php') ); add_action(&quot;widgets_init&quot;, 'ju_widgets'); </code></pre> <p>/theme_dir/includes/widgets.php</p> <pre><code>function ju_widgets() { register_sidebar([ 'name' =&gt; __('My First Theme Sidebar', 'udemy'), 'id' =&gt; 'ju_sidebar', 'description' =&gt; __('Sidebar for the theme Udemy', 'udemy'), 'before_widget' =&gt; '&lt;div id=&quot;%1$s&quot; class=&quot;widget clearfix %2$s&quot;&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;', ]); } </code></pre> <p>/theme_dir/sidebar.php</p> <pre><code>&lt;div class=&quot;sidebar nobottommargin col_last&quot;&gt; &lt;div class=&quot;sidebar-widgets-wrap&quot;&gt; &lt;?php if (is_active_sidebar('ju_sidebar')) { dynamic_sidebar('ju_sidebar'); } ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>/theme_dir/searchform.php</p> <pre><code>&lt;?php $unique_id = esc_attr( uniqid( 'search-form-' ) ); ?&gt; &lt;form role=&quot;search&quot; method=&quot;get&quot; class=&quot;search-form&quot; action=&quot;&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;&quot;&gt; &lt;div class=&quot;input-group&quot;&gt; &lt;input type=&quot;search&quot; id=&quot;&lt;?php echo $unique_id; ?&gt;&quot; class=&quot;form-control&quot; name=&quot;s&quot; value=&quot;&lt;?php the_search_query(); ?&gt;&quot; placeholder=&quot;&lt;?php _e( 'Search', 'udemy' ); ?&gt;&quot;/&gt; &lt;span class=&quot;input-group-btn&quot;&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot;&gt;&lt;i class=&quot;icon-search&quot;&gt;&lt;/i&gt;&lt;/button&gt; &lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>/theme_dir/index.php</p> <pre><code>&lt;!-- some theme html --&gt; &lt;?php get_sidebar(); ?&gt; &lt;!-- other theme html --&gt; </code></pre> <p>No matter what I change in the searchform.php file, it doesn't replace the default search widget.</p>
    [ { "answer_id": 397988, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>just an opinium, each wordpress plataform is only instaled one time, and each time only the email registered will receive the email. Not my business, but isnt this worthless, if the person is installing wordpress, he knows the wordpress is being installed. if some other email is being their instead of the one who is installing it, why just not send a personal email giving the information.\nAlso if you personalize one wordpress files to do so, you will need to use that files always you install a new wordpress. Also update your files each time wordpress has a new release/update.\nI must confess, I have installed a few and never had receive such email. And for the email to work always had to put some code on the theme functions.php</p>\n" }, { "answer_id": 398046, "author": "parvaneh", "author_id": 132518, "author_profile": "https://wordpress.stackexchange.com/users/132518", "pm_score": 3, "selected": true, "text": "<p>I found a solution:\nmu-plugins.\nMy code isn't executed in this early state, but that's what mu-plugins are for.\n<a href=\"https://wordpress.org/support/article/must-use-plugins/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/must-use-plugins/</a>\nThis did the trick.</p>\n" } ]
    2021/11/08
    [ "https://wordpress.stackexchange.com/questions/397873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214581/" ]
    I'm taking a Udemy class to learn how to make Wordpress plugins and themes. The video I'm on is having me override the default search widget with a custom one via searchform.php. From what I've gathered, this file should automatically be loaded with the rest of the theme as long as I have followed these steps: /theme\_dir/functions.php ``` /* Some other code */ include ( get_theme_file_path('/includes/widgets.php') ); add_action("widgets_init", 'ju_widgets'); ``` /theme\_dir/includes/widgets.php ``` function ju_widgets() { register_sidebar([ 'name' => __('My First Theme Sidebar', 'udemy'), 'id' => 'ju_sidebar', 'description' => __('Sidebar for the theme Udemy', 'udemy'), 'before_widget' => '<div id="%1$s" class="widget clearfix %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4>', 'after_title' => '</h4>', ]); } ``` /theme\_dir/sidebar.php ``` <div class="sidebar nobottommargin col_last"> <div class="sidebar-widgets-wrap"> <?php if (is_active_sidebar('ju_sidebar')) { dynamic_sidebar('ju_sidebar'); } ?> </div> </div> ``` /theme\_dir/searchform.php ``` <?php $unique_id = esc_attr( uniqid( 'search-form-' ) ); ?> <form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div class="input-group"> <input type="search" id="<?php echo $unique_id; ?>" class="form-control" name="s" value="<?php the_search_query(); ?>" placeholder="<?php _e( 'Search', 'udemy' ); ?>"/> <span class="input-group-btn"> <button type="submit" class="btn btn-danger"><i class="icon-search"></i></button> </span> </div> </form> ``` /theme\_dir/index.php ``` <!-- some theme html --> <?php get_sidebar(); ?> <!-- other theme html --> ``` No matter what I change in the searchform.php file, it doesn't replace the default search widget.
    I found a solution: mu-plugins. My code isn't executed in this early state, but that's what mu-plugins are for. <https://wordpress.org/support/article/must-use-plugins/> This did the trick.
    397,957
    <p>I have a <code>Quiz</code> block that contains <code>Question</code>s blocks that have <code>Answer</code> blocks. Both <code>Quiz</code> and <code>Question</code> use <code>InnerBlocks</code> to allow questions or answers to be dragged around, edited and saved.</p> <p>When I save the Quiz, how can I get the index of each question in <code>question/save.js</code> and the index of each question and answer in each <code>answer/save.js</code>.</p> <p>I would like this so I can give all checkbox unique ids, like</p> <pre><code>&lt;input id=&quot;q1-a3&quot; /&gt; </code></pre> <p>And label the questions things like &quot;Question 1.&quot;</p> <p>Quiz/save.js</p> <pre><code>return ( &lt;div {...blockProps}&gt; &lt;InnerBlocks.Content /&gt; &lt;/div&gt; ); </code></pre> <p>Question/save.js</p> <pre><code>return ( &lt;div {...blockProps}&gt; &lt;h3&gt;Question {numToWords(1)}&lt;/h3&gt; &lt;ul class=&quot;quiz--answers&quot;&gt; &lt;InnerBlocks.Content /&gt; &lt;/ul&gt; &lt;/div&gt; ); </code></pre> <p>Answer/save.js</p> <pre><code>return ( &lt;li {...blockProps}&gt; &lt;input id=&quot;checkbox-2&quot; type=&quot;checkbox&quot; value=&quot;checkbox-2&quot; /&gt; &lt;label class=&quot;checkbox&quot; for=&quot;checkbox-2&quot;&gt; {JSON.stringify(attributes)} {attributes.text} &lt;span class=&quot;quiz--answer-content&quot;&gt;{attributes.explanation}&lt;/span&gt; &lt;/label&gt; &lt;/li&gt; ); </code></pre> <p>I have tried using <code>getBlockIndex( clientId )</code> to try to get the index of each block, however I'm not sure where to use this as it always returns -1. It also only seems that <code>clientId</code> is available in the edit function, and I think I want it in the save function unless I go about adding it to the block attributes.</p>
    [ { "answer_id": 397966, "author": "shadi", "author_id": 124857, "author_profile": "https://wordpress.stackexchange.com/users/124857", "pm_score": 0, "selected": false, "text": "<p>try saving the values in html data attributes. then get them using <code>getAttribute(&quot;data-index&quot;)</code></p>\n<pre><code>data-index=&quot;number&quot;\n</code></pre>\n<p>usually in save.js you can't use useStates and useEffects. you have to make another file that uses vanilla js to do the logic. save.js is saved as a pure html elements.</p>\n" }, { "answer_id": 398017, "author": "Djave", "author_id": 27866, "author_profile": "https://wordpress.stackexchange.com/users/27866", "pm_score": 0, "selected": false, "text": "<p>The <code>Quiz</code> block was the top level block. So in its Edit function, I created a subscribe method. I was able to <a href=\"https://developer.wordpress.org/block-editor/reference-guides/packages/packages-data/#select\" rel=\"nofollow noreferrer\">select</a> the editor and get the current block:</p>\n<pre><code>// Subscribe to all changes of the Gutenberg blocks\nwp.data.subscribe(() =&gt; {\n const quiz = wp.data.select(&quot;core/editor&quot;).getBlock(clientId);\n triggerUpdate(quiz);\n});\n</code></pre>\n<p>The subscribe method is covered briefly here:</p>\n<p><a href=\"https://www.youtube.com/watch?v=OQczO6VOMkY\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=OQczO6VOMkY</a></p>\n<p>This <code>subscribe()</code> happened to be called thousands of times as the page was edited, so I was unable to work out a better way of working with it than to manually &quot;debounce&quot; it:</p>\n<pre><code>// Debounce that change, so it wouldn't trigger thousands of times\nlet timeouts = [];\n\nconst triggerUpdate = (quiz) =&gt; {\n while (timeouts.length) {\n clearTimeout(timeouts.shift());\n }\n\n const timeout = setTimeout(() =&gt; {\n // ... the code to get the index of each block\n }, 1000);\n timeouts.push(timeout);\n};\n</code></pre>\n<p>Now I had a function triggering every time I updated the post, I just needed to actually get the indexes. This was easily done by using <code>.innerBlocks</code>, once on the <code>quiz</code> (which I'd already got by using <code>wp.data.select(&quot;core/editor&quot;).getBlock(clientId)</code>) and then once on each <code>question</code>.</p>\n<p>With that, I could loop through each block and update its attributes using <a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-block-editor/#updateblockattributes\" rel=\"nofollow noreferrer\">updateBlockAttributes</a></p>\n<pre><code>// Loop through all nested blocks and update relevant attributes\nquiz.innerBlocks.forEach((question, q) =&gt; {\n let qid = &quot;q&quot; + (q + 1); // qid = &quot;q1&quot;, &quot;q2&quot; etc\n if (question.attributes.qid != qid) {\n const update = {\n qid,\n questionTitle: &quot;Question &quot; + numToWords(parseInt(q + 1)),\n };\n console.log(update);\n dispatch(&quot;core/editor&quot;).updateBlockAttributes(\n question.clientId,\n update\n );\n }\n question.innerBlocks.forEach((answer, a) =&gt; {\n let aid = qid + &quot;a&quot; + (a + 1); // aid = &quot;q1a2&quot; etc\n if (answer.attributes.qid != qid) {\n dispatch(&quot;core/editor&quot;).updateBlockAttributes(answer.clientId, {\n aid,\n });\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 404854, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 2, "selected": true, "text": "<p>You may now retrieve the index of a inner block via the <code>core/block-editor</code> data module. You may pair it with the <code>useSelect</code> hook to keep the indexes up to date on changes.</p>\n<p>Something like this. <em>Intentionally verbose for clarity.</em></p>\n<pre><code>import {useSelect} from '@wordpress/data';\n\nconst Answer = ( blockProps ) =&gt; {\n const {index} = useSelect( select =&gt; {\n const {getBlockIndex} = select( 'core/block-editor' );\n return {\n index: getBlockIndex( blockProps.clientId );\n }\n } );\n\n return ( &lt;li {...blockProps}&gt;\n &lt;input id=&quot;checkbox-2&quot; type=&quot;checkbox&quot; value=&quot;checkbox-2&quot; /&gt;\n &lt;label className=&quot;checkbox&quot; htmlFor=&quot;checkbox-2&quot;&gt;\n {JSON.stringify( blockProps.attributes )}\n {index}\n &lt;span className=&quot;quiz--answer-content&quot;&gt;{blockProps.attributes.explanation}&lt;/span&gt;\n &lt;/label&gt;\n &lt;/li&gt; );\n}\n\n</code></pre>\n" } ]
    2021/11/10
    [ "https://wordpress.stackexchange.com/questions/397957", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27866/" ]
    I have a `Quiz` block that contains `Question`s blocks that have `Answer` blocks. Both `Quiz` and `Question` use `InnerBlocks` to allow questions or answers to be dragged around, edited and saved. When I save the Quiz, how can I get the index of each question in `question/save.js` and the index of each question and answer in each `answer/save.js`. I would like this so I can give all checkbox unique ids, like ``` <input id="q1-a3" /> ``` And label the questions things like "Question 1." Quiz/save.js ``` return ( <div {...blockProps}> <InnerBlocks.Content /> </div> ); ``` Question/save.js ``` return ( <div {...blockProps}> <h3>Question {numToWords(1)}</h3> <ul class="quiz--answers"> <InnerBlocks.Content /> </ul> </div> ); ``` Answer/save.js ``` return ( <li {...blockProps}> <input id="checkbox-2" type="checkbox" value="checkbox-2" /> <label class="checkbox" for="checkbox-2"> {JSON.stringify(attributes)} {attributes.text} <span class="quiz--answer-content">{attributes.explanation}</span> </label> </li> ); ``` I have tried using `getBlockIndex( clientId )` to try to get the index of each block, however I'm not sure where to use this as it always returns -1. It also only seems that `clientId` is available in the edit function, and I think I want it in the save function unless I go about adding it to the block attributes.
    You may now retrieve the index of a inner block via the `core/block-editor` data module. You may pair it with the `useSelect` hook to keep the indexes up to date on changes. Something like this. *Intentionally verbose for clarity.* ``` import {useSelect} from '@wordpress/data'; const Answer = ( blockProps ) => { const {index} = useSelect( select => { const {getBlockIndex} = select( 'core/block-editor' ); return { index: getBlockIndex( blockProps.clientId ); } } ); return ( <li {...blockProps}> <input id="checkbox-2" type="checkbox" value="checkbox-2" /> <label className="checkbox" htmlFor="checkbox-2"> {JSON.stringify( blockProps.attributes )} {index} <span className="quiz--answer-content">{blockProps.attributes.explanation}</span> </label> </li> ); } ```
    397,962
    <p>I have a custom field for view counts that are stored as numbers. I added a Views column, and made it sortable, but they are not sorting properly.</p> <p>The results when I click on the Views column are something like this:</p> <pre><code>Views ===== 1900 10992 10004 280 18 4015 ... </code></pre> <p>Here is my code:</p> <pre><code>/** * Add view counts to admin columns */ add_filter( 'manage_posts_columns', 'eri_posts_column_views' ); function eri_posts_column_views( $columns ) { $columns['post_views'] = 'Views'; return $columns; } add_action( 'manage_posts_custom_column', 'eri_posts_custom_column_views' ); function eri_posts_custom_column_views( $column ) { if ( $column === 'post_views') { $post_id = get_the_ID(); $meta_key = 'eri_post_view_count'; $count = 0; if (get_post_meta( $post_id, $meta_key, true ) &amp;&amp; get_post_meta( $post_id, $meta_key, true ) != '') { $count = get_post_meta( $post_id, $meta_key, true ); } echo $count; } } /** * Make admin columns sortable */ add_filter('manage_edit-post_sortable_columns', 'eri_view_count_sortable_column'); function eri_view_count_sortable_column($columns){ $columns['post_views'] = 'post_views'; return $columns; } add_action( 'pre_get_posts', 'eri_view_count_custom_orderby' ); function eri_view_count_custom_orderby( $query ) { if( ! is_admin() ) return; $orderby = $query-&gt;get( 'orderby'); if( 'post_views' == $orderby ) { $query-&gt;set('meta_key','eri_post_view_count'); $query-&gt;set('orderby','meta_value_num'); } } </code></pre> <p>I've tried changing <code>meta_value_num</code> to <code>meta_value</code>... not working.</p>
    [ { "answer_id": 397999, "author": "ZealousWeb", "author_id": 70780, "author_profile": "https://wordpress.stackexchange.com/users/70780", "pm_score": -1, "selected": false, "text": "<p>Can you please set query as per below code?</p>\n<pre><code>$query-&gt;set('orderby','meta_value meta_value_num');\n</code></pre>\n<p>or below:</p>\n<pre><code>$query-&gt;set('orderby','meta_value');\n</code></pre>\n" }, { "answer_id": 398016, "author": "Michael", "author_id": 42925, "author_profile": "https://wordpress.stackexchange.com/users/42925", "pm_score": 0, "selected": false, "text": "<p>I figured it out after adding the same code to a different site I run. It was working fine on that site with the same theme and mostly the same plugins. I narrowed it down to another function I made (thankfully it wasn't another plugin). The other function was sorting something on the front end, so all I had to do was add <code>if (!is_admin())</code> to that function. So the moral of the story is, I screwed up in a completely different area. :(</p>\n" } ]
    2021/11/10
    [ "https://wordpress.stackexchange.com/questions/397962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42925/" ]
    I have a custom field for view counts that are stored as numbers. I added a Views column, and made it sortable, but they are not sorting properly. The results when I click on the Views column are something like this: ``` Views ===== 1900 10992 10004 280 18 4015 ... ``` Here is my code: ``` /** * Add view counts to admin columns */ add_filter( 'manage_posts_columns', 'eri_posts_column_views' ); function eri_posts_column_views( $columns ) { $columns['post_views'] = 'Views'; return $columns; } add_action( 'manage_posts_custom_column', 'eri_posts_custom_column_views' ); function eri_posts_custom_column_views( $column ) { if ( $column === 'post_views') { $post_id = get_the_ID(); $meta_key = 'eri_post_view_count'; $count = 0; if (get_post_meta( $post_id, $meta_key, true ) && get_post_meta( $post_id, $meta_key, true ) != '') { $count = get_post_meta( $post_id, $meta_key, true ); } echo $count; } } /** * Make admin columns sortable */ add_filter('manage_edit-post_sortable_columns', 'eri_view_count_sortable_column'); function eri_view_count_sortable_column($columns){ $columns['post_views'] = 'post_views'; return $columns; } add_action( 'pre_get_posts', 'eri_view_count_custom_orderby' ); function eri_view_count_custom_orderby( $query ) { if( ! is_admin() ) return; $orderby = $query->get( 'orderby'); if( 'post_views' == $orderby ) { $query->set('meta_key','eri_post_view_count'); $query->set('orderby','meta_value_num'); } } ``` I've tried changing `meta_value_num` to `meta_value`... not working.
    I figured it out after adding the same code to a different site I run. It was working fine on that site with the same theme and mostly the same plugins. I narrowed it down to another function I made (thankfully it wasn't another plugin). The other function was sorting something on the front end, so all I had to do was add `if (!is_admin())` to that function. So the moral of the story is, I screwed up in a completely different area. :(
    397,974
    <p>I have a client who wants to review and revise their Tags and tagging strategy, but they want to start with a spreadsheet of ALL tags, including those that have no posts assigned to them.</p> <p>SO I created a template that outputs the Tags to an HTML Table, that I can then import into Excel and upload to Google Sheets so their team can collaborate on it.</p> <p>The template works great, but the query does not include the empty Tags, even though I have &quot;hide_empty&quot; set to 0 (tried both 'false' and '0' with the same results).</p> <p>I can't use get_terms because that query includes terms added by plugins that are not at all related to Posts nor post_tags, even though when I tried get_terms I added the 'taxonomy' =&gt; post_tag, it still gave me about 400 additional terms that are not Post Tags (they are mostly for CPTs and the like, not Posts).</p> <p>If I use get_tags, I get a clean list of <em>just</em> Post Tags, but it isn't giving me the ones with 0 Posts assigned.</p> <p>Can someone please help me troubleshoot this code?</p> <p>Here is the HTML and query from my Template:</p> <pre><code> &lt;table id=&quot;download&quot;&gt; &lt;tr&gt; &lt;th&gt;Tag Name&lt;/th&gt; &lt;th&gt;Post Count&lt;/th&gt; &lt;/tr&gt; &lt;?php global $wp_query; $tags = get_tags( $args ); $args = array( 'hide_empty' =&gt; 0, ); if ( $tags ) : foreach ( $tags as $tag ) : ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo esc_html( $tag-&gt;name ); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $tag-&gt;count; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; endif; ?&gt; &lt;/table&gt; </code></pre> <p>I know there are quite a lot of Tags in their list that have 0 Posts assigned, I can see them in the WP back end, just can't figure out how to export the entire list to something someone can work with in Excel/Google Sheets....</p>
    [ { "answer_id": 397975, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>Try:</p>\n<pre><code>$args = array( 'hide_empty' =&gt; false );\n$tags = get_tags( $args );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/\" rel=\"nofollow noreferrer\">More info re possible args.</a></p>\n<p>For csv export, you probably want to use <a href=\"https://developer.wordpress.org/reference/functions/get_the_tags/\" rel=\"nofollow noreferrer\">get_the_tags</a></p>\n" }, { "answer_id": 398020, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": -1, "selected": true, "text": "<p>Well this was an odd fix, and one that in theory shouldn't have been necessary, however, what finally worked (to show ALL Tags including those with empty counts) was to specify the taxonomy =&gt; 'post_tag' EVEN THOUGH that is the 'default' parameter and shouldn't need to have been added to $args.</p>\n<p>Sigh.</p>\n<p>My final query that works:</p>\n<pre><code>global $wp_query;\n$tags = get_tags( array(\n 'taxonomy' =&gt; 'post_tag',\n 'hide_empty' =&gt; false,\n )\n);\nif ( $tags ) :\n foreach ( $tags as $tag ) :\n</code></pre>\n" } ]
    2021/11/10
    [ "https://wordpress.stackexchange.com/questions/397974", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56458/" ]
    I have a client who wants to review and revise their Tags and tagging strategy, but they want to start with a spreadsheet of ALL tags, including those that have no posts assigned to them. SO I created a template that outputs the Tags to an HTML Table, that I can then import into Excel and upload to Google Sheets so their team can collaborate on it. The template works great, but the query does not include the empty Tags, even though I have "hide\_empty" set to 0 (tried both 'false' and '0' with the same results). I can't use get\_terms because that query includes terms added by plugins that are not at all related to Posts nor post\_tags, even though when I tried get\_terms I added the 'taxonomy' => post\_tag, it still gave me about 400 additional terms that are not Post Tags (they are mostly for CPTs and the like, not Posts). If I use get\_tags, I get a clean list of *just* Post Tags, but it isn't giving me the ones with 0 Posts assigned. Can someone please help me troubleshoot this code? Here is the HTML and query from my Template: ``` <table id="download"> <tr> <th>Tag Name</th> <th>Post Count</th> </tr> <?php global $wp_query; $tags = get_tags( $args ); $args = array( 'hide_empty' => 0, ); if ( $tags ) : foreach ( $tags as $tag ) : ?> <tr> <td><?php echo esc_html( $tag->name ); ?></td> <td><?php echo $tag->count; ?></td> </tr> <?php endforeach; endif; ?> </table> ``` I know there are quite a lot of Tags in their list that have 0 Posts assigned, I can see them in the WP back end, just can't figure out how to export the entire list to something someone can work with in Excel/Google Sheets....
    Well this was an odd fix, and one that in theory shouldn't have been necessary, however, what finally worked (to show ALL Tags including those with empty counts) was to specify the taxonomy => 'post\_tag' EVEN THOUGH that is the 'default' parameter and shouldn't need to have been added to $args. Sigh. My final query that works: ``` global $wp_query; $tags = get_tags( array( 'taxonomy' => 'post_tag', 'hide_empty' => false, ) ); if ( $tags ) : foreach ( $tags as $tag ) : ```
    398,024
    <p>I am working on a multisite install where one specific site needs to have access restricted to only users who are logged in AND have a specific user meta set (key=&quot;cr_access&quot;, val=&quot;Yes&quot;). If the user is not logged in, or that meta key is not set to &quot;Yes&quot;, then they should be redirected to the specified url.</p> <p>The redirect works properly, however it seems to be getting cached. If a user tries to visit a page before logging in, then logs in and tries again, it is still redirecting them to the set url. If I purge the page and object caches, then the user is able to visit the pages. How can I prevent this from getting cached in the first place?</p> <p>Here is my code:</p> <pre><code>function hwnycr_redirect(){ //only redirect for blog id 10, non-admin, and exclude home/login pages if (!is_front_page() &amp;&amp; !current_user_can( 'edit_posts' ) &amp;&amp; get_current_blog_id() == 10 &amp;&amp; get_the_ID() &lt;&gt; 13) { if(!is_user_logged_in()) { wp_redirect('https://example.com'); exit(); } else { $current_user = wp_get_current_user(); $cr_access = get_user_meta($current_user-&gt;ID, 'cr_access', true); if ($cr_access !== &quot;Yes&quot;) { wp_redirect('https://example.com'); exit(); } } } } add_action( 'template_redirect', 'hwnycr_redirect',1); </code></pre>
    [ { "answer_id": 401005, "author": "Squivo", "author_id": 217626, "author_profile": "https://wordpress.stackexchange.com/users/217626", "pm_score": 0, "selected": false, "text": "<p>Been banging my head against the wall on this one for months. The workaround is to set all the of redirected posts under a common slug and have WPEngine force all urls under that slug ( category ) to never cache.</p>\n" }, { "answer_id": 404855, "author": "badcrocodile", "author_id": 104931, "author_profile": "https://wordpress.stackexchange.com/users/104931", "pm_score": 1, "selected": false, "text": "<p>You should try adding <code>nocache_headers()</code> before you <code>wp_redirect()</code>. It's meant for this exact thing. <a href=\"https://developer.wordpress.org/reference/functions/nocache_headers/\" rel=\"nofollow noreferrer\">From the docs</a>:</p>\n<blockquote>\n<p>Set the headers to prevent caching for the different browsers.</p>\n</blockquote>\n<p>Your scenario was mentioned and addressed in a <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/#comment-3973\" rel=\"nofollow noreferrer\">user contributed note</a> in the WP Code Reference. That's where I picked this technique up from.</p>\n" } ]
    2021/11/11
    [ "https://wordpress.stackexchange.com/questions/398024", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155285/" ]
    I am working on a multisite install where one specific site needs to have access restricted to only users who are logged in AND have a specific user meta set (key="cr\_access", val="Yes"). If the user is not logged in, or that meta key is not set to "Yes", then they should be redirected to the specified url. The redirect works properly, however it seems to be getting cached. If a user tries to visit a page before logging in, then logs in and tries again, it is still redirecting them to the set url. If I purge the page and object caches, then the user is able to visit the pages. How can I prevent this from getting cached in the first place? Here is my code: ``` function hwnycr_redirect(){ //only redirect for blog id 10, non-admin, and exclude home/login pages if (!is_front_page() && !current_user_can( 'edit_posts' ) && get_current_blog_id() == 10 && get_the_ID() <> 13) { if(!is_user_logged_in()) { wp_redirect('https://example.com'); exit(); } else { $current_user = wp_get_current_user(); $cr_access = get_user_meta($current_user->ID, 'cr_access', true); if ($cr_access !== "Yes") { wp_redirect('https://example.com'); exit(); } } } } add_action( 'template_redirect', 'hwnycr_redirect',1); ```
    You should try adding `nocache_headers()` before you `wp_redirect()`. It's meant for this exact thing. [From the docs](https://developer.wordpress.org/reference/functions/nocache_headers/): > > Set the headers to prevent caching for the different browsers. > > > Your scenario was mentioned and addressed in a [user contributed note](https://developer.wordpress.org/reference/functions/wp_redirect/#comment-3973) in the WP Code Reference. That's where I picked this technique up from.
    398,071
    <p>I have a plugin with import</p> <pre><code>import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor'; </code></pre> <p>but it's not working with newest Gutenberg plugin 11.9, because this <code>useInnerBlocksProps</code> is no longer <em>experimental</em></p> <p>so I can use</p> <pre><code>import { useInnerBlocksProps } from '@wordpress/block-editor'; </code></pre> <p>but then it will not work for older versions, or WordPress installation without Gutenberg plugin.</p> <p>What's the correct way to make it compatible with both scenarios? How to import __experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?</p>
    [ { "answer_id": 398086, "author": "KubiQ", "author_id": 128483, "author_profile": "https://wordpress.stackexchange.com/users/128483", "pm_score": 2, "selected": true, "text": "<p>Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;)</p>\n<pre><code>import {\n __experimentalUseInnerBlocksProps,\n useInnerBlocksProps,\n} from '@wordpress/block-editor';\n\nif( typeof useInnerBlocksProps == 'undefined' ){\n var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps;\n}else{\n var compatibleUseInnerBlocksProps = useInnerBlocksProps;\n}\n</code></pre>\n<ul>\n<li>so basically I can import both (experimental and no-experimental) without any error</li>\n<li>then I can just do simple type test if the new one is already supported</li>\n<li>if it's supported I will remember it in <code>compatibleUseInnerBlocksProps</code> variable</li>\n<li>otherwise I will remember old <em>experimental</em></li>\n<li>then I need to replace all other occurrences of <code>useInnerBlocksProps</code> with <code>compatibleUseInnerBlocksProps</code> in my code</li>\n</ul>\n" }, { "answer_id": 407691, "author": "Gchtr", "author_id": 22506, "author_profile": "https://wordpress.stackexchange.com/users/22506", "pm_score": 0, "selected": false, "text": "<p>I used the logic from the <a href=\"https://wordpress.stackexchange.com/a/398086/22506\">accepted answer</a>, which works great.</p>\n<p>But I implemented it a little differently. I import <code>useInnerBlocksProps</code> as <code>nonExperimentalUseInnerBlocksProps</code>. This way, I can keep using <code>useInnerBlocksProps</code> where I use it in the code. This will make it easier to remove support for <code>__experimentalUseInnerBlocksProps</code> in the future.</p>\n<pre class=\"lang-js prettyprint-override\"><code>import {\n useInnerBlocksProps as nonExperimentalUseInnerBlocksProps,\n __experimentalUseInnerBlocksProps,\n} from '@wordpress/block-editor';\n\nconst useInnerBlocksProps =\n typeof nonExperimentalUseInnerBlocksProps == 'undefined'\n ? __experimentalUseInnerBlocksProps\n : nonExperimentalUseInnerBlocksProps;\n</code></pre>\n" } ]
    2021/11/12
    [ "https://wordpress.stackexchange.com/questions/398071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128483/" ]
    I have a plugin with import ``` import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor'; ``` but it's not working with newest Gutenberg plugin 11.9, because this `useInnerBlocksProps` is no longer *experimental* so I can use ``` import { useInnerBlocksProps } from '@wordpress/block-editor'; ``` but then it will not work for older versions, or WordPress installation without Gutenberg plugin. What's the correct way to make it compatible with both scenarios? How to import \_\_experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?
    Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;) ``` import { __experimentalUseInnerBlocksProps, useInnerBlocksProps, } from '@wordpress/block-editor'; if( typeof useInnerBlocksProps == 'undefined' ){ var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps; }else{ var compatibleUseInnerBlocksProps = useInnerBlocksProps; } ``` * so basically I can import both (experimental and no-experimental) without any error * then I can just do simple type test if the new one is already supported * if it's supported I will remember it in `compatibleUseInnerBlocksProps` variable * otherwise I will remember old *experimental* * then I need to replace all other occurrences of `useInnerBlocksProps` with `compatibleUseInnerBlocksProps` in my code
    398,210
    <p>As referenced in this issue ( <a href="https://github.com/WordPress/gutenberg/issues/33374" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg/issues/33374</a>) I want my custom block's innerblocks to have the default layout and alignment controls Like the layout toggle for the Group block, but baked in.</p> <p>It was answered, but I can't figure out the code:</p> <blockquote> <p>you can do it by providing a layout to inner blocks, that said, the feature is still experimental at the moment, you should be able to pass __experimentalLayout ={ { contentSize: '800px', wideSize: '1000px' } } to your inner blocks, you can also pass __experimentalLayout ={ { inherit: true } } to your inner blocks as well to inherit whatever layout is defined.</p> </blockquote> <h1>My code</h1> <pre><code>export default function Edit() { return ( &lt;div {...useBlockProps()}&gt; &lt;InnerBlocks /&gt; &lt;/div&gt; ); } </code></pre> <p>This doesn't work</p> <pre><code>export default function Edit() { return ( &lt;div {...useBlockProps()}&gt; &lt;InnerBlocks __experimentalLayout ={ { inherit: true } } /&gt; &lt;/div&gt; ); } </code></pre> <p>Does it go in supports in block.json?</p> <h1>What I'm trying to do</h1> <p>This issue explains the custom block I'm trying to make. Very simple! But I need innerblocks to have alignment control and you lose that on innerblocks when you use theme.json. <a href="https://github.com/WordPress/gutenberg/issues/36465" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg/issues/36465</a></p> <h1>Updated code</h1> <p>I added this to the block.json, which adds the toggle for default layout, but the innerblocks still don't have full/wide alignment control. Not sure how to do that, but halfway there.</p> <pre><code> &quot;supports&quot;: { &quot;__experimentalLayout&quot;: { &quot;contentSize&quot;: &quot;800px&quot;, &quot;wideSize&quot;: &quot;1000px&quot;, &quot;inherit&quot;: true } }, </code></pre> <h2>Updated code from stokeman's answer</h2> <p>block.json</p> <pre><code>{ &quot;apiVersion&quot;: 2, &quot;name&quot;: &quot;mbp/details&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;title&quot;: &quot;Details&quot;, &quot;category&quot;: &quot;design&quot;, &quot;icon&quot;: &quot;heart&quot;, &quot;supports&quot;: { &quot;align&quot;: [&quot;full&quot;], &quot;__experimentalLayout&quot;: { &quot;allowSwitching&quot;: false, &quot;default&quot;: { &quot;inherit&quot;: true } } }, &quot;attributes&quot;: { &quot;align&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;default&quot;: &quot;full&quot; } }, &quot;textdomain&quot;: &quot;mobilebevpros&quot;, &quot;editorScript&quot;: &quot;file:../../../../build/details.js&quot; } </code></pre> <p>edit.js</p> <pre><code>import { __ } from &quot;@wordpress/i18n&quot;; import { useBlockProps, useSetting, InnerBlocks, } from &quot;@wordpress/block-editor&quot;; export default function Edit() { const defaultLayout = useSetting(&quot;layout&quot;) || {}; return ( &lt;div {...useBlockProps()}&gt; &lt;InnerBlocks __experimentalLayout={defaultLayout} /&gt; &lt;/div&gt; ); } </code></pre>
    [ { "answer_id": 398252, "author": "stokesman", "author_id": 214758, "author_profile": "https://wordpress.stackexchange.com/users/214758", "pm_score": 2, "selected": false, "text": "<p>You're pretty close. Specifying layout details in block.json should nest inside a <code>&quot;default&quot;</code> property. Doing so will have the Layout panel display accordingly but there's more to it than that.</p>\n<p>If you want the default layout for the block, there is no need to add <code>contentSize</code> or <code>wideSize</code>. Here is the layout config I'd recommend (within the block json <code>supports</code> property):</p>\n<pre class=\"lang-js prettyprint-override\"><code> &quot;__experimentalLayout&quot;: {\n &quot;allowSwitching&quot;: false,\n &quot;default&quot;: {\n &quot;inherit&quot;: true\n }\n }\n</code></pre>\n<p>That will make the Layout panel in the block’s sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs.</p>\n<p>Even though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import {\n useBlockProps, // already in use from example\n useSetting // new bit\n} from '@wordpress/block-editor';\n\nexport default function Edit() {\n const defaultLayout = useSetting( 'layout' ) || {};\n return (\n &lt;div {...useBlockProps()}&gt;\n &lt;InnerBlocks __experimentalLayout={ defaultLayout } /&gt;\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p>Besides that the block must be registered on the server but I take it that's already being done.</p>\n<p>I'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site.</p>\n" }, { "answer_id": 398849, "author": "stokesman", "author_id": 214758, "author_profile": "https://wordpress.stackexchange.com/users/214758", "pm_score": 0, "selected": false, "text": "<p>Based on what I understand of what you're trying to do, I think it might be best accomplished by registering a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-variations/\" rel=\"nofollow noreferrer\">block variation</a> for the Group block. It can preset the padding and inheritance of the default layout and has options that can make it appear as its own separate block. This example creates one that will show up in the inserter as &quot;Dat Section&quot; and has some preset padding and a custom class:</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.blocks.registerBlockVariation(\n 'core/group',\n {\n name:'dat-section',\n title: 'Dat Section',\n isActive: (blockAttributes, vAttributes) =&gt;\n blockAttributes.className\n .includes(vAttributes.className),\n attributes: {\n className: 'dat-section',\n layout: {\n inherit: true,\n },\n style:{\n spacing:{\n padding: { top: '25px', bottom:'55px' }\n }\n }\n },\n }\n);\n</code></pre>\n<p>There are more options too. You can set a different <code>icon</code> and <code>description</code> or specify <code>innerBlocks</code> to have it insert with some blocks nested already.</p>\n" } ]
    2021/11/16
    [ "https://wordpress.stackexchange.com/questions/398210", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120585/" ]
    As referenced in this issue ( <https://github.com/WordPress/gutenberg/issues/33374>) I want my custom block's innerblocks to have the default layout and alignment controls Like the layout toggle for the Group block, but baked in. It was answered, but I can't figure out the code: > > you can do it by providing a layout to inner blocks, that said, the feature is still experimental at the moment, you should be able to pass \_\_experimentalLayout ={ { contentSize: '800px', wideSize: '1000px' } } to your inner blocks, you can also pass \_\_experimentalLayout ={ { inherit: true } } to your inner blocks as well to inherit whatever layout is defined. > > > My code ======= ``` export default function Edit() { return ( <div {...useBlockProps()}> <InnerBlocks /> </div> ); } ``` This doesn't work ``` export default function Edit() { return ( <div {...useBlockProps()}> <InnerBlocks __experimentalLayout ={ { inherit: true } } /> </div> ); } ``` Does it go in supports in block.json? What I'm trying to do ===================== This issue explains the custom block I'm trying to make. Very simple! But I need innerblocks to have alignment control and you lose that on innerblocks when you use theme.json. <https://github.com/WordPress/gutenberg/issues/36465> Updated code ============ I added this to the block.json, which adds the toggle for default layout, but the innerblocks still don't have full/wide alignment control. Not sure how to do that, but halfway there. ``` "supports": { "__experimentalLayout": { "contentSize": "800px", "wideSize": "1000px", "inherit": true } }, ``` Updated code from stokeman's answer ----------------------------------- block.json ``` { "apiVersion": 2, "name": "mbp/details", "version": "0.1.0", "title": "Details", "category": "design", "icon": "heart", "supports": { "align": ["full"], "__experimentalLayout": { "allowSwitching": false, "default": { "inherit": true } } }, "attributes": { "align": { "type": "string", "default": "full" } }, "textdomain": "mobilebevpros", "editorScript": "file:../../../../build/details.js" } ``` edit.js ``` import { __ } from "@wordpress/i18n"; import { useBlockProps, useSetting, InnerBlocks, } from "@wordpress/block-editor"; export default function Edit() { const defaultLayout = useSetting("layout") || {}; return ( <div {...useBlockProps()}> <InnerBlocks __experimentalLayout={defaultLayout} /> </div> ); } ```
    You're pretty close. Specifying layout details in block.json should nest inside a `"default"` property. Doing so will have the Layout panel display accordingly but there's more to it than that. If you want the default layout for the block, there is no need to add `contentSize` or `wideSize`. Here is the layout config I'd recommend (within the block json `supports` property): ```js "__experimentalLayout": { "allowSwitching": false, "default": { "inherit": true } } ``` That will make the Layout panel in the block’s sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs. Even though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component: ```js import { useBlockProps, // already in use from example useSetting // new bit } from '@wordpress/block-editor'; export default function Edit() { const defaultLayout = useSetting( 'layout' ) || {}; return ( <div {...useBlockProps()}> <InnerBlocks __experimentalLayout={ defaultLayout } /> </div> ); } ``` Besides that the block must be registered on the server but I take it that's already being done. I'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site.
    398,340
    <p>I have some legacy meta fields in my post that I would like to display in my block. I found a documentation for settings meta fields but not how to display them. So I tried this:</p> <pre><code>export default function save( { attributes } ) { const blockProps = useBlockProps.save(); const postType = useSelect( ( select ) =&gt; select( 'core/editor' ).getCurrentPostType(), [] ); const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' ); const game_meta = meta[ '_shortscore_game' ]; return ( &lt;p { ...blockProps } &gt; &lt;h2&gt;&lt;game_meta/&gt;&lt;/h2&gt; &lt;/p&gt; ); } </code></pre> <p>I get this error:</p> <blockquote> <p>Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See <a href="https://reactjs.org/link/invalid-hook-call" rel="nofollow noreferrer">https://reactjs.org/link/invalid-hook-call</a> for tips about how to debug and fix this problem.</p> </blockquote> <p>What is the problem? It happens because of</p> <pre><code>const postType = useSelect( ( select ) =&gt; select( 'core/editor' ).getCurrentPostType(), [] ); </code></pre> <p>But why? It works the same in the edit function.</p>
    [ { "answer_id": 398361, "author": "stokesman", "author_id": 214758, "author_profile": "https://wordpress.stackexchange.com/users/214758", "pm_score": 3, "selected": true, "text": "<p>From the docs:\n<a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save</a></p>\n<blockquote>\n<p>Note: The save function should be a pure function that depends only on the attributes used to invoke it.\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it <code>select( store ).selector( ... )</code>.\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (<a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation\" rel=\"nofollow noreferrer\">read more about Validation</a>).\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:</p>\n</blockquote>\n<blockquote>\n<ul>\n<li>Use <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">dynamic blocks</a> and dynamically retrieve the required information on the server.</li>\n<li>Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 405312, "author": "Mr2P", "author_id": 16299, "author_profile": "https://wordpress.stackexchange.com/users/16299", "pm_score": 0, "selected": false, "text": "<p>There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here <a href=\"https://wordpress.org/plugins/display-a-meta-field-as-block/\" rel=\"nofollow noreferrer\">Meta Field Block</a>. The requirement is your meta field has to enable the show_in_rest option.</p>\n" } ]
    2021/11/19
    [ "https://wordpress.stackexchange.com/questions/398340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33797/" ]
    I have some legacy meta fields in my post that I would like to display in my block. I found a documentation for settings meta fields but not how to display them. So I tried this: ``` export default function save( { attributes } ) { const blockProps = useBlockProps.save(); const postType = useSelect( ( select ) => select( 'core/editor' ).getCurrentPostType(), [] ); const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' ); const game_meta = meta[ '_shortscore_game' ]; return ( <p { ...blockProps } > <h2><game_meta/></h2> </p> ); } ``` I get this error: > > Invalid hook call. Hooks can only be called inside of the body of a > function component. This could happen for one of the following > reasons: 1. You might have mismatching versions of React and the > renderer (such as React DOM) 2. You might be breaking the Rules of > Hooks 3. You might have more than one copy of React in the same app > See <https://reactjs.org/link/invalid-hook-call> for tips about how to > debug and fix this problem. > > > What is the problem? It happens because of ``` const postType = useSelect( ( select ) => select( 'core/editor' ).getCurrentPostType(), [] ); ``` But why? It works the same in the edit function.
    From the docs: <https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save> > > Note: The save function should be a pure function that depends only on the attributes used to invoke it. > It can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it `select( store ).selector( ... )`. > This is because if the external information changes, the block may be flagged as invalid when the post is later edited ([read more about Validation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation)). > If there is a need to have other information as part of the save, developers can consider one of these two alternatives: > > > > > * Use [dynamic blocks](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/) and dynamically retrieve the required information on the server. > * Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur. > > >
    398,364
    <p>I have for example this posts in WP:</p> <pre><code>Name ID Date JohnA 6 01012020 JohnB 7 01022020 KateA 7 05052021 SamA 4 01022020 SamA 4 01022022 </code></pre> <p>How I can order by date, but also put posts with ID before others for every user logged in (also ordered by date ) ? Other words - how to sort with conditional logic, using variable for example current user ID in it, so each user will see own posts before other one's.</p>
    [ { "answer_id": 398361, "author": "stokesman", "author_id": 214758, "author_profile": "https://wordpress.stackexchange.com/users/214758", "pm_score": 3, "selected": true, "text": "<p>From the docs:\n<a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save</a></p>\n<blockquote>\n<p>Note: The save function should be a pure function that depends only on the attributes used to invoke it.\nIt can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it <code>select( store ).selector( ... )</code>.\nThis is because if the external information changes, the block may be flagged as invalid when the post is later edited (<a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation\" rel=\"nofollow noreferrer\">read more about Validation</a>).\nIf there is a need to have other information as part of the save, developers can consider one of these two alternatives:</p>\n</blockquote>\n<blockquote>\n<ul>\n<li>Use <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">dynamic blocks</a> and dynamically retrieve the required information on the server.</li>\n<li>Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 405312, "author": "Mr2P", "author_id": 16299, "author_profile": "https://wordpress.stackexchange.com/users/16299", "pm_score": 0, "selected": false, "text": "<p>There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here <a href=\"https://wordpress.org/plugins/display-a-meta-field-as-block/\" rel=\"nofollow noreferrer\">Meta Field Block</a>. The requirement is your meta field has to enable the show_in_rest option.</p>\n" } ]
    2021/11/20
    [ "https://wordpress.stackexchange.com/questions/398364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81810/" ]
    I have for example this posts in WP: ``` Name ID Date JohnA 6 01012020 JohnB 7 01022020 KateA 7 05052021 SamA 4 01022020 SamA 4 01022022 ``` How I can order by date, but also put posts with ID before others for every user logged in (also ordered by date ) ? Other words - how to sort with conditional logic, using variable for example current user ID in it, so each user will see own posts before other one's.
    From the docs: <https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save> > > Note: The save function should be a pure function that depends only on the attributes used to invoke it. > It can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it `select( store ).selector( ... )`. > This is because if the external information changes, the block may be flagged as invalid when the post is later edited ([read more about Validation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation)). > If there is a need to have other information as part of the save, developers can consider one of these two alternatives: > > > > > * Use [dynamic blocks](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/) and dynamically retrieve the required information on the server. > * Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur. > > >
    398,461
    <p>I have a specific requirement that my referral link be as simple as possible to type in manually (customer base is very low skilled) while simultaneously referring to an employee number who was responsible for the referral.</p> <p>So, the referral links need to look like:</p> <pre><code>www.domain.com/referral/1555 </code></pre> <p>Where &quot;1555&quot; is the employee ref number who sent this referral link, and it's the employee ref number that I'll be taking out of the URL. I'm using PHP snippets to deal with loading that data and handling it, but I need to land on the &quot;referral&quot; page inorder for that php snippet to fire.</p> <p>How do I dictate to WP that any URL slug starting with &quot;referral&quot;, regarldes of what comes after, goes to my referral page and keeps the URL intact? The best I can do right now is land on the referral page but the URL gets reset to merely</p> <pre><code>www.domain.com/referral </code></pre>
    [ { "answer_id": 398844, "author": "keepkalm", "author_id": 26744, "author_profile": "https://wordpress.stackexchange.com/users/26744", "pm_score": 0, "selected": false, "text": "<p>You just need the <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">Redirection Plugin</a> and a little regex. There are good options on how to match the URLs in the plugin settings.</p>\n" }, { "answer_id": 398867, "author": "Aboelabbas", "author_id": 119142, "author_profile": "https://wordpress.stackexchange.com/users/119142", "pm_score": 1, "selected": false, "text": "<p>Supposing you have a <em><strong>page created with the slug &quot;referral&quot;</strong></em>, you can add another segment to the page URL containing the employee ref number like this:</p>\n<p>1- Register a new query variable e.g &quot;employee_ref&quot;</p>\n<pre><code>add_filter('query_vars', function ($query_vars){\n $query_vars[] = 'employee_ref';\n return $query_vars;\n});\n</code></pre>\n<p>2- Using <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">add_rewrite_rule</a> function, add a new rule for the 'employee_ref' to be equal to the last numeric segment of the page URL:</p>\n<pre><code>add_action('init', function (){\n add_rewrite_rule(\n '^referral/([0-9]+)/?$',\n 'index.php?pagename=referral&amp;employee_ref=$matches[1]',\n 'top'\n );\n});\n</code></pre>\n<p>3- Go to permalinks setting page on your WordPress dashboard and hit the &quot;Save Changes&quot; button to flush the rewrite rules--<em><strong>a mandatory step</strong></em>--.</p>\n<p>4- The referral link now will look like &quot;https://yourdomain.com/referral/345/&quot;, where &quot;345&quot; is the employee ref number and you can catch it in PHP using:</p>\n<pre><code>get_query_var('employee_ref');\n</code></pre>\n<p>The code used in the first two steps can be placed inside your theme's functions.php or a plugin file.</p>\n" } ]
    2021/11/23
    [ "https://wordpress.stackexchange.com/questions/398461", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/215164/" ]
    I have a specific requirement that my referral link be as simple as possible to type in manually (customer base is very low skilled) while simultaneously referring to an employee number who was responsible for the referral. So, the referral links need to look like: ``` www.domain.com/referral/1555 ``` Where "1555" is the employee ref number who sent this referral link, and it's the employee ref number that I'll be taking out of the URL. I'm using PHP snippets to deal with loading that data and handling it, but I need to land on the "referral" page inorder for that php snippet to fire. How do I dictate to WP that any URL slug starting with "referral", regarldes of what comes after, goes to my referral page and keeps the URL intact? The best I can do right now is land on the referral page but the URL gets reset to merely ``` www.domain.com/referral ```
    Supposing you have a ***page created with the slug "referral"***, you can add another segment to the page URL containing the employee ref number like this: 1- Register a new query variable e.g "employee\_ref" ``` add_filter('query_vars', function ($query_vars){ $query_vars[] = 'employee_ref'; return $query_vars; }); ``` 2- Using [add\_rewrite\_rule](https://developer.wordpress.org/reference/functions/add_rewrite_rule/) function, add a new rule for the 'employee\_ref' to be equal to the last numeric segment of the page URL: ``` add_action('init', function (){ add_rewrite_rule( '^referral/([0-9]+)/?$', 'index.php?pagename=referral&employee_ref=$matches[1]', 'top' ); }); ``` 3- Go to permalinks setting page on your WordPress dashboard and hit the "Save Changes" button to flush the rewrite rules--***a mandatory step***--. 4- The referral link now will look like "https://yourdomain.com/referral/345/", where "345" is the employee ref number and you can catch it in PHP using: ``` get_query_var('employee_ref'); ``` The code used in the first two steps can be placed inside your theme's functions.php or a plugin file.
    398,497
    <p>This is an unusual one (I think).</p> <p>We run a news site, and sometimes when editing posts (using the classic editor, not the new block one) we find that a paragraph in the post we are editing has somehow become wrapped in a bunch of spans containing bootstrap css classes.</p> <p>i.e. the paragraph becomes this</p> <pre><code>&lt;p&gt;&lt;span style=&quot;color: var(--bs-body-color); font-family: var(--bs-body-font-family); font-size: var(--bs-body-font-size); text-align: var(--bs-body-text-align); background-color: var(--bs-body-bg);&quot;&gt; {CONTENT} &lt;/span&gt;&lt;/p&gt;` </code></pre> <p>When it was originally just a normal <code>&lt;p&gt;{CONTENT}&lt;/p&gt;</code>.</p> <p>What we've discovered so far:</p> <ul> <li>The markup seems to be added when a post is saved</li> <li>It isn't just a case of cut-and-paste - the editor can just typing into the article</li> <li>The editor doesn't have to be editing the paragraph which changes</li> <li>Searching the server for &quot;body-font-family&quot; doesn't return results in php or js files</li> <li>Searching the client (i.e. browser including any externally loaded files) for &quot;body-font-family&quot; also doesn't return any results</li> <li>Multiple editors running multiple browsers have seen this so it's not a plug-in in the browser</li> <li>It doesn't happen all the time</li> <li>We can spot no pattern between the posts and paragraphs which have these tags added</li> </ul> <p>Any/all suggestions are very welcome!</p>
    [ { "answer_id": 398808, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<ol>\n<li>In developer tools, find if bootstrap css is added. Look in list of loaded css files. Copy the name of css.</li>\n<li>Search entire wp-content for that css name to find where it is enqueued.</li>\n<li>Now, when you located plugin or theme part, search within this directory for a hook <a href=\"https://developer.wordpress.org/reference/hooks/the_content/\" rel=\"nofollow noreferrer\">the_content</a>.</li>\n<li>It is probably this hook, which is hooked to callback function, in which by using regular expressions this extra HTML is added.</li>\n</ol>\n" }, { "answer_id": 399018, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>Without checking your install it's a bit of a guessing game, but I'd say your TinyMCE editor has a bootstrap plugin installed (there are several). Perhaps the developer tried to remove it, but only removed the buttons in the editor. Any case, it might be active without you noticing, with the plugin's jquery interfering with WordPress, leading to erratic behaviour.</p>\n<p>Also, the plugin may not be on your own server, but loaded from a cdn. Have you checked the editor page html for strings like 'bootstrap'?</p>\n<hr />\n<p>Completely different option: some plugin is messing with your content by adding itself to the <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow noreferrer\"><code>save_post</code></a> hook. But this looks less likely to me, because I can't see why a plugin would do this.</p>\n" } ]
    2021/11/24
    [ "https://wordpress.stackexchange.com/questions/398497", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213900/" ]
    This is an unusual one (I think). We run a news site, and sometimes when editing posts (using the classic editor, not the new block one) we find that a paragraph in the post we are editing has somehow become wrapped in a bunch of spans containing bootstrap css classes. i.e. the paragraph becomes this ``` <p><span style="color: var(--bs-body-color); font-family: var(--bs-body-font-family); font-size: var(--bs-body-font-size); text-align: var(--bs-body-text-align); background-color: var(--bs-body-bg);"> {CONTENT} </span></p>` ``` When it was originally just a normal `<p>{CONTENT}</p>`. What we've discovered so far: * The markup seems to be added when a post is saved * It isn't just a case of cut-and-paste - the editor can just typing into the article * The editor doesn't have to be editing the paragraph which changes * Searching the server for "body-font-family" doesn't return results in php or js files * Searching the client (i.e. browser including any externally loaded files) for "body-font-family" also doesn't return any results * Multiple editors running multiple browsers have seen this so it's not a plug-in in the browser * It doesn't happen all the time * We can spot no pattern between the posts and paragraphs which have these tags added Any/all suggestions are very welcome!
    Without checking your install it's a bit of a guessing game, but I'd say your TinyMCE editor has a bootstrap plugin installed (there are several). Perhaps the developer tried to remove it, but only removed the buttons in the editor. Any case, it might be active without you noticing, with the plugin's jquery interfering with WordPress, leading to erratic behaviour. Also, the plugin may not be on your own server, but loaded from a cdn. Have you checked the editor page html for strings like 'bootstrap'? --- Completely different option: some plugin is messing with your content by adding itself to the [`save_post`](https://developer.wordpress.org/reference/hooks/save_post/) hook. But this looks less likely to me, because I can't see why a plugin would do this.
    398,602
    <p>I created my first WordPress website using Elementor and an all-in-one theme called Webify.</p> <p>Since I am new to WordPress and to website design, I've imported a demo website that comes with the Webify theme and I am editing based on that import.</p> <p>I noticed that some pages on my site have this top 'stripe' with a background image and some text on the page name and location.</p> <p>For example, the blog page has this horizontal stripe, with a red background image, and the text <em><strong>Blog</strong></em> on the left-hand side and <em><strong>Home / Blog</strong></em> on the right-hand side:</p> <p><a href="https://i.stack.imgur.com/1xQbx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1xQbx.png" alt="blog page" /></a></p> <p>Do you see it? Right under the logo and the header menu? I want to remove this horizontal stripe! The thing is, I can't find how. As far as I can tell, it's not an Elementor element, because when I edit the page in Elementor I can't interact with it. I also didn't find how to remove it from the WP Customize tool.</p> <p>I do have pages on my site that don't have this top horizontal stripe, like this one:</p> <p><a href="https://i.stack.imgur.com/njjyc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/njjyc.jpg" alt="enter image description here" /></a></p> <p>Let's call this kind of page &quot;Good Page&quot;</p> <p>I can edit a good page to create the beautiful page I want:</p> <p><a href="https://i.stack.imgur.com/GGKRj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GGKRj.jpg" alt="enter image description here" /></a></p> <p>but whenever I try to create a new page I get a page with this horizontal stripe. I tried creating a new page directly from WP, from Elementor, I tried using a good page and creating an Elementor template from it and then importing the template to a new page, and even tried cloning a good page, using <a href="https://wordpress.org/plugins/copy-delete-posts/" rel="nofollow noreferrer">this WP plugin</a> but in all these attempts, the new page I got had that stripe );</p> <p>Looking at the page attributes for both a good page and a new page I created, I couldn't figure out any attribues that were controling this horizontal stripe.</p> <p>I would be grateful for some help on on to remove this horizontal stripe!</p> <p>In adddition, I would also love some debugging pointers on how to go about identifying an element such as this one, and then hide it in the CSS.</p> <p>Thank you so much for you help :)</p>
    [ { "answer_id": 398605, "author": "SavPhill", "author_id": 202754, "author_profile": "https://wordpress.stackexchange.com/users/202754", "pm_score": 1, "selected": false, "text": "<p>If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.</p>\n<p>Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.</p>\n<pre><code> .yourexampleselector {\n \n Display: none;\n \n }\n</code></pre>\n" }, { "answer_id": 398615, "author": "Arnaud Dev", "author_id": 168393, "author_profile": "https://wordpress.stackexchange.com/users/168393", "pm_score": 0, "selected": false, "text": "<p>As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.</p>\n<p>And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n<a href=\"https://i.stack.imgur.com/Y6tHl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y6tHl.jpg\" alt=\"enter image description here\" /></a></p>\n<p>You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.</p>\n<p><a href=\"https://i.stack.imgur.com/Ys6WP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ys6WP.jpg\" alt=\"enter image description here\" /></a></p>\n" } ]
    2021/11/27
    [ "https://wordpress.stackexchange.com/questions/398602", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/215262/" ]
    I created my first WordPress website using Elementor and an all-in-one theme called Webify. Since I am new to WordPress and to website design, I've imported a demo website that comes with the Webify theme and I am editing based on that import. I noticed that some pages on my site have this top 'stripe' with a background image and some text on the page name and location. For example, the blog page has this horizontal stripe, with a red background image, and the text ***Blog*** on the left-hand side and ***Home / Blog*** on the right-hand side: [![blog page](https://i.stack.imgur.com/1xQbx.png)](https://i.stack.imgur.com/1xQbx.png) Do you see it? Right under the logo and the header menu? I want to remove this horizontal stripe! The thing is, I can't find how. As far as I can tell, it's not an Elementor element, because when I edit the page in Elementor I can't interact with it. I also didn't find how to remove it from the WP Customize tool. I do have pages on my site that don't have this top horizontal stripe, like this one: [![enter image description here](https://i.stack.imgur.com/njjyc.jpg)](https://i.stack.imgur.com/njjyc.jpg) Let's call this kind of page "Good Page" I can edit a good page to create the beautiful page I want: [![enter image description here](https://i.stack.imgur.com/GGKRj.jpg)](https://i.stack.imgur.com/GGKRj.jpg) but whenever I try to create a new page I get a page with this horizontal stripe. I tried creating a new page directly from WP, from Elementor, I tried using a good page and creating an Elementor template from it and then importing the template to a new page, and even tried cloning a good page, using [this WP plugin](https://wordpress.org/plugins/copy-delete-posts/) but in all these attempts, the new page I got had that stripe ); Looking at the page attributes for both a good page and a new page I created, I couldn't figure out any attribues that were controling this horizontal stripe. I would be grateful for some help on on to remove this horizontal stripe! In adddition, I would also love some debugging pointers on how to go about identifying an element such as this one, and then hide it in the CSS. Thank you so much for you help :)
    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve. Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css. ``` .yourexampleselector { Display: none; } ```
    398,898
    <p>I use this to display all categories:</p> <pre><code>&lt;?php $args = array( 'child_of' =&gt; 0, 'current_category' =&gt; 0, 'depth' =&gt; 0, 'echo' =&gt; 1, 'exclude' =&gt; '', 'exclude_tree' =&gt; '', 'feed' =&gt; '', 'feed_image' =&gt; '', 'feed_type' =&gt; '', 'hide_empty' =&gt; 1, 'hide_title_if_empty' =&gt; false, 'hierarchical' =&gt; true, 'order' =&gt; 'ASC', 'orderby' =&gt; 'name', 'separator' =&gt; ' ', 'show_count' =&gt; 0, 'show_option_all' =&gt; '', 'style' =&gt; 'h3', 'taxonomy' =&gt; 'category', 'title_li' =&gt; __( 'Categories' ), 'use_desc_for_title' =&gt; 1, ); var_dump( wp_list_categories($args) ); ?&gt; </code></pre> <p>But it also gives me back the word &quot;NULL&quot;.</p> <p><a href="https://i.stack.imgur.com/Igqsr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Igqsr.jpg" alt="enter image description here" /></a></p> <p>How can I remove the &quot;NULL&quot;?</p>
    [ { "answer_id": 398605, "author": "SavPhill", "author_id": 202754, "author_profile": "https://wordpress.stackexchange.com/users/202754", "pm_score": 1, "selected": false, "text": "<p>If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.</p>\n<p>Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.</p>\n<pre><code> .yourexampleselector {\n \n Display: none;\n \n }\n</code></pre>\n" }, { "answer_id": 398615, "author": "Arnaud Dev", "author_id": 168393, "author_profile": "https://wordpress.stackexchange.com/users/168393", "pm_score": 0, "selected": false, "text": "<p>As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.</p>\n<p>And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n<a href=\"https://i.stack.imgur.com/Y6tHl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y6tHl.jpg\" alt=\"enter image description here\" /></a></p>\n<p>You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.</p>\n<p><a href=\"https://i.stack.imgur.com/Ys6WP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ys6WP.jpg\" alt=\"enter image description here\" /></a></p>\n" } ]
    2021/12/05
    [ "https://wordpress.stackexchange.com/questions/398898", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137495/" ]
    I use this to display all categories: ``` <?php $args = array( 'child_of' => 0, 'current_category' => 0, 'depth' => 0, 'echo' => 1, 'exclude' => '', 'exclude_tree' => '', 'feed' => '', 'feed_image' => '', 'feed_type' => '', 'hide_empty' => 1, 'hide_title_if_empty' => false, 'hierarchical' => true, 'order' => 'ASC', 'orderby' => 'name', 'separator' => ' ', 'show_count' => 0, 'show_option_all' => '', 'style' => 'h3', 'taxonomy' => 'category', 'title_li' => __( 'Categories' ), 'use_desc_for_title' => 1, ); var_dump( wp_list_categories($args) ); ?> ``` But it also gives me back the word "NULL". [![enter image description here](https://i.stack.imgur.com/Igqsr.jpg)](https://i.stack.imgur.com/Igqsr.jpg) How can I remove the "NULL"?
    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve. Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css. ``` .yourexampleselector { Display: none; } ```
    398,964
    <p>I would like to have an svg downloaded from my site as a png. Searching I found this code and I must say that everything works. The site is a project that will only be viewed from mobile <a href="https://7c81b.wineqrcode.com/" rel="nofollow noreferrer">https://7c81b.wineqrcode.com/</a> and I would like you to change the size of the downloaded image. Currently the photo is generated based on the size of the svg. Is there any way to get around this? Thanks</p> <pre><code>function downloadSVGAsPNG(e){ const canvas = document.createElement(&quot;canvas&quot;); const svg = document.querySelector('#Layer_1'); const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML))); const w = parseInt(svg.getAttribute('width')); const h = parseInt(svg.getAttribute('height')); const img_to_download = document.createElement('img'); img_to_download.src = 'data:image/svg+xml;base64,' + base64doc; console.log(w, h); img_to_download.onload = function () { console.log('img loaded'); canvas.setAttribute('width', w); canvas.setAttribute('height', h); const context = canvas.getContext(&quot;2d&quot;); //context.clearRect(0, 0, w, h); context.drawImage(img_to_download,0,0,w,h); const dataURL = canvas.toDataURL('image/png'); if (window.navigator.msSaveBlob) { window.navigator.msSaveBlob(canvas.msToBlob(), &quot;download.png&quot;); e.preventDefault(); } else { const a = document.createElement('a'); const my_evt = new MouseEvent('click'); a.download = 'download.png'; a.href = dataURL; a.dispatchEvent(my_evt); } //canvas.parentNode.removeChild(canvas); } } const downloadPNG = document.querySelector('#downloadPNG'); if(downloadPNG) { downloadPNG.addEventListener('click', downloadSVGAsPNG);} </code></pre>
    [ { "answer_id": 398605, "author": "SavPhill", "author_id": 202754, "author_profile": "https://wordpress.stackexchange.com/users/202754", "pm_score": 1, "selected": false, "text": "<p>If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.</p>\n<p>Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.</p>\n<pre><code> .yourexampleselector {\n \n Display: none;\n \n }\n</code></pre>\n" }, { "answer_id": 398615, "author": "Arnaud Dev", "author_id": 168393, "author_profile": "https://wordpress.stackexchange.com/users/168393", "pm_score": 0, "selected": false, "text": "<p>As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.</p>\n<p>And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n<a href=\"https://i.stack.imgur.com/Y6tHl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y6tHl.jpg\" alt=\"enter image description here\" /></a></p>\n<p>You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.</p>\n<p><a href=\"https://i.stack.imgur.com/Ys6WP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ys6WP.jpg\" alt=\"enter image description here\" /></a></p>\n" } ]
    2021/12/07
    [ "https://wordpress.stackexchange.com/questions/398964", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204509/" ]
    I would like to have an svg downloaded from my site as a png. Searching I found this code and I must say that everything works. The site is a project that will only be viewed from mobile <https://7c81b.wineqrcode.com/> and I would like you to change the size of the downloaded image. Currently the photo is generated based on the size of the svg. Is there any way to get around this? Thanks ``` function downloadSVGAsPNG(e){ const canvas = document.createElement("canvas"); const svg = document.querySelector('#Layer_1'); const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML))); const w = parseInt(svg.getAttribute('width')); const h = parseInt(svg.getAttribute('height')); const img_to_download = document.createElement('img'); img_to_download.src = 'data:image/svg+xml;base64,' + base64doc; console.log(w, h); img_to_download.onload = function () { console.log('img loaded'); canvas.setAttribute('width', w); canvas.setAttribute('height', h); const context = canvas.getContext("2d"); //context.clearRect(0, 0, w, h); context.drawImage(img_to_download,0,0,w,h); const dataURL = canvas.toDataURL('image/png'); if (window.navigator.msSaveBlob) { window.navigator.msSaveBlob(canvas.msToBlob(), "download.png"); e.preventDefault(); } else { const a = document.createElement('a'); const my_evt = new MouseEvent('click'); a.download = 'download.png'; a.href = dataURL; a.dispatchEvent(my_evt); } //canvas.parentNode.removeChild(canvas); } } const downloadPNG = document.querySelector('#downloadPNG'); if(downloadPNG) { downloadPNG.addEventListener('click', downloadSVGAsPNG);} ```
    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve. Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css. ``` .yourexampleselector { Display: none; } ```
    399,000
    <p>Let say I want to insert different inline formatting texts. I can do that by opening the HTML mode, but is there a way to do it directly in the visual mode? For example, if I type <code>span.a</code> in a paragraph block then it will insert <code>&lt;span class=&quot;a&quot;&gt;&lt;/span&gt;</code> in HTML, similarly how the formatting buttons like bold or italic do. Or perhaps at least a hotkey button to apply custom formatting, like <code>Ctrl+B</code>. Is that possible?</p> <p>Or to take it to another level, is there a way to implement <a href="https://emmet.io/" rel="nofollow noreferrer" title="Emmet — the essential toolkit for web-developers">Emmet</a> in WordPress?</p>
    [ { "answer_id": 398605, "author": "SavPhill", "author_id": 202754, "author_profile": "https://wordpress.stackexchange.com/users/202754", "pm_score": 1, "selected": false, "text": "<p>If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve.</p>\n<p>Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css.</p>\n<pre><code> .yourexampleselector {\n \n Display: none;\n \n }\n</code></pre>\n" }, { "answer_id": 398615, "author": "Arnaud Dev", "author_id": 168393, "author_profile": "https://wordpress.stackexchange.com/users/168393", "pm_score": 0, "selected": false, "text": "<p>As P.Sav said, it comes from your theme. You install the &quot;Show current template&quot; extension for wordpress which will show you for a page which template you are on and then you can find out which template file it is from.</p>\n<p>And if you can't do it, you can always look at the classes that wordpress adds in each page that are in the body tag, they allow the CSS properties to be applied on a page-by-page basis.\n<a href=\"https://i.stack.imgur.com/Y6tHl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y6tHl.jpg\" alt=\"enter image description here\" /></a></p>\n<p>You can also add custom css code via élementor but I find this solution a little less clean because we quickly forget where we placed the code.</p>\n<p><a href=\"https://i.stack.imgur.com/Ys6WP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ys6WP.jpg\" alt=\"enter image description here\" /></a></p>\n" } ]
    2021/12/08
    [ "https://wordpress.stackexchange.com/questions/399000", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64282/" ]
    Let say I want to insert different inline formatting texts. I can do that by opening the HTML mode, but is there a way to do it directly in the visual mode? For example, if I type `span.a` in a paragraph block then it will insert `<span class="a"></span>` in HTML, similarly how the formatting buttons like bold or italic do. Or perhaps at least a hotkey button to apply custom formatting, like `Ctrl+B`. Is that possible? Or to take it to another level, is there a way to implement [Emmet](https://emmet.io/ "Emmet — the essential toolkit for web-developers") in WordPress?
    If the element you are seeing can not be edited in Elementor, then this is part of the theme template. You should consider looking directly at the theme page template you are using on this page to solve. Nether the less, as per your question you can remove this globally using css. In your browser you can Inspect Element, select this div element and use the selector to add the following code in your custom css. ``` .yourexampleselector { Display: none; } ```
    399,225
    <p>I would like to ask about the wp_redirect(); function. Before I ask this question, everything was working on both local and test servers. But right now, for some unknown reason, on my local wp_redirect is not working.</p> <p>My current structure is this:</p> <pre><code>get_header(); ... wp_redirect($url); exit(); </code></pre> <p>This was also working with our previous programmer. If I declare my get_header after the wp_redirect, the wp_redirect function will work as intended. However, why is it that before, it was working? Btw, I read this <a href="https://wordpress.stackexchange.com/a/97982/214554">SO Answer</a> after I had this problem.</p> <p>Were you able to work the wp_redirect after the get_header?</p> <p>Note: I tried to rollback to previous version and on the old version, other part of the code that uses the same structure above no longer works.</p> <p>The only difference between the environment was on my local, I accidentally dropped my table and reinstalled from scratch. Other than that, nothing comes to mind.</p>
    [ { "answer_id": 399227, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p><code>wp_redirect()</code> works by sending a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location\" rel=\"nofollow noreferrer\">Location header</a>. Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling <code>wp_redirect()</code>.</p>\n<p>Using <code>wp_redirect()</code> after <code>get_header()</code> never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if <code>header.php</code> was completely empty, so <code>get_header()</code> did not output HTML.</p>\n" }, { "answer_id": 399228, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>You cannot redirect with <code>wp_redirect()</code> after the page content is rendered (this is what <code>get_header()</code> does).</p>\n<p>So, you basically have 2 options-</p>\n<ol>\n<li><p>Place <code>wp_redirect()</code> before you include the header.</p>\n</li>\n<li><p>With JavaScript-</p>\n</li>\n</ol>\n<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\n window.location = 'https://google.com';\n&lt;/script&gt;\n</code></pre>\n" } ]
    2021/12/14
    [ "https://wordpress.stackexchange.com/questions/399225", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214554/" ]
    I would like to ask about the wp\_redirect(); function. Before I ask this question, everything was working on both local and test servers. But right now, for some unknown reason, on my local wp\_redirect is not working. My current structure is this: ``` get_header(); ... wp_redirect($url); exit(); ``` This was also working with our previous programmer. If I declare my get\_header after the wp\_redirect, the wp\_redirect function will work as intended. However, why is it that before, it was working? Btw, I read this [SO Answer](https://wordpress.stackexchange.com/a/97982/214554) after I had this problem. Were you able to work the wp\_redirect after the get\_header? Note: I tried to rollback to previous version and on the old version, other part of the code that uses the same structure above no longer works. The only difference between the environment was on my local, I accidentally dropped my table and reinstalled from scratch. Other than that, nothing comes to mind.
    `wp_redirect()` works by sending a [Location header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location). Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling `wp_redirect()`. Using `wp_redirect()` after `get_header()` never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if `header.php` was completely empty, so `get_header()` did not output HTML.
    399,237
    <p>I searched the whole net and stackexchange for a reason and a solution, but couldn't find any. There are many questions (and answers) related to own plugins and the code how to create tables on activation. But this applies not here, because I have this problem with well known and maintained plugins from the wordpress plugin repository.</p> <p><strong>So, the situation:</strong> A kvm guest with around 20 docker stacks. Each stack consists of a nginx, a php:8-fpm and a mariadb container. In the nginx container is a web directory as a shared volume, that contains a wordpress installation. (So I'm not using the wordpress docker image!).</p> <p>The wordpress'es are running like a charm. I can access the backend and the frontends, I can install plugins and themes... everything is working... until...</p> <p><em>Until it comes to a plugin installation that wants to create own sql tables on activation.</em></p> <p>The tables are not created, I only receive an error that says, the table xxx is not existent and the plugin can not be activated.</p> <p>This happens on all plugins from the wordpress plugin repository, when they want to create own tables on activation.</p> <p>Everything else is working like a charm.</p> <p>The sql user is allowed to create tables... this was checked through the mysql console. The wp-config.php is correct... everything has worked when not in a docker container. This happens only when inside a docker container.</p> <p><strong>So here's my docker-compose.yml</strong></p> <pre><code>version: '3.8' services: app: image: nginx:latest restart: always volumes: - ./web:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf - ./logs:/var/www/logs php-fpm: image: php:8-fpm restart: always volumes: - ./web:/usr/share/nginx/html - ./errors.ini:/usr/local/etc/php/conf.d/errors.ini:rw - ./logs:/var/www/logs logging: driver: syslog options: tag: docker/php-fpm mariadb: image: mariadb:latest restart: always environment: MYSQL_ROOT_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx' MYSQL_DATABASE: 'database' MYSQL_USER: 'dbuser' MYSQL_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx' expose: - &quot;3306&quot; volumes: - ./mysql:/var/lib/mysql </code></pre> <p><strong>Here comes the default.conf:</strong></p> <pre><code>server { server_name _; index index.php index.html; client_max_body_size 1024M; client_body_timeout 900s; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; send_timeout 3600; keepalive_timeout 60m; fastcgi_send_timeout 3600s; fastcgi_read_timeout 3600s; error_log /var/www/logs/nginx-error.log; access_log /var/www/logs/nginx-access.log; root /usr/share/nginx/html; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param HTTPS on; fastcgi_pass php-fpm:9000; } } </code></pre> <p><strong>Ohh, one more fun fact:</strong> A simple php script, that creates a table with the same database user credentials through mysqli classes, works like a charm:</p> <pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli(&quot;mariadb&quot;, &quot;dbuser&quot;, &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;, &quot;database&quot;); /* Create table doesn't return a resultset */ $sql = &quot;CREATE TABLE MyGuests2 ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )&quot;; $mysqli-&gt;query($sql); printf(&quot;Table myGuests2 successfully created.\n&quot;); /* Select queries return a resultset */ $result = $mysqli-&gt;query(&quot;SELECT id FROM MyGuests2 LIMIT 10&quot;); printf(&quot;Select returned %d rows.\n&quot;, $result-&gt;num_rows); /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ $result = $mysqli-&gt;query(&quot;SELECT * FROM MyGuests&quot;, MYSQLI_USE_RESULT); </code></pre>
    [ { "answer_id": 399302, "author": "Christin Löhner", "author_id": 215861, "author_profile": "https://wordpress.stackexchange.com/users/215861", "pm_score": 3, "selected": true, "text": "<p>Like <a href=\"https://wordpress.stackexchange.com/users/108180/kero\">kero</a> already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.</p>\n<p><strong>Update</strong>\nI've tested this now with different PHP versions and different plugins from the wordpress repository.</p>\n<p>This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.</p>\n<hr />\n<p>By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n</code></pre>\n" }, { "answer_id": 400325, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.</p>\n<p>I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.</p>\n" } ]
    2021/12/14
    [ "https://wordpress.stackexchange.com/questions/399237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/215861/" ]
    I searched the whole net and stackexchange for a reason and a solution, but couldn't find any. There are many questions (and answers) related to own plugins and the code how to create tables on activation. But this applies not here, because I have this problem with well known and maintained plugins from the wordpress plugin repository. **So, the situation:** A kvm guest with around 20 docker stacks. Each stack consists of a nginx, a php:8-fpm and a mariadb container. In the nginx container is a web directory as a shared volume, that contains a wordpress installation. (So I'm not using the wordpress docker image!). The wordpress'es are running like a charm. I can access the backend and the frontends, I can install plugins and themes... everything is working... until... *Until it comes to a plugin installation that wants to create own sql tables on activation.* The tables are not created, I only receive an error that says, the table xxx is not existent and the plugin can not be activated. This happens on all plugins from the wordpress plugin repository, when they want to create own tables on activation. Everything else is working like a charm. The sql user is allowed to create tables... this was checked through the mysql console. The wp-config.php is correct... everything has worked when not in a docker container. This happens only when inside a docker container. **So here's my docker-compose.yml** ``` version: '3.8' services: app: image: nginx:latest restart: always volumes: - ./web:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf - ./logs:/var/www/logs php-fpm: image: php:8-fpm restart: always volumes: - ./web:/usr/share/nginx/html - ./errors.ini:/usr/local/etc/php/conf.d/errors.ini:rw - ./logs:/var/www/logs logging: driver: syslog options: tag: docker/php-fpm mariadb: image: mariadb:latest restart: always environment: MYSQL_ROOT_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx' MYSQL_DATABASE: 'database' MYSQL_USER: 'dbuser' MYSQL_PASSWORD: 'xxxxxxxxxxxxxxxxxxxxxxxxxx' expose: - "3306" volumes: - ./mysql:/var/lib/mysql ``` **Here comes the default.conf:** ``` server { server_name _; index index.php index.html; client_max_body_size 1024M; client_body_timeout 900s; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; send_timeout 3600; keepalive_timeout 60m; fastcgi_send_timeout 3600s; fastcgi_read_timeout 3600s; error_log /var/www/logs/nginx-error.log; access_log /var/www/logs/nginx-access.log; root /usr/share/nginx/html; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param HTTPS on; fastcgi_pass php-fpm:9000; } } ``` **Ohh, one more fun fact:** A simple php script, that creates a table with the same database user credentials through mysqli classes, works like a charm: ``` mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("mariadb", "dbuser", "xxxxxxxxxxxxxxxxxxxxxxxxxxx", "database"); /* Create table doesn't return a resultset */ $sql = "CREATE TABLE MyGuests2 ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; $mysqli->query($sql); printf("Table myGuests2 successfully created.\n"); /* Select queries return a resultset */ $result = $mysqli->query("SELECT id FROM MyGuests2 LIMIT 10"); printf("Select returned %d rows.\n", $result->num_rows); /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ $result = $mysqli->query("SELECT * FROM MyGuests", MYSQLI_USE_RESULT); ```
    Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me. **Update** I've tested this now with different PHP versions and different plugins from the wordpress repository. This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing "php:8-fpm" with "php:8.0-fpm" or any other version... it works again. --- By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top: ```sh FROM php:8-fpm RUN apt-get update RUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev RUN apt-get clean RUN rm -rf /var/lib/apt/lists/* COPY mail.ini /usr/local/etc/php/conf.d/ COPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf COPY cronjob.sh /etc/cron.hourly/cronjob.sh RUN chmod 664 /etc/ssmtp/ssmtp.conf RUN chmod +x /etc/cron.hourly/cronjob.sh RUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl RUN docker-php-ext-enable pdo_mysql RUN docker-php-ext-enable mysqli RUN docker-php-ext-enable opcache RUN docker-php-ext-enable bcmath RUN docker-php-ext-enable bz2 RUN docker-php-ext-enable gd RUN docker-php-ext-enable pspell RUN docker-php-ext-enable snmp RUN docker-php-ext-enable soap RUN docker-php-ext-enable tidy RUN docker-php-ext-enable xsl RUN docker-php-ext-enable zip RUN docker-php-ext-enable exif RUN docker-php-ext-enable gettext RUN docker-php-ext-enable intl ```
    399,279
    <p>I have my custom Wordpress+Woocommerce theme created that I want to show on my github page as a reference.</p> <p>The theme does not contain any login data. Of course it contains server-side php code that shows how the client page is created. I always tried to structure the logic according to other themes/according to how code inside Woocommerce plugin works.</p> <p><strong>Is there a security danger for the site when making the theme source public?</strong></p>
    [ { "answer_id": 399302, "author": "Christin Löhner", "author_id": 215861, "author_profile": "https://wordpress.stackexchange.com/users/215861", "pm_score": 3, "selected": true, "text": "<p>Like <a href=\"https://wordpress.stackexchange.com/users/108180/kero\">kero</a> already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.</p>\n<p><strong>Update</strong>\nI've tested this now with different PHP versions and different plugins from the wordpress repository.</p>\n<p>This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.</p>\n<hr />\n<p>By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n</code></pre>\n" }, { "answer_id": 400325, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.</p>\n<p>I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.</p>\n" } ]
    2021/12/15
    [ "https://wordpress.stackexchange.com/questions/399279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/215899/" ]
    I have my custom Wordpress+Woocommerce theme created that I want to show on my github page as a reference. The theme does not contain any login data. Of course it contains server-side php code that shows how the client page is created. I always tried to structure the logic according to other themes/according to how code inside Woocommerce plugin works. **Is there a security danger for the site when making the theme source public?**
    Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me. **Update** I've tested this now with different PHP versions and different plugins from the wordpress repository. This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing "php:8-fpm" with "php:8.0-fpm" or any other version... it works again. --- By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top: ```sh FROM php:8-fpm RUN apt-get update RUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev RUN apt-get clean RUN rm -rf /var/lib/apt/lists/* COPY mail.ini /usr/local/etc/php/conf.d/ COPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf COPY cronjob.sh /etc/cron.hourly/cronjob.sh RUN chmod 664 /etc/ssmtp/ssmtp.conf RUN chmod +x /etc/cron.hourly/cronjob.sh RUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl RUN docker-php-ext-enable pdo_mysql RUN docker-php-ext-enable mysqli RUN docker-php-ext-enable opcache RUN docker-php-ext-enable bcmath RUN docker-php-ext-enable bz2 RUN docker-php-ext-enable gd RUN docker-php-ext-enable pspell RUN docker-php-ext-enable snmp RUN docker-php-ext-enable soap RUN docker-php-ext-enable tidy RUN docker-php-ext-enable xsl RUN docker-php-ext-enable zip RUN docker-php-ext-enable exif RUN docker-php-ext-enable gettext RUN docker-php-ext-enable intl ```
    400,336
    <p>I'm studying someone else's code (a custom search widget based on Elementor) and there's one thing I just don't understand.</p> <pre><code>$type_term = get_term_by('slug', get_query_var($taxonomy), $taxonomy); $type = (!empty($type_term) &amp;&amp; !empty($type_term-&gt;slug)) ? $type_term-&gt;slug : 0; </code></pre> <pre><code>wp_dropdown_categories(array( 'show_option_all' =&gt; '', 'show_option_none' =&gt; 'Select ' . $taxonomy_obj-&gt;label, 'option_none_value' =&gt; '0', 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', 'hide_empty' =&gt; 1, 'depth' =&gt; 3, 'echo' =&gt; 1, 'selected' =&gt; $type, 'hierarchical' =&gt; 1, 'name' =&gt; $taxonomy, 'id' =&gt; $taxonomy . '-select', 'class' =&gt; $taxonomy . '-select', 'tab_index' =&gt; 1, 'taxonomy' =&gt; $taxonomy, 'value_field' =&gt; 'slug' )); </code></pre> <p>I realize <code>$type</code> is the slug of the selected term. But why do I have to manually assign <code>'selected' =&gt; $type</code>? What does this field even mean? Shouldn't this be automatically passed to the selected attribute? Am I even correct in that <code>get_query_var($taxonomy)</code>returns the selected taxonomy term?</p> <p>Or more generally speaking, how/where is the selected option stored and how/where is it retrieved for the search? I'm sure there is something really obvious I'm not getting but the documentation didn't help.</p> <p>I hope this is somewhat comprehensible. Thanks!</p>
    [ { "answer_id": 399302, "author": "Christin Löhner", "author_id": 215861, "author_profile": "https://wordpress.stackexchange.com/users/215861", "pm_score": 3, "selected": true, "text": "<p>Like <a href=\"https://wordpress.stackexchange.com/users/108180/kero\">kero</a> already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me.</p>\n<p><strong>Update</strong>\nI've tested this now with different PHP versions and different plugins from the wordpress repository.</p>\n<p>This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing &quot;php:8-fpm&quot; with &quot;php:8.0-fpm&quot; or any other version... it works again.</p>\n<hr />\n<p>By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>FROM php:8-fpm\n\nRUN apt-get update\nRUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev\n\nRUN apt-get clean\nRUN rm -rf /var/lib/apt/lists/*\n\nCOPY mail.ini /usr/local/etc/php/conf.d/\nCOPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf\nCOPY cronjob.sh /etc/cron.hourly/cronjob.sh\nRUN chmod 664 /etc/ssmtp/ssmtp.conf\nRUN chmod +x /etc/cron.hourly/cronjob.sh\n\nRUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl\n\nRUN docker-php-ext-enable pdo_mysql\nRUN docker-php-ext-enable mysqli\nRUN docker-php-ext-enable opcache\nRUN docker-php-ext-enable bcmath\nRUN docker-php-ext-enable bz2\nRUN docker-php-ext-enable gd\nRUN docker-php-ext-enable pspell\nRUN docker-php-ext-enable snmp\nRUN docker-php-ext-enable soap\nRUN docker-php-ext-enable tidy\nRUN docker-php-ext-enable xsl\nRUN docker-php-ext-enable zip\nRUN docker-php-ext-enable exif\nRUN docker-php-ext-enable gettext\nRUN docker-php-ext-enable intl\n</code></pre>\n" }, { "answer_id": 400325, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Not sure if it is related, but just in case, as for the last time I looked at it WP core 5.8 have bugs in dbdelta relating to MySQL 8 when integers are involved. Latest MariaDb seems to do better.</p>\n<p>I would assume that as of 5.8 core is not ready to be deployed on edge everything. There might be good chance of things generaly working but you might run into edge cases in which they will not.</p>\n" } ]
    2021/12/16
    [ "https://wordpress.stackexchange.com/questions/400336", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/215929/" ]
    I'm studying someone else's code (a custom search widget based on Elementor) and there's one thing I just don't understand. ``` $type_term = get_term_by('slug', get_query_var($taxonomy), $taxonomy); $type = (!empty($type_term) && !empty($type_term->slug)) ? $type_term->slug : 0; ``` ``` wp_dropdown_categories(array( 'show_option_all' => '', 'show_option_none' => 'Select ' . $taxonomy_obj->label, 'option_none_value' => '0', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'depth' => 3, 'echo' => 1, 'selected' => $type, 'hierarchical' => 1, 'name' => $taxonomy, 'id' => $taxonomy . '-select', 'class' => $taxonomy . '-select', 'tab_index' => 1, 'taxonomy' => $taxonomy, 'value_field' => 'slug' )); ``` I realize `$type` is the slug of the selected term. But why do I have to manually assign `'selected' => $type`? What does this field even mean? Shouldn't this be automatically passed to the selected attribute? Am I even correct in that `get_query_var($taxonomy)`returns the selected taxonomy term? Or more generally speaking, how/where is the selected option stored and how/where is it retrieved for the search? I'm sure there is something really obvious I'm not getting but the documentation didn't help. I hope this is somewhat comprehensible. Thanks!
    Like [kero](https://wordpress.stackexchange.com/users/108180/kero) already has mentioned, I've now tested the activation of plugins with other PHP versions. And what should I say.... Simply switching from docker image php:8-fpm (8.1) to php:7.4-fpm fixed the issue for me. **Update** I've tested this now with different PHP versions and different plugins from the wordpress repository. This happens with ALL plugins, which wants to create own tables on activation. But it only happens with PHP 8.1 (docker image php:8-fpm). Just by replacing "php:8-fpm" with "php:8.0-fpm" or any other version... it works again. --- By the way, I'm also using exactly the same Dockerfile for building the images. I'm just only replacing the version of the original image on top: ```sh FROM php:8-fpm RUN apt-get update RUN apt -y install ssmtp cron snmp mcrypt unzip curl libedit-dev libeditreadline-dev libedit2 libxml2-dev bison flex libbz2-dev libzip-dev libcurl4-openssl-dev libenchant-2-dev libpspell-dev libpng-dev libjpeg-dev libonig-dev libonig5 libsnmp-dev libtidy-dev libxslt1-dev RUN apt-get clean RUN rm -rf /var/lib/apt/lists/* COPY mail.ini /usr/local/etc/php/conf.d/ COPY --chown=root:mail ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf COPY cronjob.sh /etc/cron.hourly/cronjob.sh RUN chmod 664 /etc/ssmtp/ssmtp.conf RUN chmod +x /etc/cron.hourly/cronjob.sh RUN docker-php-ext-install pdo_mysql mysqli opcache bcmath bz2 gd pspell snmp soap tidy xsl zip exif gettext intl RUN docker-php-ext-enable pdo_mysql RUN docker-php-ext-enable mysqli RUN docker-php-ext-enable opcache RUN docker-php-ext-enable bcmath RUN docker-php-ext-enable bz2 RUN docker-php-ext-enable gd RUN docker-php-ext-enable pspell RUN docker-php-ext-enable snmp RUN docker-php-ext-enable soap RUN docker-php-ext-enable tidy RUN docker-php-ext-enable xsl RUN docker-php-ext-enable zip RUN docker-php-ext-enable exif RUN docker-php-ext-enable gettext RUN docker-php-ext-enable intl ```
    400,397
    <p>I am creating a custom theme. In it I am trying to add salon booking plugin. This plugin creates default booking page. When I am viewing the booking page I cannot see the booking form. I have tried installing the salon booking plugin in WordPress default theme twenty twenty-one and it is working fine in this theme. Not sure what is breaking in my theme.</p> <p>In my theme I have added <code>wp_head()</code> just before end of head tag in <code>header.php</code>. I have also added <code>wp_footer()</code> just before the end of body tag in footer.php.</p> <p>I have following php files</p> <ul> <li><code>header.php</code></li> <li><code>footer.php</code></li> <li><code>functions.php</code></li> <li><code>index.php</code></li> <li><code>front-page.php</code></li> </ul> <p>I have following pages - home page (that I created, this is pointing to front-page.php), Booking, Thank you for booking, Booking my account. Last three booking pages were created as part of the salon booking plugin.</p> <p><code>header.php</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html &lt;?php language_attributes();?&gt;&gt; &lt;head&gt; &lt;meta charset=&lt;?php bloginfo('charset');?&gt;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, viewport-fit=cover&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt; &lt;!--&lt;title&gt;Dust Doctors LLC Theme&lt;/title&gt;--&gt; &lt;title&gt;&lt;?php bloginfo('name');?&gt;&lt;/title&gt; &lt;link rel=&quot;shortcut icon&quot; href=&quot;&lt;?php echo get_theme_file_uri('/img/favicon.ico');?&gt;&quot;&gt; &lt;?php /*include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); */?&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class();?&gt; data-spy=&quot;scroll&quot; data-target=&quot;#navbarResponsive&quot;&gt; &lt;!-- Start Header Section --&gt; &lt;header id=&quot;home&quot;&gt; &lt;!-- Navigation --&gt; &lt;nav class=&quot;navbar navbar-expand-lg fixed-top&quot;&gt; &lt;div class=&quot;container-fluid&quot;&gt; &lt;a href=&quot;#home&quot; class=&quot;navbar-brand&quot;&gt;&lt;img src=&quot;&lt;?php echo get_theme_file_uri('/img/logo.jpeg');?&gt;&quot; alt=&quot;&quot;&gt;&lt;/a&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarResponsive&quot;&gt; &lt;span class=&quot;custom-toggler-icon&quot;&gt;&lt;i class=&quot;fas fa-bars&quot;&gt;&lt;/i&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarResponsive&quot;&gt; &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#aboutUs&quot; class=&quot;nav-link&quot;&gt;About Us&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#services&quot; class=&quot;nav-link&quot;&gt;Our Services&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#portfolio&quot; class=&quot;nav-link&quot;&gt;Portfolio&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#clients&quot; class=&quot;nav-link&quot;&gt;Clients&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#contact&quot; class=&quot;nav-link&quot;&gt;Contact Us&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#book&quot; class=&quot;nav-link&quot;&gt;Book Now&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#faq&quot; class=&quot;nav-link&quot;&gt;FAQ&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!-- End Navigation --&gt; &lt;/header&gt; &lt;!-- End Header Section --&gt; </code></pre> <p><code>footer.php</code>:</p> <pre><code>&lt;footer&gt; &lt;div class=&quot;container footer px-0&quot;&gt; &lt;hr class=&quot;socket&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-12 d-flex justify-content-center&quot;&gt; &lt;img src=&quot;img/logo.jpeg&quot; alt=&quot;&quot; class=&quot;brand__logo&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row outer&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row py-3&quot;&gt; &lt;!--&lt;div class=&quot;col-md-6 px-0 pr-md-3&quot;&gt;--&gt; &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt; &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Corporate Office&lt;/h5&gt; &lt;p&gt; &lt;i class=&quot;fas fa-map-marker&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;100 Street Name,&lt;br&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Our City, &lt;br&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;AA 10000 &lt;/p&gt; &lt;/div&gt; &lt;!-- End Column --&gt; &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt; &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Contact Info&lt;/h5&gt; &lt;p&gt;&lt;i class=&quot;fas fa-phone&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;(888) 888-8888 &lt;br&gt; &lt;i class=&quot;fas fa-envelope&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;[email protected] &lt;br&gt; &lt;i class=&quot;fas fa-fax&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;(888) 888-8888&lt;/p&gt; &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Follow Us On&lt;/h5&gt; &lt;ul class=&quot;social&quot;&gt; &lt;li&gt;&lt;span&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-facebook-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-twitter-square&quot; &gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-instagram&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-youtube-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;fab fa-linkedin&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!---&lt;div class=&quot;col-md-6 px-0 pr-md-3&quot;&gt;--&gt; &lt;div class=&quot;col-md-4 px-0 pl-md-3&quot;&gt; &lt;h5 class=&quot;text-theme util__margin__botom&quot;&gt;Useful Links&lt;/h5&gt; &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;PRIVACY POLICY&lt;/a&gt;&lt;br&gt; &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;TERMS&lt;/a&gt;&lt;br&gt; &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;COMPANY&lt;/a&gt;&lt;br&gt; &lt;i class=&quot;fas fa-link&quot;&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;#&quot; class=&quot;footer__link&quot;&gt;SERVICES&lt;/a&gt;&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- End Row --&gt; &lt;/div&gt; &lt;!-- End Container --&gt; &lt;hr class=&quot;socket&quot;&gt; &lt;div class=&quot;col-12 d-flex justify-content-center&quot;&gt; &lt;p class=&quot;text-center&quot;&gt;&amp;copy; Dust Doctors LLC 2021&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- End Row Outer --&gt; &lt;/div&gt; &lt;!-- End Container Fluid --&gt; &lt;/footer&gt; &lt;!-- Top Scroll --&gt; &lt;a href=&quot;#home&quot; class=&quot;top-scroll&quot;&gt; &lt;i class=&quot;fa fa-angle-up&quot;&gt;&lt;/i&gt; &lt;/a&gt; &lt;!-- End of Top Scroll --&gt; &lt;!-- Script Source Files --&gt; &lt;!-- Plugins.js --&gt; &lt;script src=&quot;js/plugins.js&quot;&gt;&lt;/script&gt; &lt;!-- Waypoints https://cdnjs.com/libraries/waypoints https://github.com/imakewebthings/waypoints --&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js&quot;&gt;&lt;/script&gt; &lt;!-- Font Awesome https://fontawesome.com/ https://use.fontawesome.com/releases/v5.13.0/js/all.js --&gt; &lt;script src=&quot;https://use.fontawesome.com/releases/v5.13.0/js/all.js&quot;&gt;&lt;/script&gt; &lt;!-- Lightbox Image Gallery https://cdnjs.com/libraries/lightbox2 https://lokeshdhakar.com/projects/lightbox2/ --&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js&quot;&gt;&lt;/script&gt; &lt;!-- Owl Carousel https://cdnjs.com/libraries/OwlCarousel2 http://owlcarousel2.github.io/OwlCarousel2/ --&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js&quot;&gt;&lt;/script&gt; &lt;!-- jQuery CounterUp https://www.jsdelivr.com/package/npm/jquery.counterup https://github.com/bfintal/Counter-Up2 --&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/[email protected]/jquery.counterup.min.js&quot;&gt;&lt;/script&gt; &lt;!-- Bootstrap Form Validator https://cdnjs.com/libraries/1000hz-bootstrap-validator --&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js&quot;&gt;&lt;/script&gt; &lt;!-- End of Script Source Files --&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><code>index.php</code>:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php get_footer();?&gt; </code></pre> <p><code>functions.php</code>:</p> <pre><code>&lt;?php function theme_assets(){ /*wp_enqueue_style('dust_doctors_main_styles',get_stylesheet_uri());*/ /* bootstrap*/ wp_enqueue_style('bootstrap','//cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css',array(),'v5.1.3',false); /* main css*/ wp_enqueue_style('main_style',get_theme_file_uri('/css/style.css'),array('bootstrap'),'1.0',false); /* plugins css*/ wp_enqueue_style('plugins_style',get_theme_file_uri('/css/plugins.css'),array(),'1.0',false); /* google fonts*/ wp_enqueue_style('google-fonts','//fonts.googleapis.com/css?family=Lato:300,400,700&amp;display=swap',array(),'1.0',false); /* animate css*/ wp_enqueue_style('animate-css','//cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css',array(),'v3.7.2',false); /* lightbox*/ wp_enqueue_style('lightbox','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css',array(),'v2.11.1',false); /* owl carousel */ wp_enqueue_style('owlcarousel1','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css',array(),'v2.3.4',false); wp_enqueue_style('owlcarousel2','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css',array(),'v2.3.4',false); /* jquery */ wp_enqueue_script('boot-jquery','//code.jquery.com/jquery-3.4.1.min.js',array('jquery'),'',false); /* bootstrap popper js*/ wp_enqueue_script('boot-popper-js','//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',array('jquery'),'v1.14.7',false); /* bootstrap main js*/ wp_enqueue_script('boot-main-js','//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',array('jquery'),'v4.3.1',false); /* main js script*/ wp_enqueue_script('plugin-js',get_theme_file_uri('/js/plugins.js'),array('jquery','jquery-ui-core','jquery-ui-selectmenu'),'1.0',true); /* waypoints*/ wp_enqueue_script('waypoints','//cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js',array('jquery'),'v4.0.1',true); /* font awesome */ wp_enqueue_script('font-awesome','//use.fontawesome.com/releases/v5.13.0/js/all.js',array(),'v5.13.0',true); /* lightbox */ wp_enqueue_script('lightbox-js','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js',array('jquery'),'v2.11.1',true); /* owl carousel */ wp_enqueue_script('owl-carousel-js','/cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js',array('jquery'),'v2.3.4',true); /* counter js */ wp_enqueue_script('counter-js','//cdn.jsdelivr.net/npm/[email protected]/jquery.counterup.min.js',array('jquery'),'v2.1.0',true); /* form validator*/ wp_enqueue_script('form-validator','//cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js',array('jquery'),'v0.11.9',true); } /* change login logo in wp-admin*/ function my_login_logo() { ?&gt; &lt;style type=&quot;text/css&quot;&gt; body.login{ background-image:url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/img/slide-02.jpeg); background-size: cover; background-position: center center; background-repeat:no-repeat; } #login h1 a, .login h1 a { background-image: url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/img/logo.jpeg); height:150px; width:150px; background-size: 150px 150px; background-repeat: no-repeat; padding-bottom: 30px; } &lt;/style&gt; &lt;?php } function my_login_logo_url() { return home_url(); } function my_login_logo_url_title() { return 'Dust Doctors LLC Login'; } function add_site_favicon() { echo '&lt;link rel=&quot;shortcut icon&quot; href=&quot;' . get_stylesheet_directory_uri() . '/img/favicon.ico&quot; /&gt;'; } /*function custom_unregister_theme_post_types() { global $wp_post_types; if ( isset( $wp_post_types[&quot;image&quot;] ) ) { unset( $wp_post_types[ &quot;image&quot; ] ); //UPDATED } } add_action( 'init', 'custom_unregister_theme_post_types', 20 );*/ add_action('wp_enqueue_scripts','theme_assets'); add_action( 'login_enqueue_scripts', 'my_login_logo' ); add_filter( 'login_headerurl', 'my_login_logo_url' ); add_filter( 'login_headertext', 'my_login_logo_url_title' ); add_action('login_head', 'add_site_favicon'); add_action('admin_head', 'add_site_favicon'); ?&gt; </code></pre> <p><code>front-page.php</code>:</p> <pre><code> &lt;?php get_header(); ?&gt; &lt;?php //custom fields $landing_background_image = get_field('landing_background_image'); $landing_header = get_field('landing_header'); if (empty($landing_header)){ $landing_header = 'looking for a cleaning service?'; } $landing_tag_line = get_field('landing_tag_line'); if (empty($landing_tag_line)){ $landing_tag_line = 'we are here to make your home shine'; } if (empty($landing_button)){ $landing_button = &quot;let's shine&quot;; } ?&gt; &lt;!-- Start Landing Page Section --&gt; &lt;section&gt; &lt;!-- Start Landing Page Image and Title --&gt; &lt;div class=&quot;landing&quot;&gt; &lt;div class=&quot;home-wrap&quot;&gt; &lt;!--&lt;div class=&quot;home-inner&quot;&gt;&lt;/div&gt;--&gt; &lt;ul class=&quot;home-slideshow&quot;&gt; &lt;li&gt; &lt;?php if(!empty($landing_background_image)){?&gt; &lt;span style=&quot;background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(&lt;?php echo $landing_background_image['url'];?&gt;)&quot;&gt;Image 01&lt;/span&gt; &lt;?php } else{?&gt; &lt;span style=&quot;background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(&lt;?php echo get_theme_file_uri('/img/slide-02.jpeg');?&gt;)&quot;&gt;Image 01&lt;/span&gt; &lt;?php }?&gt; &lt;!-- &lt;div class=&quot;slide__title text-center text-uppercase&quot;&gt; &lt;h1 class=&quot;slide__title__main&quot;&gt;looking for a cleaning service?&lt;/h1&gt; &lt;h3 class=&quot;slide__title__sub&quot;&gt;we are here to make your home shine&lt;/h3&gt;--&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- End Landing Page Image and Title--&gt; &lt;!-- Start Landing Page Button --&gt; &lt;div class=&quot;caption text-center text-light text-uppercase&quot;&gt; &lt;!--&lt;h1 class=&quot;caption__title__main os-animation&quot; data-animation=&quot;fadeInUp&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;1s&quot;&gt;looking for a cleaning service?&lt;/h1&gt; &lt;h3 class=&quot;caption__title__sub os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;2s&quot;&gt;we are here to make your home shine&lt;/h3&gt; &lt;a href=&quot;#booking&quot; class=&quot;btn btn__primary btn__animated os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;3s&quot;&gt;let's shine&lt;/a&gt;--&gt; &lt;h1 class=&quot;caption__title__main os-animation&quot; data-animation=&quot;fadeInUp&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;1s&quot;&gt;&lt;?php echo $landing_header;?&gt;&lt;/h1&gt; &lt;h3 class=&quot;caption__title__sub os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;2s&quot;&gt;&lt;?php echo $landing_tag_line;?&gt;&lt;/h3&gt; &lt;a href=&quot;#booking&quot; class=&quot;btn btn__primary btn__animated os-animation&quot; data-animation=&quot;fadeInUp&quot; data-delay=&quot;3s&quot;&gt;&lt;?php echo $landing_button;?&gt;&lt;/a&gt; &lt;/div&gt; &lt;!-- End Landing Page Button --&gt; &lt;!-- Start Bouncing Down Arrow --&gt; &lt;a href=&quot;#aboutUs&quot; class=&quot;down-arrow text-center&quot;&gt; &lt;!--&lt;div class=&quot;arrow d-none d-md-block&quot;&gt;--&gt; &lt;div class=&quot;arrow&quot;&gt; &lt;i class=&quot;fas fa-angle-down&quot;&gt;&lt;/i&gt; &lt;/div&gt; &lt;/a&gt; &lt;!-- End Bouncing Down Arrow --&gt; &lt;/section&gt; &lt;!-- End Landing Page Section --&gt; &lt;?php get_footer();?&gt; </code></pre>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/17
    [ "https://wordpress.stackexchange.com/questions/400397", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/216993/" ]
    I am creating a custom theme. In it I am trying to add salon booking plugin. This plugin creates default booking page. When I am viewing the booking page I cannot see the booking form. I have tried installing the salon booking plugin in WordPress default theme twenty twenty-one and it is working fine in this theme. Not sure what is breaking in my theme. In my theme I have added `wp_head()` just before end of head tag in `header.php`. I have also added `wp_footer()` just before the end of body tag in footer.php. I have following php files * `header.php` * `footer.php` * `functions.php` * `index.php` * `front-page.php` I have following pages - home page (that I created, this is pointing to front-page.php), Booking, Thank you for booking, Booking my account. Last three booking pages were created as part of the salon booking plugin. `header.php`: ``` <!DOCTYPE html> <html <?php language_attributes();?>> <head> <meta charset=<?php bloginfo('charset');?>> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!--<title>Dust Doctors LLC Theme</title>--> <title><?php bloginfo('name');?></title> <link rel="shortcut icon" href="<?php echo get_theme_file_uri('/img/favicon.ico');?>"> <?php /*include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); */?> <?php wp_head(); ?> </head> <body <?php body_class();?> data-spy="scroll" data-target="#navbarResponsive"> <!-- Start Header Section --> <header id="home"> <!-- Navigation --> <nav class="navbar navbar-expand-lg fixed-top"> <div class="container-fluid"> <a href="#home" class="navbar-brand"><img src="<?php echo get_theme_file_uri('/img/logo.jpeg');?>" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="custom-toggler-icon"><i class="fas fa-bars"></i></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a href="#aboutUs" class="nav-link">About Us</a> </li> <li class="nav-item"> <a href="#services" class="nav-link">Our Services</a> </li> <li class="nav-item"> <a href="#portfolio" class="nav-link">Portfolio</a> </li> <li class="nav-item"> <a href="#clients" class="nav-link">Clients</a> </li> <li class="nav-item"> <a href="#contact" class="nav-link">Contact Us</a> </li> <li class="nav-item"> <a href="#book" class="nav-link">Book Now</a> </li> <li class="nav-item"> <a href="#faq" class="nav-link">FAQ</a> </li> </ul> </div> </div> </nav> <!-- End Navigation --> </header> <!-- End Header Section --> ``` `footer.php`: ``` <footer> <div class="container footer px-0"> <hr class="socket"> <div class="row"> <div class="col-12 d-flex justify-content-center"> <img src="img/logo.jpeg" alt="" class="brand__logo"> </div> </div> <div class="row outer"> <div class="container"> <div class="row py-3"> <!--<div class="col-md-6 px-0 pr-md-3">--> <div class="col-md-4 px-0 pl-md-3"> <h5 class="text-theme util__margin__botom">Corporate Office</h5> <p> <i class="fas fa-map-marker"></i>&nbsp;&nbsp;&nbsp;&nbsp;100 Street Name,<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Our City, <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AA 10000 </p> </div> <!-- End Column --> <div class="col-md-4 px-0 pl-md-3"> <h5 class="text-theme util__margin__botom">Contact Info</h5> <p><i class="fas fa-phone"></i>&nbsp;&nbsp;&nbsp;&nbsp;(888) 888-8888 <br> <i class="fas fa-envelope"></i>&nbsp;&nbsp;&nbsp;&nbsp;[email protected] <br> <i class="fas fa-fax"></i>&nbsp;&nbsp;&nbsp;&nbsp;(888) 888-8888</p> <h5 class="text-theme util__margin__botom">Follow Us On</h5> <ul class="social"> <li><span><a href="#"><i class="fab fa-facebook-square"></i></a></span></li> <li><a href="#"><i class="fab fa-twitter-square" ></i></a></li> <li><a href="#"><i class="fab fa-instagram"></i></a></li> <li><a href="#"><i class="fab fa-youtube-square"></i></a></li> <li><a href="#"><i class="fab fa-linkedin"></i></a></li> </ul> </div> <!---<div class="col-md-6 px-0 pr-md-3">--> <div class="col-md-4 px-0 pl-md-3"> <h5 class="text-theme util__margin__botom">Useful Links</h5> <i class="fas fa-link"></i>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="footer__link">PRIVACY POLICY</a><br> <i class="fas fa-link"></i>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="footer__link">TERMS</a><br> <i class="fas fa-link"></i>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="footer__link">COMPANY</a><br> <i class="fas fa-link"></i>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="footer__link">SERVICES</a><br> </div> </div> <!-- End Row --> </div> <!-- End Container --> <hr class="socket"> <div class="col-12 d-flex justify-content-center"> <p class="text-center">&copy; Dust Doctors LLC 2021</p> </div> </div> <!-- End Row Outer --> </div> <!-- End Container Fluid --> </footer> <!-- Top Scroll --> <a href="#home" class="top-scroll"> <i class="fa fa-angle-up"></i> </a> <!-- End of Top Scroll --> <!-- Script Source Files --> <!-- Plugins.js --> <script src="js/plugins.js"></script> <!-- Waypoints https://cdnjs.com/libraries/waypoints https://github.com/imakewebthings/waypoints --> <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script> <!-- Font Awesome https://fontawesome.com/ https://use.fontawesome.com/releases/v5.13.0/js/all.js --> <script src="https://use.fontawesome.com/releases/v5.13.0/js/all.js"></script> <!-- Lightbox Image Gallery https://cdnjs.com/libraries/lightbox2 https://lokeshdhakar.com/projects/lightbox2/ --> <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js"></script> <!-- Owl Carousel https://cdnjs.com/libraries/OwlCarousel2 http://owlcarousel2.github.io/OwlCarousel2/ --> <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script> <!-- jQuery CounterUp https://www.jsdelivr.com/package/npm/jquery.counterup https://github.com/bfintal/Counter-Up2 --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/jquery.counterup.min.js"></script> <!-- Bootstrap Form Validator https://cdnjs.com/libraries/1000hz-bootstrap-validator --> <script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script> <!-- End of Script Source Files --> <?php wp_footer(); ?> </body> </html> ``` `index.php`: ``` <?php get_header(); ?> <?php get_footer();?> ``` `functions.php`: ``` <?php function theme_assets(){ /*wp_enqueue_style('dust_doctors_main_styles',get_stylesheet_uri());*/ /* bootstrap*/ wp_enqueue_style('bootstrap','//cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css',array(),'v5.1.3',false); /* main css*/ wp_enqueue_style('main_style',get_theme_file_uri('/css/style.css'),array('bootstrap'),'1.0',false); /* plugins css*/ wp_enqueue_style('plugins_style',get_theme_file_uri('/css/plugins.css'),array(),'1.0',false); /* google fonts*/ wp_enqueue_style('google-fonts','//fonts.googleapis.com/css?family=Lato:300,400,700&display=swap',array(),'1.0',false); /* animate css*/ wp_enqueue_style('animate-css','//cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css',array(),'v3.7.2',false); /* lightbox*/ wp_enqueue_style('lightbox','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css',array(),'v2.11.1',false); /* owl carousel */ wp_enqueue_style('owlcarousel1','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css',array(),'v2.3.4',false); wp_enqueue_style('owlcarousel2','//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css',array(),'v2.3.4',false); /* jquery */ wp_enqueue_script('boot-jquery','//code.jquery.com/jquery-3.4.1.min.js',array('jquery'),'',false); /* bootstrap popper js*/ wp_enqueue_script('boot-popper-js','//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',array('jquery'),'v1.14.7',false); /* bootstrap main js*/ wp_enqueue_script('boot-main-js','//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',array('jquery'),'v4.3.1',false); /* main js script*/ wp_enqueue_script('plugin-js',get_theme_file_uri('/js/plugins.js'),array('jquery','jquery-ui-core','jquery-ui-selectmenu'),'1.0',true); /* waypoints*/ wp_enqueue_script('waypoints','//cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js',array('jquery'),'v4.0.1',true); /* font awesome */ wp_enqueue_script('font-awesome','//use.fontawesome.com/releases/v5.13.0/js/all.js',array(),'v5.13.0',true); /* lightbox */ wp_enqueue_script('lightbox-js','//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js',array('jquery'),'v2.11.1',true); /* owl carousel */ wp_enqueue_script('owl-carousel-js','/cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js',array('jquery'),'v2.3.4',true); /* counter js */ wp_enqueue_script('counter-js','//cdn.jsdelivr.net/npm/[email protected]/jquery.counterup.min.js',array('jquery'),'v2.1.0',true); /* form validator*/ wp_enqueue_script('form-validator','//cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js',array('jquery'),'v0.11.9',true); } /* change login logo in wp-admin*/ function my_login_logo() { ?> <style type="text/css"> body.login{ background-image:url(<?php echo get_stylesheet_directory_uri(); ?>/img/slide-02.jpeg); background-size: cover; background-position: center center; background-repeat:no-repeat; } #login h1 a, .login h1 a { background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/img/logo.jpeg); height:150px; width:150px; background-size: 150px 150px; background-repeat: no-repeat; padding-bottom: 30px; } </style> <?php } function my_login_logo_url() { return home_url(); } function my_login_logo_url_title() { return 'Dust Doctors LLC Login'; } function add_site_favicon() { echo '<link rel="shortcut icon" href="' . get_stylesheet_directory_uri() . '/img/favicon.ico" />'; } /*function custom_unregister_theme_post_types() { global $wp_post_types; if ( isset( $wp_post_types["image"] ) ) { unset( $wp_post_types[ "image" ] ); //UPDATED } } add_action( 'init', 'custom_unregister_theme_post_types', 20 );*/ add_action('wp_enqueue_scripts','theme_assets'); add_action( 'login_enqueue_scripts', 'my_login_logo' ); add_filter( 'login_headerurl', 'my_login_logo_url' ); add_filter( 'login_headertext', 'my_login_logo_url_title' ); add_action('login_head', 'add_site_favicon'); add_action('admin_head', 'add_site_favicon'); ?> ``` `front-page.php`: ``` <?php get_header(); ?> <?php //custom fields $landing_background_image = get_field('landing_background_image'); $landing_header = get_field('landing_header'); if (empty($landing_header)){ $landing_header = 'looking for a cleaning service?'; } $landing_tag_line = get_field('landing_tag_line'); if (empty($landing_tag_line)){ $landing_tag_line = 'we are here to make your home shine'; } if (empty($landing_button)){ $landing_button = "let's shine"; } ?> <!-- Start Landing Page Section --> <section> <!-- Start Landing Page Image and Title --> <div class="landing"> <div class="home-wrap"> <!--<div class="home-inner"></div>--> <ul class="home-slideshow"> <li> <?php if(!empty($landing_background_image)){?> <span style="background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(<?php echo $landing_background_image['url'];?>)">Image 01</span> <?php } else{?> <span style="background-image: -webkit-linear-gradient(rgba(11,12,16,0.7) 30%,rgba(0,0,0,0.7)), url(<?php echo get_theme_file_uri('/img/slide-02.jpeg');?>)">Image 01</span> <?php }?> <!-- <div class="slide__title text-center text-uppercase"> <h1 class="slide__title__main">looking for a cleaning service?</h1> <h3 class="slide__title__sub">we are here to make your home shine</h3>--> </div> </li> </ul> </div> </div> <!-- End Landing Page Image and Title--> <!-- Start Landing Page Button --> <div class="caption text-center text-light text-uppercase"> <!--<h1 class="caption__title__main os-animation" data-animation="fadeInUp" data-animation="fadeInUp" data-delay="1s">looking for a cleaning service?</h1> <h3 class="caption__title__sub os-animation" data-animation="fadeInUp" data-delay="2s">we are here to make your home shine</h3> <a href="#booking" class="btn btn__primary btn__animated os-animation" data-animation="fadeInUp" data-delay="3s">let's shine</a>--> <h1 class="caption__title__main os-animation" data-animation="fadeInUp" data-animation="fadeInUp" data-delay="1s"><?php echo $landing_header;?></h1> <h3 class="caption__title__sub os-animation" data-animation="fadeInUp" data-delay="2s"><?php echo $landing_tag_line;?></h3> <a href="#booking" class="btn btn__primary btn__animated os-animation" data-animation="fadeInUp" data-delay="3s"><?php echo $landing_button;?></a> </div> <!-- End Landing Page Button --> <!-- Start Bouncing Down Arrow --> <a href="#aboutUs" class="down-arrow text-center"> <!--<div class="arrow d-none d-md-block">--> <div class="arrow"> <i class="fas fa-angle-down"></i> </div> </a> <!-- End Bouncing Down Arrow --> </section> <!-- End Landing Page Section --> <?php get_footer();?> ```
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,444
    <p>my javascript code isn't working. I put the js folder next to the other folders, the astra-child folder, astra folder and other themes. Is this correct. Then in the js folder, I created custom_script.js file and put the javascript in there. And in functions.php file enqueued it.</p> <pre class="lang-php prettyprint-override"><code>&lt;?php /** * Astra Child Theme functions and definitions * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package Astra Child * @since 1.0.0 */ /** * Define Constants */ define( 'CHILD_THEME_ASTRA_CHILD_VERSION', '1.0.0' ); /** * Enqueue styles */ function child_enqueue_styles() { wp_enqueue_style( 'astra-child-theme-css', get_stylesheet_directory_uri() . '/style.css', array('astra-theme-css'), CHILD_THEME_ASTRA_CHILD_VERSION, 'all' ); } add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 ); } function my_scripts_method() { wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', ); add_action( 'wp_enqueue_scripts', 'my_scripts_method'); } </code></pre>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/19
    [ "https://wordpress.stackexchange.com/questions/400444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205788/" ]
    my javascript code isn't working. I put the js folder next to the other folders, the astra-child folder, astra folder and other themes. Is this correct. Then in the js folder, I created custom\_script.js file and put the javascript in there. And in functions.php file enqueued it. ```php <?php /** * Astra Child Theme functions and definitions * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package Astra Child * @since 1.0.0 */ /** * Define Constants */ define( 'CHILD_THEME_ASTRA_CHILD_VERSION', '1.0.0' ); /** * Enqueue styles */ function child_enqueue_styles() { wp_enqueue_style( 'astra-child-theme-css', get_stylesheet_directory_uri() . '/style.css', array('astra-theme-css'), CHILD_THEME_ASTRA_CHILD_VERSION, 'all' ); } add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 ); } function my_scripts_method() { wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', ); add_action( 'wp_enqueue_scripts', 'my_scripts_method'); } ```
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,480
    <p>WordPress supports storing multiple post meta values for a single post using the same meta key. For example one post can have multiple instances of meta_key 'pet' with meta_value 'cat', 'dog', and/or 'fish'. This is super useful when using get_post_meta because you can get an array of all values for the pet meta key, versus managing a serialized array in a single field.</p> <p>It's also really useful when using a meta query, because you can query any post where meta_key 'pet' = 'cat', and get posts where any instance of 'pet' is equal to 'cat', regardless of how many other instances of the meta key may be associated with the post with different values.</p> <p>But is the opposite (e.g. <code>!=</code> or <code>NOT LIKE</code> or <code>NOT IN</code>) possible? I'm using the following and it's returning lots of posts that have one instance of meta_key 'pet' = 'cat'.</p> <pre><code>$pet_owners = new WP_Query([ 'post_type' =&gt; 'pet_owner', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; [ [ 'key' =&gt; 'pet', 'value' =&gt; 'cat', 'compare' =&gt; '!=' ] ] ]); </code></pre> <p><strong>Edit</strong>: I had an error in my pseudocode as flagged by Buttered_toast below.</p>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/20
    [ "https://wordpress.stackexchange.com/questions/400480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28924/" ]
    WordPress supports storing multiple post meta values for a single post using the same meta key. For example one post can have multiple instances of meta\_key 'pet' with meta\_value 'cat', 'dog', and/or 'fish'. This is super useful when using get\_post\_meta because you can get an array of all values for the pet meta key, versus managing a serialized array in a single field. It's also really useful when using a meta query, because you can query any post where meta\_key 'pet' = 'cat', and get posts where any instance of 'pet' is equal to 'cat', regardless of how many other instances of the meta key may be associated with the post with different values. But is the opposite (e.g. `!=` or `NOT LIKE` or `NOT IN`) possible? I'm using the following and it's returning lots of posts that have one instance of meta\_key 'pet' = 'cat'. ``` $pet_owners = new WP_Query([ 'post_type' => 'pet_owner', 'posts_per_page' => -1, 'meta_query' => [ [ 'key' => 'pet', 'value' => 'cat', 'compare' => '!=' ] ] ]); ``` **Edit**: I had an error in my pseudocode as flagged by Buttered\_toast below.
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,507
    <p>I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there. Would anybody know, how I could activate it, if that is the problem. Thanks</p>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/21
    [ "https://wordpress.stackexchange.com/questions/400507", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205788/" ]
    I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there. Would anybody know, how I could activate it, if that is the problem. Thanks
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,598
    <p>I am very new to HTML and PHP and have spent hours trying to find the right questions to ask. I would like to create a simple webform on a page and add a button that will generate text (on the same page) based on the variables answered in the webform. I don't need to/want to capture the data from the form. I <em>do not</em> want to show the output in a table format. If possible, I would like the output to be editable and have a copy button. The user would answer the questions they want to, then see the summary of their answers. Any questions they skipped would not show up in the summary. In an ideal situation, they would also be able to edit the compiled text before copying it.</p> <p><strong>Example:</strong></p> <p>Question 1 (required)<br /> Question 2 (optional)<br /> Question 3 (optional)</p> <p>[Generate]</p> <p>(On webpage, print:) &quot;Hello (Q1 answer). Based on your blah blah, we think your idea to (Q2 answer) is great!&quot;</p> <p>This is do-able, right? I feel like it is such a simple thing to do that no one talks about how to do it. I understand how to create forms and input fields, but I'm not sure how to make the generate button that will compile the answers from the questions into a paragraph on the page. Any syntax examples would be so, so helpful.</p> <p>Thank you!!</p>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/23
    [ "https://wordpress.stackexchange.com/questions/400598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217202/" ]
    I am very new to HTML and PHP and have spent hours trying to find the right questions to ask. I would like to create a simple webform on a page and add a button that will generate text (on the same page) based on the variables answered in the webform. I don't need to/want to capture the data from the form. I *do not* want to show the output in a table format. If possible, I would like the output to be editable and have a copy button. The user would answer the questions they want to, then see the summary of their answers. Any questions they skipped would not show up in the summary. In an ideal situation, they would also be able to edit the compiled text before copying it. **Example:** Question 1 (required) Question 2 (optional) Question 3 (optional) [Generate] (On webpage, print:) "Hello (Q1 answer). Based on your blah blah, we think your idea to (Q2 answer) is great!" This is do-able, right? I feel like it is such a simple thing to do that no one talks about how to do it. I understand how to create forms and input fields, but I'm not sure how to make the generate button that will compile the answers from the questions into a paragraph on the page. Any syntax examples would be so, so helpful. Thank you!!
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,712
    <p>I am trying to change the classes for the &quot;View cart&quot; button after adding an item to the cart. What I tried to do is to hook into the &quot;woocommerce_ajax_added_to_cart&quot; action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook:</p> <pre><code>function set_button_classes() { echo &quot;&lt;script&gt;document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');&lt;/script&gt;&quot;; } add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); </code></pre> <p>Any pointers would be really appreciated.</p>
    [ { "answer_id": 400400, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your theme does not contain a main post loop, so there is no place for the plugin to do its work</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n the_content();\n } // end while\n} // end if\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 400401, "author": "seshadri mandal", "author_id": 216993, "author_profile": "https://wordpress.stackexchange.com/users/216993", "pm_score": 0, "selected": false, "text": "<p>Thanks a ton. I now created two new php files page.php and single.php with following content and the issue got resolved.</p>\n \n<pre><code> &lt;div class=&quot;generic-content&quot;&gt; &lt;?php the_content();?&gt; &lt;/div&gt; \n</code></pre>\n\n" } ]
    2021/12/28
    [ "https://wordpress.stackexchange.com/questions/400712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217352/" ]
    I am trying to change the classes for the "View cart" button after adding an item to the cart. What I tried to do is to hook into the "woocommerce\_ajax\_added\_to\_cart" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook: ``` function set_button_classes() { echo "<script>document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');</script>"; } add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); ``` Any pointers would be really appreciated.
    Your theme does not contain a main post loop, so there is no place for the plugin to do its work ```php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post Content here // the_content(); } // end while } // end if ``` <https://codex.wordpress.org/The_Loop>
    400,820
    <p>I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?</p> <pre><code>&lt;?php add_action( 'template_redirect', function() { if ( is_page( 4848 ) ) { return; } wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) ); //wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) ); exit; } ); </code></pre>
    [ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
    2022/01/01
    [ "https://wordpress.stackexchange.com/questions/400820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/179876/" ]
    I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users? ``` <?php add_action( 'template_redirect', function() { if ( is_page( 4848 ) ) { return; } wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) ); //wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) ); exit; } ); ```
    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
    400,831
    <p>I am moving a site from a Genesis theme to Colorlib theme. The genesis theme includes <code>add_action( 'genesis_before_while', 'custom function' );</code> in a custom archive page, which loads restricted content from a template part. Is there a standard WP hook equivalent? or a work-around?</p>
    [ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
    2022/01/02
    [ "https://wordpress.stackexchange.com/questions/400831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/212424/" ]
    I am moving a site from a Genesis theme to Colorlib theme. The genesis theme includes `add_action( 'genesis_before_while', 'custom function' );` in a custom archive page, which loads restricted content from a template part. Is there a standard WP hook equivalent? or a work-around?
    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.