qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
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.