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
|
---|---|---|---|---|---|---|
406,131 | <p>Custom quicktags not working after Wordpress 6.0</p>
<p>wp 5.8.x/5.9.x: working --
wp 6.0: not working</p>
<p>Buttons are not showing here: <a href="https://imgur.com/a/T05o0WX" rel="nofollow noreferrer">https://imgur.com/a/T05o0WX</a></p>
<p>Console error: Uncaught ReferenceError: QTags is not defined</p>
<p>I am using this code.</p>
<pre><code> function my_quicktags() {
if ( wp_script_is( 'quicktags' ) ) {
?>
<script type="text/javascript">
QTags.addButton( 'eg_php', 'PHP', '<pre><code class=\"language-php\">', '</code></pre>', 'p', 'PHP Code', 200 );
QTags.addButton( 'eg_css', 'CSS', '<pre><code class=\"language-css\">', '</code></pre>', 'q', 'CSS Code', 201 );
QTags.addButton( 'eg_html', 'HTML', '<pre><code class=\"language-html\">', '</code></pre>', 'r', 'HTML Code', 202 );
QTags.addButton( 'eg_callback', 'CSS div', css_callback );
function css_callback(){
var css_class = prompt( 'Class name:', '' );
if ( css_class && css_class !== '' ) {
QTags.insertContent('<div class="' + css_class +'"></div>');
}
}
</script>
<?php
}
}
add_action( 'admin_print_footer_scripts', 'my_quicktags' );
</code></pre>
| [
{
"answer_id": 406152,
"author": "Nick R.",
"author_id": 222590,
"author_profile": "https://wordpress.stackexchange.com/users/222590",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. I fixed it by using the ep_enqueue_script aproach shown here: <a href=\"https://codex.wordpress.org/Quicktags_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Quicktags_API</a> listed under "A more modern example".</p>\n<p>It's the same thing that Tom mentions. Instead of using 'admin_print_fotter_scripts' to write an inline script on the page, the example shows putting the Qtags javascript in a separate JS file, and loading it with 'admin_enqueue_scripts' as the action and calling wp_enqueue_script.</p>\n<p>The Quicktags_API link above shows both methods, but the inline script method stoped working for me.</p>\n"
},
{
"answer_id": 406155,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>wp_add_inline_script</code> to add more quicktags, ensuring it only runs when <code>quicktags</code> is used, and runs after it's loaded:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function add_quicktag_paragraph() {\n wp_add_inline_script(\n 'quicktags',\n "QTags.addButton( 'eg_paragraph', 'p', '<p>', '</p>', 'p', 'Paragraph tag', 1 );"\n);\nadd_action( 'wp_enqueue_scripts', 'add_quicktag_paragraph' );\n</code></pre>\n<p>Here the second parameter of <code>wp_add_inline_script</code> gets put into a <code><script></code> tag by WordPress, and it places it so that it shows <em>after</em> quicktags is loaded, not before. I've places a single line of code in my example but you could insert multiple lines instead.</p>\n<p>This solves several problems the original snippet in the handbook had:</p>\n<ul>\n<li>it works on non-admin pages that use quicktags</li>\n<li>it always runs the code <em>after</em> quicktags is loaded, not before.</li>\n<li>no hardcoded script tags</li>\n<li>it's possible to filter and process this because of <code>wp_add_inline_script</code></li>\n<li>if a plugin removes the quicktags code then this will not show and break</li>\n</ul>\n<hr />\n<p>Another alternative is to write a JS file with your quicktags additions, and enqueue it, declaring quicktags as a dependency. This ensures it is always loaded in the correct order.</p>\n"
},
{
"answer_id": 406191,
"author": "kegnum",
"author_id": 222623,
"author_profile": "https://wordpress.stackexchange.com/users/222623",
"pm_score": 2,
"selected": false,
"text": "<p>Found a fix.</p>\n<pre><code> <script type="text/javascript">\n window.onload=function(){ \n\n\n }\n</script>\n</code></pre>\n<p>make sure the JS loads after the page fully loads this will allow the qtags js to work. Had the same issue as you right after I updated to 6.0. This fixed it for me.</p>\n"
},
{
"answer_id": 406200,
"author": "Dominator0",
"author_id": 130775,
"author_profile": "https://wordpress.stackexchange.com/users/130775",
"pm_score": 0,
"selected": false,
"text": "<p>Another fix..</p>\n<pre><code> <script type="text/javascript">\n window.addEventListener('DOMContentLoaded', () => {\n QTags.addButton( 'test', 'Test', '<test>', '</test>', 'test' );\n });\n </script>\n</code></pre>\n"
},
{
"answer_id": 413634,
"author": "charll",
"author_id": 229525,
"author_profile": "https://wordpress.stackexchange.com/users/229525",
"pm_score": 0,
"selected": false,
"text": "<p>This work for me (<a href=\"https://perishablepress.com/wordpress-fix-error-qtags-not-defined/\" rel=\"nofollow noreferrer\">more info</a>)</p>\n<p>My QTags:</p>\n<pre><code>QTags.addButton('codelights', 'CodeLights', btnAction);\n</code></pre>\n<p>I edit to:</p>\n<pre><code>window.onload = function() {\n QTags.addButton('codelights', 'CodeLights', btnAction);\n};\n</code></pre>\n"
}
] | 2022/05/26 | [
"https://wordpress.stackexchange.com/questions/406131",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130775/"
] | Custom quicktags not working after Wordpress 6.0
wp 5.8.x/5.9.x: working --
wp 6.0: not working
Buttons are not showing here: <https://imgur.com/a/T05o0WX>
Console error: Uncaught ReferenceError: QTags is not defined
I am using this code.
```
function my_quicktags() {
if ( wp_script_is( 'quicktags' ) ) {
?>
<script type="text/javascript">
QTags.addButton( 'eg_php', 'PHP', '<pre><code class=\"language-php\">', '</code></pre>', 'p', 'PHP Code', 200 );
QTags.addButton( 'eg_css', 'CSS', '<pre><code class=\"language-css\">', '</code></pre>', 'q', 'CSS Code', 201 );
QTags.addButton( 'eg_html', 'HTML', '<pre><code class=\"language-html\">', '</code></pre>', 'r', 'HTML Code', 202 );
QTags.addButton( 'eg_callback', 'CSS div', css_callback );
function css_callback(){
var css_class = prompt( 'Class name:', '' );
if ( css_class && css_class !== '' ) {
QTags.insertContent('<div class="' + css_class +'"></div>');
}
}
</script>
<?php
}
}
add_action( 'admin_print_footer_scripts', 'my_quicktags' );
``` | I had the same problem. I fixed it by using the ep\_enqueue\_script aproach shown here: <https://codex.wordpress.org/Quicktags_API> listed under "A more modern example".
It's the same thing that Tom mentions. Instead of using 'admin\_print\_fotter\_scripts' to write an inline script on the page, the example shows putting the Qtags javascript in a separate JS file, and loading it with 'admin\_enqueue\_scripts' as the action and calling wp\_enqueue\_script.
The Quicktags\_API link above shows both methods, but the inline script method stoped working for me. |
406,260 | <p>/wp-includes/class-wp-widget.php gives me an error for one blog, but not the other, and both have the same version of class-wp-widget.php which makes no sense to me.</p>
<blockquote>
<p>PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to
function WP_Widget::__construct(), 0 passed in
/home/www/stackexchange.com/wp-includes/class-wp-widget-factory.php on
line 61 and at least 2 expected in
/home/www/stackexchange.com/wp-includes/class-wp-widget.php:162</p>
</blockquote>
<p>Reading the code, it appears class-wp-widget.php is the root of the problem, but I could be wrong.</p>
<p>My other (working) blog on the same server has this same file and I don't get the error.</p>
<p>You can see the broken WordPress function here <a href="https://developer.wordpress.org/reference/classes/wp_widget/__construct/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/classes/wp_widget/__construct/</a></p>
<p>Is there a way to "turn off" widgets to deactivate this broken WordPress code?</p>
<p>Update: thanks @bosco for the idea, looking at the Stack trace helped...</p>
<pre><code>Stack trace:
#0 /home/www/example.com/wp-includes/class-wp-widget-factory.php(61): WP_Widget->__construct()
#1 /home/www/example.com/wp-includes/widgets.php(115): WP_Widget_Factory->register()
#2 /home/www/example.com/wp-content/themes/theme1516/includes/register-widgets.php(22): register_widget()
#3 /home/www/example.com/wp-includes/class-wp-hook.php(307): load_my_widgets()
#4 /home/www/example.com/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters()
#5 /home/www/example.com/wp-includes/plugin.php(476): WP_Hook->do_action()
#6 /home/www/example.com/wp-includes/widgets.php(1854)
</code></pre>
<p>Since "register-widgets.php" is the only non-core code here, and because I assume @bosco's comment is correct, I commented out the old widgets and that at least removed the "white screen of death" meanwhile the homepage looks wonky, will probably just cut/paste the HTML from the PHP 7.x site.</p>
| [
{
"answer_id": 406263,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect the cause is a custom widget that has been built incorrectly. Take a look at this example from the Codex:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class My_Widget extends WP_Widget {\n\n /**\n * Sets up the widgets name etc\n */\n public function __construct() {\n $widget_ops = array( \n 'classname' => 'my_widget',\n 'description' => 'My Widget is awesome',\n );\n parent::__construct( 'my_widget', 'My Widget', $widget_ops );\n }\n</code></pre>\n<p>What a lot of poorly built plugins do is this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class My_Widget extends WP_Widget {\n\n /**\n * Sets up the widgets name etc\n */\n public function __construct() {\n parent::__construct();\n }\n</code></pre>\n<p>Or they fail to include a <code>__construct</code> method at all! Passing no parameters or not having a constructor is incorrect. Past versions of PHP may have substituted these values for <code>null</code> or <code>undefined, resolving to </code>''`, but I would still have expected this to become a problem before upgrading to 8.1, and it would certainly have appeared in the error log as a notice.</p>\n<p>So identify which plugin or theme is responsible for this, either with stack traces, or a process of elimination, perhaps even by doing a search of the codebase with a tool.</p>\n<p>If this is in code that you maintain such as a custom theme or plugin, you can resolve the issue by implementing the Widget API correctly as the Codex and the devhub handbooks instruct. Specifically, by providing the first two parameters.</p>\n<p>If you're not interested in fixing the widgets, you can also remove them from your site completely.</p>\n<hr />\n<p>In the meantime, downgrade to 8.0 for a little while. Both 8.0 and 8.1 are currently supported versions of PHP and receiving updates. WordPress has yet to build official support for 8.0, and 8.1 is a very recent release ( early 2022 ), so it's unsurprising you encountered compatibility issues and clashes with 3rd party code when you upgraded.</p>\n"
},
{
"answer_id": 409112,
"author": "bndn",
"author_id": 225377,
"author_profile": "https://wordpress.stackexchange.com/users/225377",
"pm_score": 2,
"selected": false,
"text": "<p>In case you couldn’t revert to PHP older than 8.1 or fix the widget registration (and you trust your 10+ years old theme), you can update the line 61 of <code>wp-includes/class-wp-widget-factory.php</code> this way :</p>\n<pre><code>$this->widgets[ $widget ] = new $widget( $widget, $widget );\n</code></pre>\n<p>This may fix the widget registration.</p>\n"
},
{
"answer_id": 413021,
"author": "Mobination",
"author_id": 229270,
"author_profile": "https://wordpress.stackexchange.com/users/229270",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone still having this issue, you can try to go\n<code>wordpress/wp-includes/class-wp-widget-factory.php</code> on line 61 make this change to fix the issue without changing any other code:</p>\n<p>Change this: <code>$this->widgets[ $widget ] = new $widget();</code></p>\n<p>To: <code>$this->widgets[ $widget ] = new $widget( $widget, $widget );</code></p>\n<p>Everything should work as expected now.</p>\n"
}
] | 2022/05/30 | [
"https://wordpress.stackexchange.com/questions/406260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3453/"
] | /wp-includes/class-wp-widget.php gives me an error for one blog, but not the other, and both have the same version of class-wp-widget.php which makes no sense to me.
>
> PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to
> function WP\_Widget::\_\_construct(), 0 passed in
> /home/www/stackexchange.com/wp-includes/class-wp-widget-factory.php on
> line 61 and at least 2 expected in
> /home/www/stackexchange.com/wp-includes/class-wp-widget.php:162
>
>
>
Reading the code, it appears class-wp-widget.php is the root of the problem, but I could be wrong.
My other (working) blog on the same server has this same file and I don't get the error.
You can see the broken WordPress function here <https://developer.wordpress.org/reference/classes/wp_widget/__construct/>
Is there a way to "turn off" widgets to deactivate this broken WordPress code?
Update: thanks @bosco for the idea, looking at the Stack trace helped...
```
Stack trace:
#0 /home/www/example.com/wp-includes/class-wp-widget-factory.php(61): WP_Widget->__construct()
#1 /home/www/example.com/wp-includes/widgets.php(115): WP_Widget_Factory->register()
#2 /home/www/example.com/wp-content/themes/theme1516/includes/register-widgets.php(22): register_widget()
#3 /home/www/example.com/wp-includes/class-wp-hook.php(307): load_my_widgets()
#4 /home/www/example.com/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters()
#5 /home/www/example.com/wp-includes/plugin.php(476): WP_Hook->do_action()
#6 /home/www/example.com/wp-includes/widgets.php(1854)
```
Since "register-widgets.php" is the only non-core code here, and because I assume @bosco's comment is correct, I commented out the old widgets and that at least removed the "white screen of death" meanwhile the homepage looks wonky, will probably just cut/paste the HTML from the PHP 7.x site. | In case you couldn’t revert to PHP older than 8.1 or fix the widget registration (and you trust your 10+ years old theme), you can update the line 61 of `wp-includes/class-wp-widget-factory.php` this way :
```
$this->widgets[ $widget ] = new $widget( $widget, $widget );
```
This may fix the widget registration. |
406,490 | <p>The problem:</p>
<p>I want to run Wordpress 6.x with PHP 8.x in development mode - meaning <code>define('WP_DEBUG', true);</code> but Wordpress 6.x <a href="https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/" rel="nofollow noreferrer">partial support for PHP 8.x</a> throws a lot of deprecated warnings which do a lot of mess on the screen and also mess with cookies and REST API.</p>
<p>Setting <code>error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);</code> in <code>php.ini</code> or <code>wp-config.php</code> does not solve the problem because Wordpress overwrites this setting when you set <code>define('WP_DEBUG', true);</code> which you want normally have for the development.</p>
<p>The solution is no straight forward and I couldn't find fast, either on Stack or anywhere else so below I will answer my own question and solve the problem for others.</p>
| [
{
"answer_id": 406491,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 2,
"selected": false,
"text": "<p>The key to the solution is <code>enable_wp_debug_mode_checks</code> filter but to use it you have to do something special.</p>\n<p>As the <a href=\"https://developer.wordpress.org/reference/hooks/enable_wp_debug_mode_checks/\" rel=\"nofollow noreferrer\">documentation</a> says:</p>\n<blockquote>\n<p>This filter runs before it can be used by plugins. It is designed for\nnon-web runtimes. Returning false causes the WP_DEBUG and related\nconstants to not be checked and the default PHP values for errors will\nbe used unless you take care to update them yourself.</p>\n<p>To use this filter you must define a $wp_filter global before\nWordPress loads, usually in wp-config.php.</p>\n</blockquote>\n<p>Then when you disable this default error reporting overwrite - you can set your own.\nSo the final solution looks like this:</p>\n<pre><code>define('WP_DEBUG', true);\n\nif (WP_DEBUG) {\n define('WP_DEBUG_LOG', true);\n define('WP_DEBUG_DISPLAY', true);\n\n // disable friendly non informative error messages\n define('WP_DISABLE_FATAL_ERROR_HANDLER', true);\n\n $GLOBALS['wp_filter'] = [\n 'enable_wp_debug_mode_checks' => [\n 10 => [[\n 'accepted_args' => 0,\n 'function' => function() { return false; },\n ]],\n ],\n ];\n}\n\nerror_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);\n</code></pre>\n<p>Unfortunately it turns off automatically also deprecated messages from your own code, but what can you do until Wordpress solves its deprecated code fragments.</p>\n"
},
{
"answer_id": 408781,
"author": "Mark B",
"author_id": 174879,
"author_profile": "https://wordpress.stackexchange.com/users/174879",
"pm_score": 2,
"selected": false,
"text": "<p>change the line that sets error_reporting in wp-includes/load.php, probably around line 450:</p>\n<pre><code>if ( WP_DEBUG ) {\n error_reporting( E_ALL);\n</code></pre>\n<p>just add the <code> & ~E_DEPRECATED</code> bit so it becomes:</p>\n<pre><code>if ( WP_DEBUG ) {\n error_reporting( E_ALL & ~E_DEPRECATED );\n</code></pre>\n<p>[wordpress rant] - why would they not put something like this in the config file? In my (painful) experience of writing plugins & child themes for wordpress it's impossible to use debug mode not because of problems in my code but deprecated code in literally dozens of files throughout the codebase, ALWAYS. This renders WP_DEBUG useless. And don't get me started about how simple it would be to implement by default the multi-environment support I always have to hack into the wp-config.php file (I assume everyone else probably does this too) :-( [rant over(!!)]</p>\n"
}
] | 2022/06/07 | [
"https://wordpress.stackexchange.com/questions/406490",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118566/"
] | The problem:
I want to run Wordpress 6.x with PHP 8.x in development mode - meaning `define('WP_DEBUG', true);` but Wordpress 6.x [partial support for PHP 8.x](https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/) throws a lot of deprecated warnings which do a lot of mess on the screen and also mess with cookies and REST API.
Setting `error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);` in `php.ini` or `wp-config.php` does not solve the problem because Wordpress overwrites this setting when you set `define('WP_DEBUG', true);` which you want normally have for the development.
The solution is no straight forward and I couldn't find fast, either on Stack or anywhere else so below I will answer my own question and solve the problem for others. | The key to the solution is `enable_wp_debug_mode_checks` filter but to use it you have to do something special.
As the [documentation](https://developer.wordpress.org/reference/hooks/enable_wp_debug_mode_checks/) says:
>
> This filter runs before it can be used by plugins. It is designed for
> non-web runtimes. Returning false causes the WP\_DEBUG and related
> constants to not be checked and the default PHP values for errors will
> be used unless you take care to update them yourself.
>
>
> To use this filter you must define a $wp\_filter global before
> WordPress loads, usually in wp-config.php.
>
>
>
Then when you disable this default error reporting overwrite - you can set your own.
So the final solution looks like this:
```
define('WP_DEBUG', true);
if (WP_DEBUG) {
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', true);
// disable friendly non informative error messages
define('WP_DISABLE_FATAL_ERROR_HANDLER', true);
$GLOBALS['wp_filter'] = [
'enable_wp_debug_mode_checks' => [
10 => [[
'accepted_args' => 0,
'function' => function() { return false; },
]],
],
];
}
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
```
Unfortunately it turns off automatically also deprecated messages from your own code, but what can you do until Wordpress solves its deprecated code fragments. |
406,541 | <p>I am using the following filter to select <code><a></code> tags from a specific menu that have no attributes (href, class, etc.) and replace them with <code><button></code> tags.</p>
<pre><code>add_filter( 'wp_nav_menu_items', 'filter_empty_anchor_items', 10, 2 );
function filter_empty_anchor_items( $items, $args ) {
if( $args->theme_location == 'want-to-navigation') {
$pattern = '/<a>(.*?)<\/a>/s';
$items = preg_replace($pattern, '<button>$1</button>', $items );
}
return $items;
}
</code></pre>
<p>The filter itself is working, but I need to adjust the regular expression or run a second pass of a separate regular expression to select the text within the <code><button></code> tag and wrap it with a <code><span></code> tag.</p>
<p>The following <code>wp_nav_menu</code> code is being used to display the menu with a <code><svg></code> attached to the <code>link_after</code> argument.</p>
<pre><code>$args = array(
"theme_location" => "want-to-navigation",
"menu_id" => "want-to-navigation",
"container" => "false",
"container_id" => "want-to",
"container_class" => "quicklinks",
"link_after" => '<svg viewBox="0 0 448 512" xmlns="http://www.w3.org/2000/svg"><path d="m432 256c0 17.69-14.33 32.01-32 32.01h-144v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144h-144c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99h144v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144c17.7-.01 32 14.29 32 31.99z"/></svg>',
);
echo wp_nav_menu( $args );
</code></pre>
<p>An example: Select <code><button></code><strong>Select this text and wrap with span</strong><code><svg></svg></button></code></p>
| [
{
"answer_id": 406548,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Just use <code>link_before</code> in your <code>wp_nav_menu</code> <code>$args</code> and add opening/closing span tags:</p>\n<pre><code>$args = [\n 'link_before' => '<span>',\n /* Add closing </span> to link_after */\n 'link_after' => '</span><svg>...</svg>',\n\n // Other args\n];\n</code></pre>\n"
},
{
"answer_id": 406549,
"author": "Mike Hermary",
"author_id": 20357,
"author_profile": "https://wordpress.stackexchange.com/users/20357",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution with assistance from TheDeadMedic.</p>\n<p>I added the <code><svg></code> code to the replacement value in the <code>preg_replace</code> function, then added the opening and closing <code><span></code> tags to the <code>link_before</code> and <code>link_after</code> arguments in the theme template file.</p>\n<p>Nav menu items filter</p>\n<pre><code>add_filter( 'wp_nav_menu_items', 'filter_empty_anchor_items', 10, 2 );\nfunction filter_empty_anchor_items( $items, $args ) {\n if( $args->theme_location == 'want-to-navigation') {\n $pattern = '/<a>(.*?)<\\/a>/s';\n $replacement = '<button>$1<svg viewBox="0 0 448 512" xmlns="http://www.w3.org/2000/svg"><path d="m432 256c0 17.69-14.33 32.01-32 32.01h-144v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144h-144c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99h144v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144c17.7-.01 32 14.29 32 31.99z"/></svg></button>';\n $items = preg_replace($pattern, $replacement, $items );\n }\n return $items;\n}\n</code></pre>\n<p>Nav menu output</p>\n<pre><code>$args = array(\n "theme_location" => "want-to-navigation",\n "menu_id" => "want-to-navigation",\n "container" => "false",\n "container_id" => "want-to",\n "container_class" => "quicklinks",\n "link_before" => '<span>',\n "link_after" => '</span>',\n);\n</code></pre>\n<p>I hope this is helpful to others needing to achieve something similar.</p>\n"
}
] | 2022/06/08 | [
"https://wordpress.stackexchange.com/questions/406541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20357/"
] | I am using the following filter to select `<a>` tags from a specific menu that have no attributes (href, class, etc.) and replace them with `<button>` tags.
```
add_filter( 'wp_nav_menu_items', 'filter_empty_anchor_items', 10, 2 );
function filter_empty_anchor_items( $items, $args ) {
if( $args->theme_location == 'want-to-navigation') {
$pattern = '/<a>(.*?)<\/a>/s';
$items = preg_replace($pattern, '<button>$1</button>', $items );
}
return $items;
}
```
The filter itself is working, but I need to adjust the regular expression or run a second pass of a separate regular expression to select the text within the `<button>` tag and wrap it with a `<span>` tag.
The following `wp_nav_menu` code is being used to display the menu with a `<svg>` attached to the `link_after` argument.
```
$args = array(
"theme_location" => "want-to-navigation",
"menu_id" => "want-to-navigation",
"container" => "false",
"container_id" => "want-to",
"container_class" => "quicklinks",
"link_after" => '<svg viewBox="0 0 448 512" xmlns="http://www.w3.org/2000/svg"><path d="m432 256c0 17.69-14.33 32.01-32 32.01h-144v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144h-144c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99h144v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144c17.7-.01 32 14.29 32 31.99z"/></svg>',
);
echo wp_nav_menu( $args );
```
An example: Select `<button>`**Select this text and wrap with span**`<svg></svg></button>` | Just use `link_before` in your `wp_nav_menu` `$args` and add opening/closing span tags:
```
$args = [
'link_before' => '<span>',
/* Add closing </span> to link_after */
'link_after' => '</span><svg>...</svg>',
// Other args
];
``` |
406,607 | <p>When I add 'author' I only get results from "post" but no results are received from the "my_post_type_name"
My code:</p>
<pre><code>$args = array(
'author' => $user_id,
'post_type' => array('my_post_type_name', 'post'),
);
$wp_query = new WP_Query( $args );
</code></pre>
<p>Is it possible? Or do I need two query?</p>
| [
{
"answer_id": 406548,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Just use <code>link_before</code> in your <code>wp_nav_menu</code> <code>$args</code> and add opening/closing span tags:</p>\n<pre><code>$args = [\n 'link_before' => '<span>',\n /* Add closing </span> to link_after */\n 'link_after' => '</span><svg>...</svg>',\n\n // Other args\n];\n</code></pre>\n"
},
{
"answer_id": 406549,
"author": "Mike Hermary",
"author_id": 20357,
"author_profile": "https://wordpress.stackexchange.com/users/20357",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution with assistance from TheDeadMedic.</p>\n<p>I added the <code><svg></code> code to the replacement value in the <code>preg_replace</code> function, then added the opening and closing <code><span></code> tags to the <code>link_before</code> and <code>link_after</code> arguments in the theme template file.</p>\n<p>Nav menu items filter</p>\n<pre><code>add_filter( 'wp_nav_menu_items', 'filter_empty_anchor_items', 10, 2 );\nfunction filter_empty_anchor_items( $items, $args ) {\n if( $args->theme_location == 'want-to-navigation') {\n $pattern = '/<a>(.*?)<\\/a>/s';\n $replacement = '<button>$1<svg viewBox="0 0 448 512" xmlns="http://www.w3.org/2000/svg"><path d="m432 256c0 17.69-14.33 32.01-32 32.01h-144v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144h-144c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99h144v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144c17.7-.01 32 14.29 32 31.99z"/></svg></button>';\n $items = preg_replace($pattern, $replacement, $items );\n }\n return $items;\n}\n</code></pre>\n<p>Nav menu output</p>\n<pre><code>$args = array(\n "theme_location" => "want-to-navigation",\n "menu_id" => "want-to-navigation",\n "container" => "false",\n "container_id" => "want-to",\n "container_class" => "quicklinks",\n "link_before" => '<span>',\n "link_after" => '</span>',\n);\n</code></pre>\n<p>I hope this is helpful to others needing to achieve something similar.</p>\n"
}
] | 2022/06/09 | [
"https://wordpress.stackexchange.com/questions/406607",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223011/"
] | When I add 'author' I only get results from "post" but no results are received from the "my\_post\_type\_name"
My code:
```
$args = array(
'author' => $user_id,
'post_type' => array('my_post_type_name', 'post'),
);
$wp_query = new WP_Query( $args );
```
Is it possible? Or do I need two query? | Just use `link_before` in your `wp_nav_menu` `$args` and add opening/closing span tags:
```
$args = [
'link_before' => '<span>',
/* Add closing </span> to link_after */
'link_after' => '</span><svg>...</svg>',
// Other args
];
``` |
406,640 | <p>I am trying to remove some script files added by wordpress. However, the code I wrote does not work. Where am I doing wrong? Can you show me the way?</p>
<p>I looked at many sources. But I couldn't find an answer for the ui. I have used the wp_dequeue_script function many times. But it doesn't work for Wordpress.</p>
<p>child theme function.php</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'a_remove_some_js');
function a_remove_some_js() {
//wp_dequeue_script( 'jquery-ui-core-js');
//wp_dequeue_script( 'jquery-ui-tooltip-js');
wp_dequeue_script( 'jquery-ui-core');
wp_dequeue_script( 'jquery-ui-tooltip');
}
</code></pre>
| [
{
"answer_id": 406645,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The related library is registered with a function called <a href=\"https://developer.wordpress.org/reference/functions/wp_default_scripts/\" rel=\"nofollow noreferrer\">wp_default_scripts</a>.\nFile location (for Wordpress 6.0): <strong>...<a href=\"https://github.com/WordPress/WordPress/blob/df0d9100070579ef83b4acd0db865232d4a0e58a/wp-includes/script-loader.php#L1446\" rel=\"nofollow noreferrer\">wp-includes/script-loader.php</a></strong>\nremove to remove the relevant script; The add function is used to add a new script.</p>\n<pre><code>/**\n * Assigns default styles to $styles object.\n *\n * Nothing is returned, because the $styles parameter is passed by reference.\n * Meaning that whatever object is passed will be updated without having to\n * reassign the variable that was passed back to the same value. This saves\n * memory.\n *\n * Adding default styles is not the only task, it also assigns the base_url\n * property, the default version, and text direction for the object.\n *\n * @since 2.6.0\n *\n * @global array $editor_styles\n *\n * @param WP_Styles $styles\n */\n\n\nadd_action( 'wp_default_scripts', 'remove_js_ui_library' );\nfunction remove_js_ui_library( &$scripts){\n if(!is_admin()){\n $scripts->remove( 'jquery-ui-core');\n}\n</code></pre>\n<p>}</p>\n"
},
{
"answer_id": 410065,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>It is add_action, not a filter hook - @ddisdevelpgelis</p>\n<p>You added it as a filter hook in below code</p>\n<pre><code>add_filter( 'wp_default_scripts', 'remove_js_ui_library' );\nfunction remove_js_ui_library( &$scripts){\n if(!is_admin()){\n $scripts->remove( 'jquery-ui-core');\n }\n}\n</code></pre>\n<p>My changes to the above code :</p>\n<pre><code>add_action( 'wp_default_scripts', 'remove_js_ui_library' );\nfunction remove_js_ui_library( &$scripts){\n if(!is_admin()){\n $scripts->remove( 'jquery-ui-core');\n }\n}\n</code></pre>\n<p>Checkout this link for more information - <a href=\"https://developer.wordpress.org/reference/hooks/wp_default_scripts/\" rel=\"nofollow noreferrer\">wp_default_scripts</a></p>\n"
}
] | 2022/06/10 | [
"https://wordpress.stackexchange.com/questions/406640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I am trying to remove some script files added by wordpress. However, the code I wrote does not work. Where am I doing wrong? Can you show me the way?
I looked at many sources. But I couldn't find an answer for the ui. I have used the wp\_dequeue\_script function many times. But it doesn't work for Wordpress.
child theme function.php
```
add_action( 'wp_enqueue_scripts', 'a_remove_some_js');
function a_remove_some_js() {
//wp_dequeue_script( 'jquery-ui-core-js');
//wp_dequeue_script( 'jquery-ui-tooltip-js');
wp_dequeue_script( 'jquery-ui-core');
wp_dequeue_script( 'jquery-ui-tooltip');
}
``` | The related library is registered with a function called [wp\_default\_scripts](https://developer.wordpress.org/reference/functions/wp_default_scripts/).
File location (for Wordpress 6.0): **...[wp-includes/script-loader.php](https://github.com/WordPress/WordPress/blob/df0d9100070579ef83b4acd0db865232d4a0e58a/wp-includes/script-loader.php#L1446)**
remove to remove the relevant script; The add function is used to add a new script.
```
/**
* Assigns default styles to $styles object.
*
* Nothing is returned, because the $styles parameter is passed by reference.
* Meaning that whatever object is passed will be updated without having to
* reassign the variable that was passed back to the same value. This saves
* memory.
*
* Adding default styles is not the only task, it also assigns the base_url
* property, the default version, and text direction for the object.
*
* @since 2.6.0
*
* @global array $editor_styles
*
* @param WP_Styles $styles
*/
add_action( 'wp_default_scripts', 'remove_js_ui_library' );
function remove_js_ui_library( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery-ui-core');
}
```
} |
406,644 | <p>I have a template that adds a shortcode. The add_shortcode is at the top of the template, before any template output. Note that any attributes for the shortcode are optional. I don't care if they exist or not. I will just test for the attribute values and do something if they exist.</p>
<p>When are the shortcode attributes available for use in the template? Psuedocode example ($atts are the shortcode's attributes array):</p>
<pre><code>// template header is here
// add the shortcode
add_shortcode("mycode", "myshortcodefunction");
// is $atts available here? Because they are need by the next
// included function
include('someotherfunction.php'); // edited to add this line
function myshortcodefunction() {
echo "a shortcode processed here ";
echo "and here are the attributes:<br>";
print_r($atts);
return;
}
// is $atts available here?
// template code here
// show the page content in the loop
the_post();
// is $atts available here?
// end of template
// is $atts available here?
</code></pre>
<p>In which of those 'spots' in the template page code does $atts contain the shortcode parameters? And how do I use those parameters outside of the add_shortcode function?</p>
<p>Can I create a constant that contains $atts?</p>
<p>// ending template stuff</p>
<p><strong>Added</strong></p>
<p>The overall intent of my project is to use the attributes in an 'included' function that is loaded after the add_shortcode statement. That included function does a lot of work, including displaying text (a form), and using the shortcode attributes in other parts of that included function.</p>
<p>So, I need access to the shortcode attributes <strong>before</strong> the content (and it's shortcode) is processed.... in the first "is $atts available here" after the add_shortcode.</p>
<p>I've also changed the pseudocode above to show where that included function is placed - directly after the add_shortcode.</p>
| [
{
"answer_id": 406647,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>I need access to the shortcode attributes <strong>before</strong> the content (and\nit's shortcode) is processed.... in the first "is $atts available\nhere" after the add_shortcode</p>\n</blockquote>\n<p>In that case, you can manually parse the shortcode and retrieve its attributes (if any) like so, which uses <a href=\"https://developer.wordpress.org/reference/functions/get_shortcode_regex/\" rel=\"nofollow noreferrer\"><code>get_shortcode_regex()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/shortcode_parse_atts/\" rel=\"nofollow noreferrer\"><code>shortcode_parse_atts()</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$content = 'before blah2 [foo bar="baz" num="123"] after';\n\npreg_match( '/' . get_shortcode_regex() . '/s', $content, $matches );\n$atts = isset( $matches[3] ) ? shortcode_parse_atts( $matches[3] ) : '';\n\nvar_dump( $atts );\n/* Output:\narray(2) {\n ["bar"]=>\n string(3) "baz"\n ["num"]=>\n string(3) "123"\n}\n*/\n</code></pre>\n<ul>\n<li>Note that the above will only retrieve the attributes of the <em>first</em> shortcode found in <code>$content</code>. So use that code only if you're sure the content would never contain any other shortcodes..</li>\n</ul>\n<p>Or you can try this function which parses all shortcodes of <strong>a certain tag</strong> and return an array of attributes:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function my_shortcode_parse_atts( $text, $tag ) {\n $all_atts = array();\n\n preg_match_all( '/' . get_shortcode_regex() . '/s', $text, $matches );\n\n // If the shortcode ($tag) is found in $text, we parse the attributes.\n if ( isset( $matches[3] ) ) {\n // $matches[3] is the attributes string like ' bar="baz" num="123"'\n foreach ( $matches[3] as $i => $s ) {\n if ( $tag === $matches[2][ $i ] ) {\n $all_atts[] = shortcode_parse_atts( $s );\n }\n }\n }\n\n return $all_atts;\n}\n</code></pre>\n<ul>\n<li><p>Sample usage and output:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$content = 'before [foo] blah2 [foo bar="baz" num="123"] after';\n$all_atts = my_shortcode_parse_atts( $content, 'foo' );\n\nvar_dump( $all_atts );\n/* Output:\narray(2) {\n [0]=>\n string(0) ""\n [1]=>\n array(2) {\n ["bar"]=>\n string(3) "baz"\n ["num"]=>\n string(3) "123"\n }\n}\n*/\n</code></pre>\n<p>Note: In the above <code>$content</code>, there are 2 instances of the <code>foo</code> shortcode; one without any attributes, and the other with 2 attributes.</p>\n</li>\n</ul>\n<p>Also, I used a dummy text, so it's up to you on how to get the actual <code>$content</code>'s value..</p>\n"
},
{
"answer_id": 406679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>The answer from @SallyCJ got me started on the solution that worked best for me. It uses some of her code. There are references to other resources that helped out.</p>\n<pre><code>function my_get_shortcode_atts($shortcode_id) {\n/* given the $shortcode_id you are looking for, find it in the content\n before the loop \n returns an array of the $atts element from the content\n the array will be empty if there are no attributes for the shortcode\n*/\n\n\n// get the content before the loop \n// (see https://wordpress.stackexchange.com/a/377671/29416 )\nglobal $post;\n$pageID = $post->ID;\n$fst_content = get_the_content(null, false, $pageID);\n\n// extract shortcode attributes \n// (from https://wordpress.stackexchange.com/a/172285/29416\npreg_match_all( '/' . get_shortcode_regex() . '/s', $fst_content , $matches );\n $shortcode_atts = array();\n if( isset( $matches[2] ) )\n {\n foreach( (array) $matches[2] as $key => $value )\n {\n if( $shortcode_id === $value )\n $shortcode_atts[] = shortcode_parse_atts( $matches[3][$key] );\n }\n }\n if (! count($shortcode_atts)) { // this returns false if shortcode not found\n return array();\n }\n// 0th element is the attributes, so we get just that; \n// if there is more than one, you may need to adjust this part\n$shortcode_atts = $shortcode_atts[0];\ndefine("SHORTCODE_ATTS", $shortcode_atts); // so I can use the $atts anywhere\nreturn $shortcode_atts;\n}\n</code></pre>\n<p>Once I have the attributes, I can use this in my 'big function file' to set some constants:</p>\n<pre><code> if (function_exists('get_bloginfo')) { \n // get_bloginfo function won't exist in non-WP environment\n // you can use other WP-unique functions if you wish\n // get shortcode atts into an array, otherwise false\n $atts = my_get_shortcode_atts("my_shortcode_name");\n // do whatever you want with the atts\n // you may want to test for no shortcode attributes ($atts will be false)\n // in my case, I'll use the constant defined to do things\n }\n</code></pre>\n<p>Now I can use my 'big functions file' in non-WP environments, as well as with shortcodes in a WP post/page. And the SHORTCODE_ATTS constant is used to do things based on the attributes (if any) found in the shortcode.</p>\n<p>Since this is the solution that worked for me, it will be marked as such. But an upvote given on @SallyCJ's answer because it helped me with the above solution.</p>\n"
}
] | 2022/06/10 | [
"https://wordpress.stackexchange.com/questions/406644",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | I have a template that adds a shortcode. The add\_shortcode is at the top of the template, before any template output. Note that any attributes for the shortcode are optional. I don't care if they exist or not. I will just test for the attribute values and do something if they exist.
When are the shortcode attributes available for use in the template? Psuedocode example ($atts are the shortcode's attributes array):
```
// template header is here
// add the shortcode
add_shortcode("mycode", "myshortcodefunction");
// is $atts available here? Because they are need by the next
// included function
include('someotherfunction.php'); // edited to add this line
function myshortcodefunction() {
echo "a shortcode processed here ";
echo "and here are the attributes:<br>";
print_r($atts);
return;
}
// is $atts available here?
// template code here
// show the page content in the loop
the_post();
// is $atts available here?
// end of template
// is $atts available here?
```
In which of those 'spots' in the template page code does $atts contain the shortcode parameters? And how do I use those parameters outside of the add\_shortcode function?
Can I create a constant that contains $atts?
// ending template stuff
**Added**
The overall intent of my project is to use the attributes in an 'included' function that is loaded after the add\_shortcode statement. That included function does a lot of work, including displaying text (a form), and using the shortcode attributes in other parts of that included function.
So, I need access to the shortcode attributes **before** the content (and it's shortcode) is processed.... in the first "is $atts available here" after the add\_shortcode.
I've also changed the pseudocode above to show where that included function is placed - directly after the add\_shortcode. | The answer from @SallyCJ got me started on the solution that worked best for me. It uses some of her code. There are references to other resources that helped out.
```
function my_get_shortcode_atts($shortcode_id) {
/* given the $shortcode_id you are looking for, find it in the content
before the loop
returns an array of the $atts element from the content
the array will be empty if there are no attributes for the shortcode
*/
// get the content before the loop
// (see https://wordpress.stackexchange.com/a/377671/29416 )
global $post;
$pageID = $post->ID;
$fst_content = get_the_content(null, false, $pageID);
// extract shortcode attributes
// (from https://wordpress.stackexchange.com/a/172285/29416
preg_match_all( '/' . get_shortcode_regex() . '/s', $fst_content , $matches );
$shortcode_atts = array();
if( isset( $matches[2] ) )
{
foreach( (array) $matches[2] as $key => $value )
{
if( $shortcode_id === $value )
$shortcode_atts[] = shortcode_parse_atts( $matches[3][$key] );
}
}
if (! count($shortcode_atts)) { // this returns false if shortcode not found
return array();
}
// 0th element is the attributes, so we get just that;
// if there is more than one, you may need to adjust this part
$shortcode_atts = $shortcode_atts[0];
define("SHORTCODE_ATTS", $shortcode_atts); // so I can use the $atts anywhere
return $shortcode_atts;
}
```
Once I have the attributes, I can use this in my 'big function file' to set some constants:
```
if (function_exists('get_bloginfo')) {
// get_bloginfo function won't exist in non-WP environment
// you can use other WP-unique functions if you wish
// get shortcode atts into an array, otherwise false
$atts = my_get_shortcode_atts("my_shortcode_name");
// do whatever you want with the atts
// you may want to test for no shortcode attributes ($atts will be false)
// in my case, I'll use the constant defined to do things
}
```
Now I can use my 'big functions file' in non-WP environments, as well as with shortcodes in a WP post/page. And the SHORTCODE\_ATTS constant is used to do things based on the attributes (if any) found in the shortcode.
Since this is the solution that worked for me, it will be marked as such. But an upvote given on @SallyCJ's answer because it helped me with the above solution. |
406,687 | <p><strong>Hello</strong>, I have this code so when I place the <strong>[need_login]</strong> shortcode on a page, it redirects users who are not logged in to a <strong>Login page</strong>. The problem with this is the that it redirects them to the default WordPress page. How can I add the <strong>url</strong> of the page I want them to be redirected to.</p>
<pre><code>
function shortcode_needLogin() {
if (!is_user_logged_in()) {
auth_redirect();
}
}
</code></pre>
| [
{
"answer_id": 406647,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>I need access to the shortcode attributes <strong>before</strong> the content (and\nit's shortcode) is processed.... in the first "is $atts available\nhere" after the add_shortcode</p>\n</blockquote>\n<p>In that case, you can manually parse the shortcode and retrieve its attributes (if any) like so, which uses <a href=\"https://developer.wordpress.org/reference/functions/get_shortcode_regex/\" rel=\"nofollow noreferrer\"><code>get_shortcode_regex()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/shortcode_parse_atts/\" rel=\"nofollow noreferrer\"><code>shortcode_parse_atts()</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$content = 'before blah2 [foo bar="baz" num="123"] after';\n\npreg_match( '/' . get_shortcode_regex() . '/s', $content, $matches );\n$atts = isset( $matches[3] ) ? shortcode_parse_atts( $matches[3] ) : '';\n\nvar_dump( $atts );\n/* Output:\narray(2) {\n ["bar"]=>\n string(3) "baz"\n ["num"]=>\n string(3) "123"\n}\n*/\n</code></pre>\n<ul>\n<li>Note that the above will only retrieve the attributes of the <em>first</em> shortcode found in <code>$content</code>. So use that code only if you're sure the content would never contain any other shortcodes..</li>\n</ul>\n<p>Or you can try this function which parses all shortcodes of <strong>a certain tag</strong> and return an array of attributes:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function my_shortcode_parse_atts( $text, $tag ) {\n $all_atts = array();\n\n preg_match_all( '/' . get_shortcode_regex() . '/s', $text, $matches );\n\n // If the shortcode ($tag) is found in $text, we parse the attributes.\n if ( isset( $matches[3] ) ) {\n // $matches[3] is the attributes string like ' bar="baz" num="123"'\n foreach ( $matches[3] as $i => $s ) {\n if ( $tag === $matches[2][ $i ] ) {\n $all_atts[] = shortcode_parse_atts( $s );\n }\n }\n }\n\n return $all_atts;\n}\n</code></pre>\n<ul>\n<li><p>Sample usage and output:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$content = 'before [foo] blah2 [foo bar="baz" num="123"] after';\n$all_atts = my_shortcode_parse_atts( $content, 'foo' );\n\nvar_dump( $all_atts );\n/* Output:\narray(2) {\n [0]=>\n string(0) ""\n [1]=>\n array(2) {\n ["bar"]=>\n string(3) "baz"\n ["num"]=>\n string(3) "123"\n }\n}\n*/\n</code></pre>\n<p>Note: In the above <code>$content</code>, there are 2 instances of the <code>foo</code> shortcode; one without any attributes, and the other with 2 attributes.</p>\n</li>\n</ul>\n<p>Also, I used a dummy text, so it's up to you on how to get the actual <code>$content</code>'s value..</p>\n"
},
{
"answer_id": 406679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>The answer from @SallyCJ got me started on the solution that worked best for me. It uses some of her code. There are references to other resources that helped out.</p>\n<pre><code>function my_get_shortcode_atts($shortcode_id) {\n/* given the $shortcode_id you are looking for, find it in the content\n before the loop \n returns an array of the $atts element from the content\n the array will be empty if there are no attributes for the shortcode\n*/\n\n\n// get the content before the loop \n// (see https://wordpress.stackexchange.com/a/377671/29416 )\nglobal $post;\n$pageID = $post->ID;\n$fst_content = get_the_content(null, false, $pageID);\n\n// extract shortcode attributes \n// (from https://wordpress.stackexchange.com/a/172285/29416\npreg_match_all( '/' . get_shortcode_regex() . '/s', $fst_content , $matches );\n $shortcode_atts = array();\n if( isset( $matches[2] ) )\n {\n foreach( (array) $matches[2] as $key => $value )\n {\n if( $shortcode_id === $value )\n $shortcode_atts[] = shortcode_parse_atts( $matches[3][$key] );\n }\n }\n if (! count($shortcode_atts)) { // this returns false if shortcode not found\n return array();\n }\n// 0th element is the attributes, so we get just that; \n// if there is more than one, you may need to adjust this part\n$shortcode_atts = $shortcode_atts[0];\ndefine("SHORTCODE_ATTS", $shortcode_atts); // so I can use the $atts anywhere\nreturn $shortcode_atts;\n}\n</code></pre>\n<p>Once I have the attributes, I can use this in my 'big function file' to set some constants:</p>\n<pre><code> if (function_exists('get_bloginfo')) { \n // get_bloginfo function won't exist in non-WP environment\n // you can use other WP-unique functions if you wish\n // get shortcode atts into an array, otherwise false\n $atts = my_get_shortcode_atts("my_shortcode_name");\n // do whatever you want with the atts\n // you may want to test for no shortcode attributes ($atts will be false)\n // in my case, I'll use the constant defined to do things\n }\n</code></pre>\n<p>Now I can use my 'big functions file' in non-WP environments, as well as with shortcodes in a WP post/page. And the SHORTCODE_ATTS constant is used to do things based on the attributes (if any) found in the shortcode.</p>\n<p>Since this is the solution that worked for me, it will be marked as such. But an upvote given on @SallyCJ's answer because it helped me with the above solution.</p>\n"
}
] | 2022/06/12 | [
"https://wordpress.stackexchange.com/questions/406687",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223078/"
] | **Hello**, I have this code so when I place the **[need\_login]** shortcode on a page, it redirects users who are not logged in to a **Login page**. The problem with this is the that it redirects them to the default WordPress page. How can I add the **url** of the page I want them to be redirected to.
```
function shortcode_needLogin() {
if (!is_user_logged_in()) {
auth_redirect();
}
}
``` | The answer from @SallyCJ got me started on the solution that worked best for me. It uses some of her code. There are references to other resources that helped out.
```
function my_get_shortcode_atts($shortcode_id) {
/* given the $shortcode_id you are looking for, find it in the content
before the loop
returns an array of the $atts element from the content
the array will be empty if there are no attributes for the shortcode
*/
// get the content before the loop
// (see https://wordpress.stackexchange.com/a/377671/29416 )
global $post;
$pageID = $post->ID;
$fst_content = get_the_content(null, false, $pageID);
// extract shortcode attributes
// (from https://wordpress.stackexchange.com/a/172285/29416
preg_match_all( '/' . get_shortcode_regex() . '/s', $fst_content , $matches );
$shortcode_atts = array();
if( isset( $matches[2] ) )
{
foreach( (array) $matches[2] as $key => $value )
{
if( $shortcode_id === $value )
$shortcode_atts[] = shortcode_parse_atts( $matches[3][$key] );
}
}
if (! count($shortcode_atts)) { // this returns false if shortcode not found
return array();
}
// 0th element is the attributes, so we get just that;
// if there is more than one, you may need to adjust this part
$shortcode_atts = $shortcode_atts[0];
define("SHORTCODE_ATTS", $shortcode_atts); // so I can use the $atts anywhere
return $shortcode_atts;
}
```
Once I have the attributes, I can use this in my 'big function file' to set some constants:
```
if (function_exists('get_bloginfo')) {
// get_bloginfo function won't exist in non-WP environment
// you can use other WP-unique functions if you wish
// get shortcode atts into an array, otherwise false
$atts = my_get_shortcode_atts("my_shortcode_name");
// do whatever you want with the atts
// you may want to test for no shortcode attributes ($atts will be false)
// in my case, I'll use the constant defined to do things
}
```
Now I can use my 'big functions file' in non-WP environments, as well as with shortcodes in a WP post/page. And the SHORTCODE\_ATTS constant is used to do things based on the attributes (if any) found in the shortcode.
Since this is the solution that worked for me, it will be marked as such. But an upvote given on @SallyCJ's answer because it helped me with the above solution. |
406,719 | <p><strong>My problem</strong>:</p>
<p>I use the wp-scripts node packages to create a gutenberg plugin. My configuration worked well for one or two weeks and soudainely it stop to work.</p>
<p>My package.json files is:</p>
<pre><code>{
"name": "wf-g",
"version": "0.1.0",
"description": "Example static block scaffolded with Create Block tool.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"main": "build/index.js",
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start",
"css": "node-sass --source-map true --output-style compressed -w src/scss/style.scss -o css/ ",
"dev": "concurrently --kill-others \"npm run start\" \"npm run css\""
},
"devDependencies": {
"@wordpress/scripts": "^23.0.0",
"concurrently": "^7.1.0"
},
"dependencies": {
"node-sass": "^7.0.1"
}
}
</code></pre>
<p>I used to run the script <code>dev</code> with <code>npm run dev</code> command. Css script continue to work but the <code>start</code> script doesn't work anymore.</p>
<p>I work with Visual Studio Code and the terminal display this :</p>
<pre><code>PS D:\Developpement\Sites - Local\Gutenberg-Dev\app\public\wp-content\plugins\webformation-gut> npm run dev
> [email protected] dev
> concurrently --kill-others "npm run start" "npm run css"
[1]
[1] > [email protected] css
[1] > node-sass --source-map true --output-style compressed -w src/scss/style.scss -o css/
[1]
[0]
[0] > [email protected] start
[0] > wp-scripts start
[0]
</code></pre>
<p><strong>What I tried</strong>:</p>
<p>I try to run <code>start</code> script directly nothing... <code>build</code> script nothing.
I try to delete the <code>node_modules</code> folder and the <code>package-lock.json</code>... and try again <code>npm install --only=dev</code>. Nothing append.</p>
<p>Does anyone can help me ?</p>
<p>Thanks</p>
| [
{
"answer_id": 406892,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you are doing it unnecessarily complicated. You can use <code>@wordpress/create-block</code> to scaffold basic block and go from there. I never used concurrently, but my guess is that [1] pattern is from entering npm cli mode instead of starting the command. I understand you are trying to speed build process, by separating javascript and scss building steps and running them concurrently, but be aware that in standard @wordpress/scripts configuration, webpack is configured to process both javascript and scss, so you should modify webpack config. I also suggest updating @wordpress/scripts to the latest version.</p>\n<p>My guess is that your run configuration does not work because environment variable path to wp-scripts is not set properly. Try installing <code>@wordpress/create-block</code> and see if that works. You can start modifying from there.</p>\n"
},
{
"answer_id": 406914,
"author": "Albedo0",
"author_id": 86085,
"author_profile": "https://wordpress.stackexchange.com/users/86085",
"pm_score": 1,
"selected": false,
"text": "<p>Finally i found the problem !\nThere was a problem in the scss file which stop the building script. I had no error message.\nI think that the problem was that i used a sass variable which was too long.</p>\n"
}
] | 2022/06/13 | [
"https://wordpress.stackexchange.com/questions/406719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86085/"
] | **My problem**:
I use the wp-scripts node packages to create a gutenberg plugin. My configuration worked well for one or two weeks and soudainely it stop to work.
My package.json files is:
```
{
"name": "wf-g",
"version": "0.1.0",
"description": "Example static block scaffolded with Create Block tool.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"main": "build/index.js",
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start",
"css": "node-sass --source-map true --output-style compressed -w src/scss/style.scss -o css/ ",
"dev": "concurrently --kill-others \"npm run start\" \"npm run css\""
},
"devDependencies": {
"@wordpress/scripts": "^23.0.0",
"concurrently": "^7.1.0"
},
"dependencies": {
"node-sass": "^7.0.1"
}
}
```
I used to run the script `dev` with `npm run dev` command. Css script continue to work but the `start` script doesn't work anymore.
I work with Visual Studio Code and the terminal display this :
```
PS D:\Developpement\Sites - Local\Gutenberg-Dev\app\public\wp-content\plugins\webformation-gut> npm run dev
> [email protected] dev
> concurrently --kill-others "npm run start" "npm run css"
[1]
[1] > [email protected] css
[1] > node-sass --source-map true --output-style compressed -w src/scss/style.scss -o css/
[1]
[0]
[0] > [email protected] start
[0] > wp-scripts start
[0]
```
**What I tried**:
I try to run `start` script directly nothing... `build` script nothing.
I try to delete the `node_modules` folder and the `package-lock.json`... and try again `npm install --only=dev`. Nothing append.
Does anyone can help me ?
Thanks | Finally i found the problem !
There was a problem in the scss file which stop the building script. I had no error message.
I think that the problem was that i used a sass variable which was too long. |
406,989 | <p>I have a mu-plugin that removes a branded "Welcome to X" dashboard meta box placed there by the hosting company I work for. It works fine mostly.</p>
<p>However, some of our agency clients are already removing it in functions.php, which is now causing a fatal error when the mu-plugin removes it and then functions.php tries again.</p>
<p>The error I'm getting is:</p>
<pre><code> Cannot redeclare remove_specific_widget() (previously declared in /srv/htdocs/wp-content/mu-plugins/whitelabel-dashboard.php:24) in /srv/htdocs/wp-content/themes/twentytwentytwo/functions.php on line 70
</code></pre>
<p>I've added a check to see if the function already exists (in functions.php), which <em>should</em> have the mu-plugin only run when it isn't found in functions.php. But it is only working on sites that do have the code in functions.php, and not on sites that do not.</p>
<p>It's been about a decade since I looked at any code, so feel free to point and laugh. I suspect the answer is obvious and I'm just missing it.</p>
<p>$test_info returns true (1) in the echo statement on both the test site <em>with</em> removal code in functions.php and on the site <em>without</em> removal code.</p>
<p>Will function_exists() just not work in this case? Is there an alternative, or should I do it myself? (Best I could come up with was to grab functions.php contents to a string, check for the function name with strpos() since some sites don't run PHP 8 so str_contains() isn't an option. Then use that check where I'm using function_exists() right now.)</p>
<p>The mu-plugin is:</p>
<pre><code>
$test_info = function_exists('remove_x_widget') === false;
echo($test_info);
echo('Is this thing on?');
// remove the "Welcome to X" widget box from dashboard
function remove_x_widget_with_plugin() { // must be different name than identical function used in functions.php so function_exists() isn't accidentally triggered
remove_meta_box( 'x_dashboard_widget', 'dashboard', 'normal' );
}
// if x widget is active, remove it
function remove_widget_if_active() {
if (function_exists('remove_x_widget') === false) {
add_action('wp_dashboard_setup', 'remove_x_widget_with_plugin' );
}
}
add_action('wp_dashboard_setup', 'remove_widget_if_active');
?>```
</code></pre>
| [
{
"answer_id": 406892,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you are doing it unnecessarily complicated. You can use <code>@wordpress/create-block</code> to scaffold basic block and go from there. I never used concurrently, but my guess is that [1] pattern is from entering npm cli mode instead of starting the command. I understand you are trying to speed build process, by separating javascript and scss building steps and running them concurrently, but be aware that in standard @wordpress/scripts configuration, webpack is configured to process both javascript and scss, so you should modify webpack config. I also suggest updating @wordpress/scripts to the latest version.</p>\n<p>My guess is that your run configuration does not work because environment variable path to wp-scripts is not set properly. Try installing <code>@wordpress/create-block</code> and see if that works. You can start modifying from there.</p>\n"
},
{
"answer_id": 406914,
"author": "Albedo0",
"author_id": 86085,
"author_profile": "https://wordpress.stackexchange.com/users/86085",
"pm_score": 1,
"selected": false,
"text": "<p>Finally i found the problem !\nThere was a problem in the scss file which stop the building script. I had no error message.\nI think that the problem was that i used a sass variable which was too long.</p>\n"
}
] | 2022/06/21 | [
"https://wordpress.stackexchange.com/questions/406989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/218210/"
] | I have a mu-plugin that removes a branded "Welcome to X" dashboard meta box placed there by the hosting company I work for. It works fine mostly.
However, some of our agency clients are already removing it in functions.php, which is now causing a fatal error when the mu-plugin removes it and then functions.php tries again.
The error I'm getting is:
```
Cannot redeclare remove_specific_widget() (previously declared in /srv/htdocs/wp-content/mu-plugins/whitelabel-dashboard.php:24) in /srv/htdocs/wp-content/themes/twentytwentytwo/functions.php on line 70
```
I've added a check to see if the function already exists (in functions.php), which *should* have the mu-plugin only run when it isn't found in functions.php. But it is only working on sites that do have the code in functions.php, and not on sites that do not.
It's been about a decade since I looked at any code, so feel free to point and laugh. I suspect the answer is obvious and I'm just missing it.
$test\_info returns true (1) in the echo statement on both the test site *with* removal code in functions.php and on the site *without* removal code.
Will function\_exists() just not work in this case? Is there an alternative, or should I do it myself? (Best I could come up with was to grab functions.php contents to a string, check for the function name with strpos() since some sites don't run PHP 8 so str\_contains() isn't an option. Then use that check where I'm using function\_exists() right now.)
The mu-plugin is:
```
$test_info = function_exists('remove_x_widget') === false;
echo($test_info);
echo('Is this thing on?');
// remove the "Welcome to X" widget box from dashboard
function remove_x_widget_with_plugin() { // must be different name than identical function used in functions.php so function_exists() isn't accidentally triggered
remove_meta_box( 'x_dashboard_widget', 'dashboard', 'normal' );
}
// if x widget is active, remove it
function remove_widget_if_active() {
if (function_exists('remove_x_widget') === false) {
add_action('wp_dashboard_setup', 'remove_x_widget_with_plugin' );
}
}
add_action('wp_dashboard_setup', 'remove_widget_if_active');
?>```
``` | Finally i found the problem !
There was a problem in the scss file which stop the building script. I had no error message.
I think that the problem was that i used a sass variable which was too long. |
407,050 | <p>Can anyone help me here. I want to list all the custom posts with the type 'portfolio' in this loop, where they have the 'Project Categories' set to 'ABC'. The below doesn't work, I think the issue is that the '' array parameter is looking at the main WP 'Categories'. Can someone help me to get it working please? Cheers.</p>
<pre class="lang-php prettyprint-override"><code>$loop = new WP_Query(
array(
'post_type' => 'portfolio',
'posts_per_page' => 50,
'category_name' => 'ABC',
)
);
while ( $loop->have_posts() ) :
$loop->the_post();
?>
<div class="half-column">
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile;
wp_reset_postdata();
</code></pre>
| [
{
"answer_id": 407051,
"author": "Sarequl Basar",
"author_id": 125457,
"author_profile": "https://wordpress.stackexchange.com/users/125457",
"pm_score": 1,
"selected": false,
"text": "<p>Is that <strong>category</strong> or custom <strong>taxonomy</strong>?</p>\n<p>if this is a category, then try this one.</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n$loop = new WP_Query(\narray(\n 'post_type' => 'portfolio',\n 'posts_per_page' => 50,\n 'category__in' => array('8','9','10'), // your category ids\n)\n);\nwhile ( $loop->have_posts() ) : $loop->the_post();\n\n?>\n\n<div class="half-column">\n<h2><?php the_title(); ?></h2>\n</div>\n\n<?php endwhile;\nwp_reset_postdata();\n?>\n</code></pre>\n<p>Or if this <strong>custom taxonomy</strong>, try this one</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n$loop = new WP_Query(\narray(\n 'post_type' => 'portfolio',\n 'posts_per_page' => 50,\n 'tax_query' => array(\n array (\n 'taxonomy' => 'yourTaxonomy',\n 'field' => 'slug', //type, id or slug\n 'terms' => 'yourTermSlug',\n )\n ),\n)\n);\nwhile ( $loop->have_posts() ) : $loop->the_post();\n\n?>\n\n<div class="half-column">\n<h2><?php the_title(); ?></h2>\n</div>\n\n<?php endwhile;\nwp_reset_postdata();\n?>\n</code></pre>\n<p>let me know the update.\nThank You</p>\n"
},
{
"answer_id": 407058,
"author": "dubbs",
"author_id": 176049,
"author_profile": "https://wordpress.stackexchange.com/users/176049",
"pm_score": 0,
"selected": false,
"text": "<p>This solution worked for me <code>'project-type' => 'ABC' </code></p>\n"
}
] | 2022/06/23 | [
"https://wordpress.stackexchange.com/questions/407050",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/176049/"
] | Can anyone help me here. I want to list all the custom posts with the type 'portfolio' in this loop, where they have the 'Project Categories' set to 'ABC'. The below doesn't work, I think the issue is that the '' array parameter is looking at the main WP 'Categories'. Can someone help me to get it working please? Cheers.
```php
$loop = new WP_Query(
array(
'post_type' => 'portfolio',
'posts_per_page' => 50,
'category_name' => 'ABC',
)
);
while ( $loop->have_posts() ) :
$loop->the_post();
?>
<div class="half-column">
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile;
wp_reset_postdata();
``` | Is that **category** or custom **taxonomy**?
if this is a category, then try this one.
```php
<?php
$loop = new WP_Query(
array(
'post_type' => 'portfolio',
'posts_per_page' => 50,
'category__in' => array('8','9','10'), // your category ids
)
);
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="half-column">
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile;
wp_reset_postdata();
?>
```
Or if this **custom taxonomy**, try this one
```php
<?php
$loop = new WP_Query(
array(
'post_type' => 'portfolio',
'posts_per_page' => 50,
'tax_query' => array(
array (
'taxonomy' => 'yourTaxonomy',
'field' => 'slug', //type, id or slug
'terms' => 'yourTermSlug',
)
),
)
);
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="half-column">
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile;
wp_reset_postdata();
?>
```
let me know the update.
Thank You |
407,167 | <p>I'm trying to create a generic, re-usable function that shows the site name on the login screen. It works with just static text, but how do I pull in the site name dynamically? Here's what I've tried:</p>
<pre><code>function custom_login_message() {
$message = '<p class="natz-login">Log in to <?php echo get_option( 'name' ); ?> </p><br />';
return $message;
}
add_filter('login_message', 'custom_login_message');
</code></pre>
<p>This is obviously wrong, but what do is use instead of <code><?php echo get_option( 'name' ); ?></code> ?</p>
| [
{
"answer_id": 407173,
"author": "safir",
"author_id": 222127,
"author_profile": "https://wordpress.stackexchange.com/users/222127",
"pm_score": -1,
"selected": false,
"text": "<p>if you mean, the php to replace <code><?php echo get_option( 'name' ); ?></code><br />\nthen it's probably <code><?= bloginfo('name') ?></code></p>\n"
},
{
"answer_id": 407190,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": true,
"text": "<p>The function you are looking for is <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/\" rel=\"nofollow noreferrer\"><code>get_bloginfo()</code></a>.</p>\n<pre><code>function wpse407167_custom_login_message( $message ) {\n\n $message = '<p class="natz-login">Log in to ' . get_bloginfo('name') . '</p><br>';\n return $message;\n \n}\nadd_filter( 'login_message', 'wpse407167_custom_login_message', 99 );\n</code></pre>\n"
}
] | 2022/06/28 | [
"https://wordpress.stackexchange.com/questions/407167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/222589/"
] | I'm trying to create a generic, re-usable function that shows the site name on the login screen. It works with just static text, but how do I pull in the site name dynamically? Here's what I've tried:
```
function custom_login_message() {
$message = '<p class="natz-login">Log in to <?php echo get_option( 'name' ); ?> </p><br />';
return $message;
}
add_filter('login_message', 'custom_login_message');
```
This is obviously wrong, but what do is use instead of `<?php echo get_option( 'name' ); ?>` ? | The function you are looking for is [`get_bloginfo()`](https://developer.wordpress.org/reference/functions/get_bloginfo/).
```
function wpse407167_custom_login_message( $message ) {
$message = '<p class="natz-login">Log in to ' . get_bloginfo('name') . '</p><br>';
return $message;
}
add_filter( 'login_message', 'wpse407167_custom_login_message', 99 );
``` |
407,263 | <p>Hello I'm new to Wordpress and I'm trying to create an ajax endpoint that outputs JSON so I can access it through jQuery Datatables. I'm using Air Light theme for my current site and what happens when I go into <code>/wp-admin/admin-ajax.php?action=ajax_endpoint</code> is that it just gives me 0. I tried querying posts, users, and my custom tables they all give me 0 even though I have a status code 200.</p>
<p>I'm wondering if there's something wrong I'm doing here. I've also tried putting an echo somewhere in the function and it does not show up.</p>
<p><em>functions.php</em></p>
<pre><code>namespace Air_Light;
/**
* The current version of the theme.
*/
define( 'AIR_LIGHT_VERSION', '8.3.2' );
/**
* Theme setup code
*/
add_action('wp_ajax_ajax_endpoint', 'ajax_endpoint');
add_action('wp_ajax_no_priv_ajax_endpoint', 'ajax_endpoint');
function ajax_endpoint(){
global $wpdb;
$results = $wpdb->get_results('SELECT * FROM table');
echo json_encode($results);
wp_die();
}
</code></pre>
| [
{
"answer_id": 407264,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 3,
"selected": true,
"text": "<p>You need to use the defined namespace as the prefix for the <code>add_action</code> callbacks so that PHP knows which function it is supposed to call. More on this here, <a href=\"https://wordpress.stackexchange.com/questions/284877/add-action-in-namespace-not-working\">add_action in namespace not working</a></p>\n<p>The <code>add_action</code>s should look like this then,</p>\n<pre><code>add_action('wp_ajax_ajax_endpoint', __NAMESPACE__ . '\\\\ajax_endpoint');\nadd_action('wp_ajax_nopriv_ajax_endpoint', __NAMESPACE__ . '\\\\ajax_endpoint');\n</code></pre>\n<p>When doing development work it is a good idea to have debugging on so that you can check <code>debug.log</code> for error messages, which usually tell you what is wrong with the code and why it isn't working. <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">Debugging in WordPress</a></p>\n<p>As a side note, for sending a json response you can also use <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json/\" rel=\"nofollow noreferrer\">wp_send_json()</a>, <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json_error/\" rel=\"nofollow noreferrer\">wp_send_json_error()</a>, and <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json_success/\" rel=\"nofollow noreferrer\">wp_send_json_success()</a>.</p>\n"
},
{
"answer_id": 407282,
"author": "Irfan",
"author_id": 193019,
"author_profile": "https://wordpress.stackexchange.com/users/193019",
"pm_score": 0,
"selected": false,
"text": "<p>It seems the issue is because of incorrect hook_name. You have used <code>wp_ajax_no_priv_{$action}</code> instead of <code>wp_ajax_nopriv_{$action}</code></p>\n<p>Also use <code>wp_send_json()</code> for send response in json format.</p>\n<pre><code>add_action('wp_ajax_ajax_endpoint', 'ajax_endpoint');\nadd_action('wp_ajax_nopriv_ajax_endpoint', 'ajax_endpoint');\nfunction ajax_endpoint(){\n $results = array("Test Result");\n wp_send_json($results);\n wp_die();\n}\n</code></pre>\n"
}
] | 2022/07/01 | [
"https://wordpress.stackexchange.com/questions/407263",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223649/"
] | Hello I'm new to Wordpress and I'm trying to create an ajax endpoint that outputs JSON so I can access it through jQuery Datatables. I'm using Air Light theme for my current site and what happens when I go into `/wp-admin/admin-ajax.php?action=ajax_endpoint` is that it just gives me 0. I tried querying posts, users, and my custom tables they all give me 0 even though I have a status code 200.
I'm wondering if there's something wrong I'm doing here. I've also tried putting an echo somewhere in the function and it does not show up.
*functions.php*
```
namespace Air_Light;
/**
* The current version of the theme.
*/
define( 'AIR_LIGHT_VERSION', '8.3.2' );
/**
* Theme setup code
*/
add_action('wp_ajax_ajax_endpoint', 'ajax_endpoint');
add_action('wp_ajax_no_priv_ajax_endpoint', 'ajax_endpoint');
function ajax_endpoint(){
global $wpdb;
$results = $wpdb->get_results('SELECT * FROM table');
echo json_encode($results);
wp_die();
}
``` | You need to use the defined namespace as the prefix for the `add_action` callbacks so that PHP knows which function it is supposed to call. More on this here, [add\_action in namespace not working](https://wordpress.stackexchange.com/questions/284877/add-action-in-namespace-not-working)
The `add_action`s should look like this then,
```
add_action('wp_ajax_ajax_endpoint', __NAMESPACE__ . '\\ajax_endpoint');
add_action('wp_ajax_nopriv_ajax_endpoint', __NAMESPACE__ . '\\ajax_endpoint');
```
When doing development work it is a good idea to have debugging on so that you can check `debug.log` for error messages, which usually tell you what is wrong with the code and why it isn't working. [Debugging in WordPress](https://wordpress.org/support/article/debugging-in-wordpress/)
As a side note, for sending a json response you can also use [wp\_send\_json()](https://developer.wordpress.org/reference/functions/wp_send_json/), [wp\_send\_json\_error()](https://developer.wordpress.org/reference/functions/wp_send_json_error/), and [wp\_send\_json\_success()](https://developer.wordpress.org/reference/functions/wp_send_json_success/). |
407,275 | <p>I'm currently setting up my first WP REST API and am attempting to understand how WP implements JSON Schema for the API endpoints, and the docs are imho really poor and confusing; so I wanted to make sure that I understand things properly:</p>
<ol>
<li><p>According to <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#resource-schema" rel="nofollow noreferrer">this</a>, you can specify the 'schema' parameter within the <a href="https://developer.wordpress.org/reference/functions/register_rest_route/#parameters" rel="nofollow noreferrer">$args</a> argument when registering a new rest route, to provide a JSON schema <strong>informing about the structure of the response</strong> of your endpoint. That schema should be delivered to any client making an <code>OPTIONS</code> HTTP request to the according endpoint. That works.</p>
</li>
<li><p>You can then specify any combination of the <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics" rel="nofollow noreferrer">WP JSON Schema parameters</a> for every parameter of your <code>$args</code> array when using <code>register_rest_route</code>, to <strong>inform about the required format of the request's arguments</strong>, for that respective endpoint. When I add for example a <code>description</code> key to the argument X of the endpoint Y, and then inspect the general <code>https://example.org/wp-json/</code> REST schema of the website via <code>GET</code>, that <code>description</code> indeed shows up under the argument X of my API endpoint Y. So that also works.</p>
</li>
<li><p>What I totally don't understand is, how can I use the JSON schema I've specified in 2) for validation and subsequent (if validation is passed) sanitization? The docs <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#api" rel="nofollow noreferrer">mention</a> the built-in <code>rest_validate_value_from_schema</code> and <code>rest_validate_value_from_schema</code> functions, but do not really show any examples / explain how you implement your JSON schemas provided for the request data (step 2)) for validation / sanitization.</p>
</li>
</ol>
<p>How is that actually done using WP's built-in JSON schema ?</p>
| [
{
"answer_id": 407280,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>You're already providing a schema, the parameters in <code>args</code> are their own schemas, but WordPress does not enforce this schema or perform sanitisation/validation by default.</p>\n<p>You can make WordPress enforce it though by setting the validation and sanitisation callbacks to the following:</p>\n<pre class=\"lang-php prettyprint-override\"><code>'sanitize_callback' => 'rest_sanitize_request_arg',\n'validate_callback' => 'rest_validate_request_arg',\n</code></pre>\n<p><code>rest_validate_request_arg</code> will look up the parameter in the args and use that as the schema and pass it to <code>rest_validate_value_from_schema</code> for validation. The format of each parameter in the <code>args</code> section is also the format of the schema for that input because it <em>is</em> a schema.</p>\n<p>For example, this is how WordPress defines validates and enforces the <code>per_page</code> parameter in the args section of collection endpoints:</p>\n<pre class=\"lang-php prettyprint-override\"><code> 'per_page' => array(\n 'description' => __( 'Maximum number of items to be returned in result set.' ),\n 'type' => 'integer',\n 'default' => 10,\n 'minimum' => 1,\n 'maximum' => 100,\n 'sanitize_callback' => 'absint',\n 'validate_callback' => 'rest_validate_request_arg',\n ),\n</code></pre>\n<p>And here is how it does it internally:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function rest_validate_request_arg( $value, $request, $param ) {\n $attributes = $request->get_attributes();\n if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {\n return true;\n }\n $args = $attributes['args'][ $param ];\n \n return rest_validate_value_from_schema( $value, $args, $param );\n}\n</code></pre>\n<p>There is also a <code>rest_sanitize_request_arg</code> for sanitisation, but this is used in fewer locations in core itself.</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/rest_sanitize_request_arg/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rest_sanitize_request_arg/</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/rest_validate_request_arg/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rest_validate_request_arg/</a></li>\n<li><a href=\"https://github.com/WordPress/WordPress/blob/c7d3e267b8a7aebc28b23efa74b2971602852315/wp-includes/rest-api/endpoints/class-wp-rest-controller.php#L348\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/c7d3e267b8a7aebc28b23efa74b2971602852315/wp-includes/rest-api/endpoints/class-wp-rest-controller.php#L348</a></li>\n</ul>\n"
},
{
"answer_id": 407281,
"author": "DevelJoe",
"author_id": 188571,
"author_profile": "https://wordpress.stackexchange.com/users/188571",
"pm_score": -1,
"selected": false,
"text": "<p>So the way to do what's mentioned can be reached by the following, coded in your main plugin file or the active theme's <code>functions.php</code>. But as you see, I need to specify the JSON schema used for validation, sanitization, and request argument documentation. I just would like to know if there's a way to provide that schema only once and use it everywhere (of course in a way different from just storing it in a variable).</p>\n<pre><code>add_action(\n 'rest_api_init',\n function () {\n \n // Register Route - START\n \n register_rest_route(\n 'api/v1',\n '/zoo',\n [\n [\n 'methods' => 'POST',\n 'permission_callback' => function ( WP_REST_Request $request ) { // authenticate client + check nonce\n },\n 'callback' => 'controller_callback',\n 'args' => [\n 'animal' => [\n 'type' => 'string',\n 'oneOf' => ['lion','tiger'],\n 'description' => "string determining the kind of animal you're trying to create",\n 'required' => true,\n 'validate_callback' => function ( $param ) {\n return rest_validate_value_from_schema( $param, ['type' => 'string', 'enum' => ['lion','tiger']]);\n },\n 'sanitize_callback' => function ( $param ) {\n return rest_sanitize_value_from_schema( $param, ['type' => 'string', 'enum' => ['lion','tiger']]);\n }\n ],\n '_wpnonce' => [\n 'required' => true\n ]\n ]\n ],\n 'schema' => function() { return array(\n // This tells the spec of JSON Schema we are using which is draft 4.\n '$schema' => 'http://json-schema.org/draft-04/schema#',\n // The title property marks the identity of the resource.\n 'title' => 'animal',\n 'type' => 'object',\n // In JSON Schema you can specify object properties in the properties attribute.\n 'properties' => array(\n 'id' => array(\n 'description' => 'ID of the created animal',\n 'type' => 'integer',\n 'readonly' => true,\n ),\n 'animal' => array(\n 'description' => 'identifier of the animal type',\n 'type' => 'string',\n )\n )); }\n ]\n );\n \n // Register Route - END\n }\n );\n</code></pre>\n"
},
{
"answer_id": 407286,
"author": "DevelJoe",
"author_id": 188571,
"author_profile": "https://wordpress.stackexchange.com/users/188571",
"pm_score": -1,
"selected": false,
"text": "<p>So the finally correct (and tested) way to implement what I was looking for is:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action(\n 'rest_api_init',\n function () {\n \n // Register Route - START\n \n register_rest_route(\n 'api/v1',\n '/zoo',\n [\n [\n 'methods' => 'POST',\n 'permission_callback' => function ( WP_REST_Request $request ) { // authenticate client + check nonce\n },\n 'callback' => 'controller_callback',\n 'args' => [\n 'animal' => [\n 'type' => 'string',\n 'enum' => ['lion','tiger'],\n 'description' => "string determining the kind of animal you're trying to create",\n 'required' => true,\n 'validate_callback' => 'rest_validate_request_arg',\n 'sanitize_callback' => 'rest_sanitize_request_arg'\n ],\n '_wpnonce' => [\n 'required' => true\n ]\n ]\n ]\n ]\n );\n \n // Register Route - END\n }\n );\n</code></pre>\n<p>As a side-note, be aware that using JSON schema arguments exposes your argument validation + sanitization criteria through your endpoints, and will cause default responses with clear details about where your validation / sanitization failed.</p>\n<p>This is perfect for development environments, but if you do not want this to happen in production environments, you're better off using custom validation and sanitization callbacks, where you can explicitly determine the information returned to your client in case of any failure, as documented <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#argument-schema\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Was just a final thought I had on this story.</p>\n"
}
] | 2022/07/01 | [
"https://wordpress.stackexchange.com/questions/407275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188571/"
] | I'm currently setting up my first WP REST API and am attempting to understand how WP implements JSON Schema for the API endpoints, and the docs are imho really poor and confusing; so I wanted to make sure that I understand things properly:
1. According to [this](https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#resource-schema), you can specify the 'schema' parameter within the [$args](https://developer.wordpress.org/reference/functions/register_rest_route/#parameters) argument when registering a new rest route, to provide a JSON schema **informing about the structure of the response** of your endpoint. That schema should be delivered to any client making an `OPTIONS` HTTP request to the according endpoint. That works.
2. You can then specify any combination of the [WP JSON Schema parameters](https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics) for every parameter of your `$args` array when using `register_rest_route`, to **inform about the required format of the request's arguments**, for that respective endpoint. When I add for example a `description` key to the argument X of the endpoint Y, and then inspect the general `https://example.org/wp-json/` REST schema of the website via `GET`, that `description` indeed shows up under the argument X of my API endpoint Y. So that also works.
3. What I totally don't understand is, how can I use the JSON schema I've specified in 2) for validation and subsequent (if validation is passed) sanitization? The docs [mention](https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#api) the built-in `rest_validate_value_from_schema` and `rest_validate_value_from_schema` functions, but do not really show any examples / explain how you implement your JSON schemas provided for the request data (step 2)) for validation / sanitization.
How is that actually done using WP's built-in JSON schema ? | You're already providing a schema, the parameters in `args` are their own schemas, but WordPress does not enforce this schema or perform sanitisation/validation by default.
You can make WordPress enforce it though by setting the validation and sanitisation callbacks to the following:
```php
'sanitize_callback' => 'rest_sanitize_request_arg',
'validate_callback' => 'rest_validate_request_arg',
```
`rest_validate_request_arg` will look up the parameter in the args and use that as the schema and pass it to `rest_validate_value_from_schema` for validation. The format of each parameter in the `args` section is also the format of the schema for that input because it *is* a schema.
For example, this is how WordPress defines validates and enforces the `per_page` parameter in the args section of collection endpoints:
```php
'per_page' => array(
'description' => __( 'Maximum number of items to be returned in result set.' ),
'type' => 'integer',
'default' => 10,
'minimum' => 1,
'maximum' => 100,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
),
```
And here is how it does it internally:
```php
function rest_validate_request_arg( $value, $request, $param ) {
$attributes = $request->get_attributes();
if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
return true;
}
$args = $attributes['args'][ $param ];
return rest_validate_value_from_schema( $value, $args, $param );
}
```
There is also a `rest_sanitize_request_arg` for sanitisation, but this is used in fewer locations in core itself.
* <https://developer.wordpress.org/reference/functions/rest_sanitize_request_arg/>
* <https://developer.wordpress.org/reference/functions/rest_validate_request_arg/>
* <https://github.com/WordPress/WordPress/blob/c7d3e267b8a7aebc28b23efa74b2971602852315/wp-includes/rest-api/endpoints/class-wp-rest-controller.php#L348> |
407,346 | <p>When using <code>@wordpress/create-block</code> to scaffhold a plugin for a block, the generated bundle is automatically registered via the <code>block.json</code> metadata :</p>
<pre class="lang-json prettyprint-override"><code>{
...
"name": "my-block",
"textdomain": "my-block",
"editorScript": "file:./index.js",
...
}
</code></pre>
<p>No need to call <code>wp_register_script</code> myself. This is great since it automatically handles dependencies via the <code>index.asset.php</code> file generated in the build folder.</p>
<p>Following the procedure mentionned <a href="https://developer.wordpress.org/block-editor/how-to-guides/internationalization/" rel="nofollow noreferrer">in the doc</a>, I then create a JET translation file. Here is the procedure :</p>
<ol>
<li>Creating POT file with <code>wp i18n make-pot . languages/my-block.pot</code></li>
<li>Creating PO file with <code>cp languages/test.pot languages/my-block-FR_BE.po</code></li>
<li>Filling msgstr strings in <code>my-block-FR_BE.po</code></li>
<li>Adding line <code>"Language: fr_BE\n"</code> to <code>my-block-FR_BE.po</code></li>
<li>Creating JSON file with <code>wp i18n make-json languages/my-block-FR_BE.po --no-purge</code></li>
</ol>
<p>The JSON generated is appended with a md5 hash: <strong>my-block-fr_BE-cae574befd871d4f740fd8b719bac1db.json</strong>.</p>
<p>Now I have to call <code>wp_set_script_translations</code> in my init method :</p>
<pre class="lang-php prettyprint-override"><code>function my_block_init() {
register_block_type( __DIR__ . '/build' );
wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );
}
</code></pre>
<p>This does not work.</p>
<p>In order to make it work, I have to register the script and enqueue it, loosing the ability to have dependencies automatically injected :</p>
<pre class="lang-php prettyprint-override"><code>function my_block_init() {
wp_register_script(
'my-block-script',
plugins_url('/build/index.js', __FILE__),
array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-react-refresh-runtime')
);
wp_enqueue_script('my-block-script');
register_block_type( __DIR__ . '/build' );
wp_set_script_translations('my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/');
}
</code></pre>
<p>I also need to rename my JSON file to include the script handle instead of the automatically generated md5 hash. The <a href="https://developer.wordpress.org/block-editor/how-to-guides/internationalization/#load-translation-file" rel="nofollow noreferrer">"Load Translation File"</a> section in the doc gives me the impression that this shouldn't be necessary when keeping the generated name, though I'm not sure of what I'm supposed to do here :</p>
<blockquote>
<p>WordPress will check for a file in that path with the format ${domain}-${locale}-${handle}.json as the source of translations. Alternatively, instead of the registered handle you can use the md5 hash of the relative path of the file, ${domain}-${locale} in the form of ${domain}-${locale}-${md5}.json.</p>
</blockquote>
<p>Is there a way to register JET translations for a script that is automatically registered via the block metadata ? And how can I use the generated name for the JSON file when registering my translation ?</p>
<h3>Edit</h3>
<p>Here's the folder structure :</p>
<pre><code>app/plugins/my-block/
├── build
│ ├── block.json
│ └── index.asset.php
│ └── index.css
│ └── index.js
│ └── style-index.css
├── languages
│ ├── my-block.pot
│ └── my-block-fr_BE.po
│ └── my-block-fr_BE-my-block-script.json
├── src
│ ├── block.json
│ └── index.js
│ └── ...
└── my-block.php
</code></pre>
<p>And here's the content of the <code>my-block.php</code> file (plugin root) :</p>
<pre class="lang-php prettyprint-override"><code><?php
/**
* Plugin Name: My Block
* Requires at least: 5.9
* Requires PHP: 7.0
* Version: 0.1.0
* Author: The WordPress Contributors
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: my-block
*/
function my_block_init() {
register_block_type( __DIR__ . '/build' );
wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );
}
add_action( 'init', 'my_block_init' );
</code></pre>
| [
{
"answer_id": 407405,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the problem:</p>\n<pre class=\"lang-php prettyprint-override\"><code> wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );\n}\nadd_action( 'init', 'my_block_init' );\n</code></pre>\n<p><code>init</code> is too early, WP hasn't registered your blocks assets yet, it knows about the block but that doesn't mean it instantly did all the work all at once in a single atomic step. If it registered and enqueued the scripts and styles on <code>init</code> it would generate warnings and doing it wrong notices!</p>\n<p>And as the docs say:</p>\n<blockquote>\n<p>Works only if the script has already been registered.</p>\n</blockquote>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_script_translations/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_script_translations/</a></p>\n<p>It's too early!!! A useful thing to do is check the return value which is a <code>true</code>/<code>false</code> indicating success.</p>\n<p>Instead, call it on the <code>wp_enqueue_scripts</code> hook the same way the docs say <code>wp_enqueue_script</code> and others should be called, but give it a higher priority value on the hook to ensure it runs afterwards.</p>\n<p>Here's a useful example from the official WP docs:</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_script_translations/#comment-5072\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_script_translations/#comment-5072</a></p>\n"
},
{
"answer_id": 407437,
"author": "drskullster",
"author_id": 29500,
"author_profile": "https://wordpress.stackexchange.com/users/29500",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I managed to make it work :</p>\n<p>I found the handle of the script registered automatically with <code>register_block_type</code> by printing the <code>$this->registered</code> variable inside the <code>WP_Scripts->set_translations</code> method, it was called something like <code>my-block-editor-script</code>.</p>\n<p>By using this handle inside the call to <code>wp_set_script_translations</code> I was able to remove the code that registered and enqueued the script, and I also could use the generated name for the json files.</p>\n<p>Here's what my main plugin file looks like now :</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n/**\n * Plugin Name: My Block\n * Requires at least: 5.9\n * Requires PHP: 7.0\n * Version: 0.1.0\n * Text Domain: my-block\n */\n\nfunction my_block_init() {\n register_block_type( __DIR__ . '/build' );\n}\nadd_action( 'init', 'my_block_init' );\n\nfunction my_block_set_translations() {\n wp_set_script_translations( 'my-block-editor-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );\n}\nadd_action( 'init', 'my_block_set_translations' );\n</code></pre>\n<p>And the path to the JET file: <code>languages/my-block-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json</code>.</p>\n"
},
{
"answer_id": 407513,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://wordpress.stackexchange.com/users/29500/drskullster\">@drskullster</a> already posted a good answer, but I thought I should share the following which explains why <a href=\"https://developer.wordpress.org/reference/functions/wp_set_script_translations/\" rel=\"noreferrer\"><code>wp_set_script_translations()</code></a> needs to be called manually:</p>\n<ol>\n<li><p>Yes it's true that WordPress will automatically register and enqueue the block editor script. <em><strong>So we do not need to manually register/enqueue that script!</strong></em></p>\n</li>\n<li><p>WordPress will also automatically set the script's translations, but only if the block metadata file (i.e. <code>block.json</code>) specifies a valid text domain (e.g. <code>"textdomain": "gutenpride"</code>) and that the script has <code>wp-i18n</code> as one of its dependencies. See <a href=\"https://developer.wordpress.org/reference/functions/register_block_script_handle/\" rel=\"noreferrer\"><code>register_block_script_handle()</code></a>.</p>\n</li>\n<li><p>WordPress uses <code>wp_set_script_translations( $script_handle, $metadata['textdomain'] )</code> to register/set the translations for the script, which means the 3rd parameter (the file path) is not specified and therefore, WordPress will try to load the translation files from the <code>wp-content/languages/plugins</code> folder.</p>\n<p>So for example, if <code>my-block-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json</code> was the JSON file name, then WordPress would attempt to load <code>wp-content/languages/plugins/my-block-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json</code>.</p>\n<p>And thus, you should copy that file to the <code>wp-content/languages/plugins</code> folder. That way, your main plugin file would only need to call <code>register_block_type()</code> and that's it — no need to worry about the JSON file name or MD5 hash, and you also would <strong>not</strong> need to <em>manually</em> call <code>wp_set_script_translations()</code>.</p>\n</li>\n</ol>\n<p>But if you don't want to having to copy the files, then yes, you will need to manually call <code>wp_set_script_translations()</code>, but remember that the <strong>script handle</strong> is in the form of <code><block name>-editor-script</code> where <code><block name></code> is the block name (which is the <code>name</code> property in <code>block.json</code>), but with <em>slashes (<code>/</code>) replaced with hypens (<code>-</code>)</em>.</p>\n<ul>\n<li>So if the block name is <code>my-block</code>, then the script handle would be <code>my-block-editor-script</code>. Or if the name is <code>create-block/gutenpride</code>, then the handle would be <code>create-block-gutenpride-editor-script</code>. See <a href=\"https://developer.wordpress.org/reference/functions/generate_block_asset_handle/\" rel=\"noreferrer\"><code>generate_block_asset_handle()</code></a> for more details.</li>\n</ul>\n<p>So I hope that helps, and FYI, the following is what I had in my main plugin file (<code>wp-content/plugins/gutenpride/gutenpride.php</code>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>function create_block_gutenpride_block_init() {\n register_block_type( __DIR__ . '/build' );\n\n // Load MO files for PHP.\n load_plugin_textdomain( 'gutenpride', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );\n\n // Load JSON files for JS - this is necessary if using a custom languages path!!\n $script_handle = generate_block_asset_handle( 'create-block/gutenpride', 'editorScript' );\n wp_set_script_translations( $script_handle, 'gutenpride', plugin_dir_path( __FILE__ ) . 'languages' );\n}\nadd_action( 'init', 'create_block_gutenpride_block_init' );\n</code></pre>\n<ul>\n<li>Note: I followed the same steps as in your procedure, but I got an extra step — I created an MO file for use in standard PHP translations, e.g. <code><?php _e( 'text', 'gutenpride' ); ?></code>.</li>\n</ul>\n<h3>Additional Notes</h3>\n<ol>\n<li><p>If the 3rd parameter for <code>wp_set_script_translations()</code> is specified and the path/folder contains a JSON translations file named <code><text domain>-<locale>-<script handle>.json</code>, e.g. <code>gutenpride-fr_BE-create-block-gutenpride-editor-script.json</code>, then WordPress will attempt to load that <em>first</em>.</p>\n<p>So if the file doesn't exist, then WordPress will attempt to load the default one with the MD5 hash, e.g. <code>gutenpride-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json</code>.</p>\n</li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/load_script_translations/\" rel=\"noreferrer\"><code>load_script_translations()</code></a> is the function used to load translations from script translations files, i.e. that function opens the file and reads its content; and the function applies filters like <a href=\"https://developer.wordpress.org/reference/hooks/load_script_translation_file/\" rel=\"noreferrer\"><code>load_script_translation_file</code></a> which you may find useful when debugging.. :)</p>\n</li>\n<li><p>My "Gutenpride" block was tried & tested with WordPress v6.0, and the latest version of the @wordpress/create-block package at the time of writing.</p>\n</li>\n</ol>\n"
}
] | 2022/07/04 | [
"https://wordpress.stackexchange.com/questions/407346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29500/"
] | When using `@wordpress/create-block` to scaffhold a plugin for a block, the generated bundle is automatically registered via the `block.json` metadata :
```json
{
...
"name": "my-block",
"textdomain": "my-block",
"editorScript": "file:./index.js",
...
}
```
No need to call `wp_register_script` myself. This is great since it automatically handles dependencies via the `index.asset.php` file generated in the build folder.
Following the procedure mentionned [in the doc](https://developer.wordpress.org/block-editor/how-to-guides/internationalization/), I then create a JET translation file. Here is the procedure :
1. Creating POT file with `wp i18n make-pot . languages/my-block.pot`
2. Creating PO file with `cp languages/test.pot languages/my-block-FR_BE.po`
3. Filling msgstr strings in `my-block-FR_BE.po`
4. Adding line `"Language: fr_BE\n"` to `my-block-FR_BE.po`
5. Creating JSON file with `wp i18n make-json languages/my-block-FR_BE.po --no-purge`
The JSON generated is appended with a md5 hash: **my-block-fr\_BE-cae574befd871d4f740fd8b719bac1db.json**.
Now I have to call `wp_set_script_translations` in my init method :
```php
function my_block_init() {
register_block_type( __DIR__ . '/build' );
wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );
}
```
This does not work.
In order to make it work, I have to register the script and enqueue it, loosing the ability to have dependencies automatically injected :
```php
function my_block_init() {
wp_register_script(
'my-block-script',
plugins_url('/build/index.js', __FILE__),
array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-react-refresh-runtime')
);
wp_enqueue_script('my-block-script');
register_block_type( __DIR__ . '/build' );
wp_set_script_translations('my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/');
}
```
I also need to rename my JSON file to include the script handle instead of the automatically generated md5 hash. The ["Load Translation File"](https://developer.wordpress.org/block-editor/how-to-guides/internationalization/#load-translation-file) section in the doc gives me the impression that this shouldn't be necessary when keeping the generated name, though I'm not sure of what I'm supposed to do here :
>
> WordPress will check for a file in that path with the format ${domain}-${locale}-${handle}.json as the source of translations. Alternatively, instead of the registered handle you can use the md5 hash of the relative path of the file, ${domain}-${locale} in the form of ${domain}-${locale}-${md5}.json.
>
>
>
Is there a way to register JET translations for a script that is automatically registered via the block metadata ? And how can I use the generated name for the JSON file when registering my translation ?
### Edit
Here's the folder structure :
```
app/plugins/my-block/
├── build
│ ├── block.json
│ └── index.asset.php
│ └── index.css
│ └── index.js
│ └── style-index.css
├── languages
│ ├── my-block.pot
│ └── my-block-fr_BE.po
│ └── my-block-fr_BE-my-block-script.json
├── src
│ ├── block.json
│ └── index.js
│ └── ...
└── my-block.php
```
And here's the content of the `my-block.php` file (plugin root) :
```php
<?php
/**
* Plugin Name: My Block
* Requires at least: 5.9
* Requires PHP: 7.0
* Version: 0.1.0
* Author: The WordPress Contributors
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: my-block
*/
function my_block_init() {
register_block_type( __DIR__ . '/build' );
wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );
}
add_action( 'init', 'my_block_init' );
``` | [@drskullster](https://wordpress.stackexchange.com/users/29500/drskullster) already posted a good answer, but I thought I should share the following which explains why [`wp_set_script_translations()`](https://developer.wordpress.org/reference/functions/wp_set_script_translations/) needs to be called manually:
1. Yes it's true that WordPress will automatically register and enqueue the block editor script. ***So we do not need to manually register/enqueue that script!***
2. WordPress will also automatically set the script's translations, but only if the block metadata file (i.e. `block.json`) specifies a valid text domain (e.g. `"textdomain": "gutenpride"`) and that the script has `wp-i18n` as one of its dependencies. See [`register_block_script_handle()`](https://developer.wordpress.org/reference/functions/register_block_script_handle/).
3. WordPress uses `wp_set_script_translations( $script_handle, $metadata['textdomain'] )` to register/set the translations for the script, which means the 3rd parameter (the file path) is not specified and therefore, WordPress will try to load the translation files from the `wp-content/languages/plugins` folder.
So for example, if `my-block-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json` was the JSON file name, then WordPress would attempt to load `wp-content/languages/plugins/my-block-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json`.
And thus, you should copy that file to the `wp-content/languages/plugins` folder. That way, your main plugin file would only need to call `register_block_type()` and that's it — no need to worry about the JSON file name or MD5 hash, and you also would **not** need to *manually* call `wp_set_script_translations()`.
But if you don't want to having to copy the files, then yes, you will need to manually call `wp_set_script_translations()`, but remember that the **script handle** is in the form of `<block name>-editor-script` where `<block name>` is the block name (which is the `name` property in `block.json`), but with *slashes (`/`) replaced with hypens (`-`)*.
* So if the block name is `my-block`, then the script handle would be `my-block-editor-script`. Or if the name is `create-block/gutenpride`, then the handle would be `create-block-gutenpride-editor-script`. See [`generate_block_asset_handle()`](https://developer.wordpress.org/reference/functions/generate_block_asset_handle/) for more details.
So I hope that helps, and FYI, the following is what I had in my main plugin file (`wp-content/plugins/gutenpride/gutenpride.php`):
```php
function create_block_gutenpride_block_init() {
register_block_type( __DIR__ . '/build' );
// Load MO files for PHP.
load_plugin_textdomain( 'gutenpride', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
// Load JSON files for JS - this is necessary if using a custom languages path!!
$script_handle = generate_block_asset_handle( 'create-block/gutenpride', 'editorScript' );
wp_set_script_translations( $script_handle, 'gutenpride', plugin_dir_path( __FILE__ ) . 'languages' );
}
add_action( 'init', 'create_block_gutenpride_block_init' );
```
* Note: I followed the same steps as in your procedure, but I got an extra step — I created an MO file for use in standard PHP translations, e.g. `<?php _e( 'text', 'gutenpride' ); ?>`.
### Additional Notes
1. If the 3rd parameter for `wp_set_script_translations()` is specified and the path/folder contains a JSON translations file named `<text domain>-<locale>-<script handle>.json`, e.g. `gutenpride-fr_BE-create-block-gutenpride-editor-script.json`, then WordPress will attempt to load that *first*.
So if the file doesn't exist, then WordPress will attempt to load the default one with the MD5 hash, e.g. `gutenpride-fr_BE-dfbff627e6c248bcb3b61d7d06da9ca9.json`.
2. [`load_script_translations()`](https://developer.wordpress.org/reference/functions/load_script_translations/) is the function used to load translations from script translations files, i.e. that function opens the file and reads its content; and the function applies filters like [`load_script_translation_file`](https://developer.wordpress.org/reference/hooks/load_script_translation_file/) which you may find useful when debugging.. :)
3. My "Gutenpride" block was tried & tested with WordPress v6.0, and the latest version of the @wordpress/create-block package at the time of writing. |
407,347 | <p>I have to create the next feature fore the project:</p>
<p>We have two type of top-bar lines. We need to show every second user(or user session I think it's more easy) different types of banners. Okay I created a really simple code for this propose:
//Create a session
session_start();</p>
<pre><code>if(isset( $_SESSION ) ){
$_SESSION['visitCount']++;
//Create the option for adding here the session value
add_option( 'banner_counter', $_SESSION['visitCount'] );
//Get curren value from the option table
$sessionValue = get_option('banner_counter');
//Added the value of new current session to the value from the optiontable
$TotalSession = $sessionValue + 1;
//Updat the option value for showing it on the admin section
update_option( 'banner_counter', $TotalSession );
}else{
$_SESSION['visitCount']=1;
}
</code></pre>
<p>For displing different banner I used the next code:</p>
<pre><code> <?php if($_SESSION['visitCount'] % 2): ?>
<h2>Banner One</h2>
<?php else: ?>
<h2>Banner One</h2>
<?php endif; ?>
</code></pre>
<p>And it works. But I afraid this is not correct solution used wp_option() for my propose. May be everybody could help me giving advise in this area.</p>
| [
{
"answer_id": 407352,
"author": "Bruno Ribarić",
"author_id": 200784,
"author_profile": "https://wordpress.stackexchange.com/users/200784",
"pm_score": 2,
"selected": false,
"text": "<p>You could set a cookie that identifies a user as belonging to either group, then based on the cookie display different things.</p>\n<p>And I think there is no need to save the counter, you can randomly assign a new user to a group.</p>\n"
},
{
"answer_id": 407377,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 2,
"selected": true,
"text": "<p>Instead of using the <a href=\"https://developer.wordpress.org/plugins/settings/options-api/\" rel=\"nofollow noreferrer\">Options API</a>, you'd be better off using the <a href=\"https://developer.wordpress.org/apis/handbook/transients/\" rel=\"nofollow noreferrer\">Transients API</a>, however in either case you'll be polluting the <code>*_options</code> table (even if you use transients with expiration times).</p>\n<p>I'd <strong>possibly recommend</strong> using <a href=\"https://github.com/ericmann/wp-session-manager\" rel=\"nofollow noreferrer\"><strong>wp-session-manager</strong></a> plugin by <a href=\"https://wordpress.stackexchange.com/users/46/eamann\">EAMann's</a> which will allow you to use and store <code>$_SESSION</code> data in a dedicated sessions database table that the plugin creates upon activation (or where it does not exist).</p>\n<p>Reading:</p>\n<ul>\n<li><a href=\"https://github.com/ericmann/wp-session-manager\" rel=\"nofollow noreferrer\">https://github.com/ericmann/wp-session-manager</a></li>\n<li><a href=\"https://wordpress.org/plugins/wp-session-manager\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-session-manager</a> (Plugin Repo)</li>\n<li><a href=\"https://developer.wordpress.org/apis/handbook/transients/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/apis/handbook/transients/</a></li>\n<li><a href=\"https://developer.wordpress.org/plugins/settings/options-api/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/settings/options-api/</a></li>\n</ul>\n"
}
] | 2022/07/04 | [
"https://wordpress.stackexchange.com/questions/407347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201628/"
] | I have to create the next feature fore the project:
We have two type of top-bar lines. We need to show every second user(or user session I think it's more easy) different types of banners. Okay I created a really simple code for this propose:
//Create a session
session\_start();
```
if(isset( $_SESSION ) ){
$_SESSION['visitCount']++;
//Create the option for adding here the session value
add_option( 'banner_counter', $_SESSION['visitCount'] );
//Get curren value from the option table
$sessionValue = get_option('banner_counter');
//Added the value of new current session to the value from the optiontable
$TotalSession = $sessionValue + 1;
//Updat the option value for showing it on the admin section
update_option( 'banner_counter', $TotalSession );
}else{
$_SESSION['visitCount']=1;
}
```
For displing different banner I used the next code:
```
<?php if($_SESSION['visitCount'] % 2): ?>
<h2>Banner One</h2>
<?php else: ?>
<h2>Banner One</h2>
<?php endif; ?>
```
And it works. But I afraid this is not correct solution used wp\_option() for my propose. May be everybody could help me giving advise in this area. | Instead of using the [Options API](https://developer.wordpress.org/plugins/settings/options-api/), you'd be better off using the [Transients API](https://developer.wordpress.org/apis/handbook/transients/), however in either case you'll be polluting the `*_options` table (even if you use transients with expiration times).
I'd **possibly recommend** using [**wp-session-manager**](https://github.com/ericmann/wp-session-manager) plugin by [EAMann's](https://wordpress.stackexchange.com/users/46/eamann) which will allow you to use and store `$_SESSION` data in a dedicated sessions database table that the plugin creates upon activation (or where it does not exist).
Reading:
* <https://github.com/ericmann/wp-session-manager>
* <https://wordpress.org/plugins/wp-session-manager> (Plugin Repo)
* <https://developer.wordpress.org/apis/handbook/transients/>
* <https://developer.wordpress.org/plugins/settings/options-api/> |
407,391 | <p>How do I get the full category path including the subcategories?</p>
<p>I am using</p>
<pre><code>if ( is_archive() ) {
$term = get_queried_object();
$page_path = $term->slug;
}
</code></pre>
<p><code>https://mandoemedia.com/blog/topic/aaa-1ndustries/beauty/</code> this returns <code>beauty</code> only, <strong>not</strong> <code>aaa-1ndustries/beauty</code>.</p>
<p>How do I grab the parent category and subcategory, i.e. <code>aaa-1ndustries/beauty</code>?</p>
<p>The previous developer added some code to prefix post categories with <code>/blog/topic/</code>.</p>
| [
{
"answer_id": 407469,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>How do I grab the parent category and subcategory, i.e. <code>aaa-1ndustries/beauty</code>?</p>\n</blockquote>\n<p>Well if you meant the <strong>current</strong> category URL, where it looks like <code>https://example.com/blog/topic/aaa-1ndustries/beauty/</code>, and you just wanted to get the above category path from that URL, then try this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$request = $GLOBALS['wp']->request;\n$page_path = trim( preg_replace( '#^blog/topic/#', '', $request ), '/' );\n</code></pre>\n<p>And if you want to do the same for a specific category URL/<strong>permalink</strong>, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_category_link/\" rel=\"nofollow noreferrer\"><code>get_category_link()</code></a> (or <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a> for custom taxonomies) and <a href=\"https://www.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\"><code>parse_url()</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$cat_id = 123; // change the value to the correct category ID\n$request = parse_url( get_category_link( $cat_id ), PHP_URL_PATH );\n$page_path = trim( preg_replace( '#^/blog/topic/#', '', $request ), '/' );\n</code></pre>\n<p>But if you actually wanted to get the <strong>actual <em>hierarchical path</em></strong> of the category, then use <a href=\"https://developer.wordpress.org/reference/functions/get_category_parents/\" rel=\"nofollow noreferrer\"><code>get_category_parents()</code></a> (or <a href=\"https://developer.wordpress.org/reference/functions/get_term_parents_list/\" rel=\"nofollow noreferrer\"><code>get_term_parents_list()</code></a> for custom taxonomies). E.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Use this for the core `category` taxonomy:\n$cat_id = get_queried_object_id(); // or just set a specific category ID\n$cat_path = get_category_parents( $cat_id, false, '/', true );\n\n// OR use this for custom taxonomies:\n$term = get_queried_object(); // or just set a specific term object\n$cat_path = get_term_parents_list( $term->term_id, $term->taxonomy, array(\n 'separator' => '/',\n 'link' => false,\n 'format' => 'slug',\n) );\n\necho trim( $cat_path, '/' ); // the trim() removes the trailing/last slash\n</code></pre>\n"
},
{
"answer_id": 407485,
"author": "Irfan",
"author_id": 193019,
"author_profile": "https://wordpress.stackexchange.com/users/193019",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to get full category path then you can use <code>get_term_link()</code>.\nSo your code shoud change as</p>\n<pre><code>if ( is_archive() ) {\n $term = get_queried_object();\n $full_path = get_term_link($term);\n}\n</code></pre>\n"
}
] | 2022/07/06 | [
"https://wordpress.stackexchange.com/questions/407391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | How do I get the full category path including the subcategories?
I am using
```
if ( is_archive() ) {
$term = get_queried_object();
$page_path = $term->slug;
}
```
`https://mandoemedia.com/blog/topic/aaa-1ndustries/beauty/` this returns `beauty` only, **not** `aaa-1ndustries/beauty`.
How do I grab the parent category and subcategory, i.e. `aaa-1ndustries/beauty`?
The previous developer added some code to prefix post categories with `/blog/topic/`. | >
> How do I grab the parent category and subcategory, i.e. `aaa-1ndustries/beauty`?
>
>
>
Well if you meant the **current** category URL, where it looks like `https://example.com/blog/topic/aaa-1ndustries/beauty/`, and you just wanted to get the above category path from that URL, then try this:
```php
$request = $GLOBALS['wp']->request;
$page_path = trim( preg_replace( '#^blog/topic/#', '', $request ), '/' );
```
And if you want to do the same for a specific category URL/**permalink**, you can use [`get_category_link()`](https://developer.wordpress.org/reference/functions/get_category_link/) (or [`get_term_link()`](https://developer.wordpress.org/reference/functions/get_term_link/) for custom taxonomies) and [`parse_url()`](https://www.php.net/manual/en/function.parse-url.php):
```php
$cat_id = 123; // change the value to the correct category ID
$request = parse_url( get_category_link( $cat_id ), PHP_URL_PATH );
$page_path = trim( preg_replace( '#^/blog/topic/#', '', $request ), '/' );
```
But if you actually wanted to get the **actual *hierarchical path*** of the category, then use [`get_category_parents()`](https://developer.wordpress.org/reference/functions/get_category_parents/) (or [`get_term_parents_list()`](https://developer.wordpress.org/reference/functions/get_term_parents_list/) for custom taxonomies). E.g.
```php
// Use this for the core `category` taxonomy:
$cat_id = get_queried_object_id(); // or just set a specific category ID
$cat_path = get_category_parents( $cat_id, false, '/', true );
// OR use this for custom taxonomies:
$term = get_queried_object(); // or just set a specific term object
$cat_path = get_term_parents_list( $term->term_id, $term->taxonomy, array(
'separator' => '/',
'link' => false,
'format' => 'slug',
) );
echo trim( $cat_path, '/' ); // the trim() removes the trailing/last slash
``` |
407,454 | <p>So I have a complex list of ACF repeaters for ingredients, but have a save hook to store them all as one comma delimited text string in a custom field to help. My current "advanced" search passes ingredient searches as a meta query and works, but non-exact matches return nothing. Like if you search "pepper and paprika" it fails, but if you search "pepper" or "paprika" there are common posts (recipes).</p>
<p>Is there a way to make a meta query work like a normal query a little bit more?</p>
<p>My meta_query:</p>
<pre><code> $args['meta_query'] = array(
array(
'key' => 'ingredient_list',
'value' => $search_query,
'compare' => 'LIKE',
)
);
</code></pre>
<p>Thank you for any help!</p>
| [
{
"answer_id": 407469,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>How do I grab the parent category and subcategory, i.e. <code>aaa-1ndustries/beauty</code>?</p>\n</blockquote>\n<p>Well if you meant the <strong>current</strong> category URL, where it looks like <code>https://example.com/blog/topic/aaa-1ndustries/beauty/</code>, and you just wanted to get the above category path from that URL, then try this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$request = $GLOBALS['wp']->request;\n$page_path = trim( preg_replace( '#^blog/topic/#', '', $request ), '/' );\n</code></pre>\n<p>And if you want to do the same for a specific category URL/<strong>permalink</strong>, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_category_link/\" rel=\"nofollow noreferrer\"><code>get_category_link()</code></a> (or <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a> for custom taxonomies) and <a href=\"https://www.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\"><code>parse_url()</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$cat_id = 123; // change the value to the correct category ID\n$request = parse_url( get_category_link( $cat_id ), PHP_URL_PATH );\n$page_path = trim( preg_replace( '#^/blog/topic/#', '', $request ), '/' );\n</code></pre>\n<p>But if you actually wanted to get the <strong>actual <em>hierarchical path</em></strong> of the category, then use <a href=\"https://developer.wordpress.org/reference/functions/get_category_parents/\" rel=\"nofollow noreferrer\"><code>get_category_parents()</code></a> (or <a href=\"https://developer.wordpress.org/reference/functions/get_term_parents_list/\" rel=\"nofollow noreferrer\"><code>get_term_parents_list()</code></a> for custom taxonomies). E.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Use this for the core `category` taxonomy:\n$cat_id = get_queried_object_id(); // or just set a specific category ID\n$cat_path = get_category_parents( $cat_id, false, '/', true );\n\n// OR use this for custom taxonomies:\n$term = get_queried_object(); // or just set a specific term object\n$cat_path = get_term_parents_list( $term->term_id, $term->taxonomy, array(\n 'separator' => '/',\n 'link' => false,\n 'format' => 'slug',\n) );\n\necho trim( $cat_path, '/' ); // the trim() removes the trailing/last slash\n</code></pre>\n"
},
{
"answer_id": 407485,
"author": "Irfan",
"author_id": 193019,
"author_profile": "https://wordpress.stackexchange.com/users/193019",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to get full category path then you can use <code>get_term_link()</code>.\nSo your code shoud change as</p>\n<pre><code>if ( is_archive() ) {\n $term = get_queried_object();\n $full_path = get_term_link($term);\n}\n</code></pre>\n"
}
] | 2022/07/07 | [
"https://wordpress.stackexchange.com/questions/407454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/221659/"
] | So I have a complex list of ACF repeaters for ingredients, but have a save hook to store them all as one comma delimited text string in a custom field to help. My current "advanced" search passes ingredient searches as a meta query and works, but non-exact matches return nothing. Like if you search "pepper and paprika" it fails, but if you search "pepper" or "paprika" there are common posts (recipes).
Is there a way to make a meta query work like a normal query a little bit more?
My meta\_query:
```
$args['meta_query'] = array(
array(
'key' => 'ingredient_list',
'value' => $search_query,
'compare' => 'LIKE',
)
);
```
Thank you for any help! | >
> How do I grab the parent category and subcategory, i.e. `aaa-1ndustries/beauty`?
>
>
>
Well if you meant the **current** category URL, where it looks like `https://example.com/blog/topic/aaa-1ndustries/beauty/`, and you just wanted to get the above category path from that URL, then try this:
```php
$request = $GLOBALS['wp']->request;
$page_path = trim( preg_replace( '#^blog/topic/#', '', $request ), '/' );
```
And if you want to do the same for a specific category URL/**permalink**, you can use [`get_category_link()`](https://developer.wordpress.org/reference/functions/get_category_link/) (or [`get_term_link()`](https://developer.wordpress.org/reference/functions/get_term_link/) for custom taxonomies) and [`parse_url()`](https://www.php.net/manual/en/function.parse-url.php):
```php
$cat_id = 123; // change the value to the correct category ID
$request = parse_url( get_category_link( $cat_id ), PHP_URL_PATH );
$page_path = trim( preg_replace( '#^/blog/topic/#', '', $request ), '/' );
```
But if you actually wanted to get the **actual *hierarchical path*** of the category, then use [`get_category_parents()`](https://developer.wordpress.org/reference/functions/get_category_parents/) (or [`get_term_parents_list()`](https://developer.wordpress.org/reference/functions/get_term_parents_list/) for custom taxonomies). E.g.
```php
// Use this for the core `category` taxonomy:
$cat_id = get_queried_object_id(); // or just set a specific category ID
$cat_path = get_category_parents( $cat_id, false, '/', true );
// OR use this for custom taxonomies:
$term = get_queried_object(); // or just set a specific term object
$cat_path = get_term_parents_list( $term->term_id, $term->taxonomy, array(
'separator' => '/',
'link' => false,
'format' => 'slug',
) );
echo trim( $cat_path, '/' ); // the trim() removes the trailing/last slash
``` |
407,541 | <p>I've added a <code>wp_login</code> action and it's getting executed. Then within that function, I'm adding a filter to <code>the_content</code> so that a script gets inserted upon certain conditions but it's not getting executed. The filter within the <code>wp_login</code> action is:</p>
<pre><code>add_filter( 'the_content', 'my_function', 10, 1 );
</code></pre>
<p>If I move that filter to outside <code>wp_login</code> it works.</p>
<p>I've also tried adding actions '<code>wp_loaded</code>' and '<code>wp_enqueue_scripts</code>' but no go either.</p>
<p>Do the actions get cleared at some stage after <code>wp_login</code>?</p>
| [
{
"answer_id": 407547,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You've misunderstood how hooks, and PHP, work.</p>\n<p>Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run <code>add_action()</code> that queues up a callback function to run whenever the corresponding <code>do_action()</code> is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.</p>\n<p>So, if you try to run <code>add_filter( 'the_content', 'my_function', 10, 1 );</code> on <code>wp_login</code>, the <code>my_function()</code> callback will only be applied to <code>the_content</code> if the <code>the_content</code> is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.</p>\n<p>What you are <em>actually</em> trying to do is filter <code>the_content</code> if the current user is logged in. The proper way to do that is to check if the user is logged in inside <code>my_function()</code> and to add your filter for every request:</p>\n<pre><code>function my_function( $content ) {\n if ( is_user_logged_in() ) {\n // Do something with $content.\n }\n\n return $content;\n}\nadd_filter( 'the_content', 'my_function' );\n</code></pre>\n<p>Note that <code>add_filter()</code> is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used <code>is_user_logged_in()</code> <em>inside</em> the callback function, instead of around <code>add_filter()</code>. This is because when <code>add_filter()</code> will be run it hasn't been determined if the user is logged in or not yet.</p>\n"
},
{
"answer_id": 407550,
"author": "Kristián Filo",
"author_id": 138610,
"author_profile": "https://wordpress.stackexchange.com/users/138610",
"pm_score": 1,
"selected": false,
"text": "<p>I've read your question and comments once again and I finally get what you are trying to achieve here. Calling <code>the_content</code> filter from inside <code>wp_login</code> callback will not work (as explained in Jacob's answer in detail).</p>\n<p>Solution in my link I posted as a comment above will also not work, it's meant for a different scenario.</p>\n<p>Your best bet would be to assign custom <code>user_meta</code> value to each user, that would prevent second and any other subsequent runs of your code. Here's a simple example:</p>\n<pre><code>function custom_the_content( $content ) {\n\n // Only for logged in users\n if( is_user_logged_in() ) {\n\n // Get user ID\n $user_id = get_current_user_id();\n\n // Check if the content was already filtered for this user (if yes, do nothing)\n if( get_user_meta($user_id, 'content_filtered', true) ) {\n return;\n }\n\n // Filter the content (do anything)\n // ...\n\n // Set the user meta for subsequent checks\n update_user_meta($user_id, 'content_filtered', 'yes');\n }\n}\nadd_filter('the_content', 'custom_the_content');\n</code></pre>\n<p>Add your code (any changes to <code>the_content</code>) instead of the three dots in my example. The code should be altered only <strong>once</strong> for each logged in user.</p>\n<p><strong>EDIT:</strong> If you need to change the content every time the user logs in, you can just delete this custom user meta with the <code>wp_login</code> action (or you can use cookies, session variables or WordPress transients instead of database meta data, your choice).</p>\n"
}
] | 2022/07/11 | [
"https://wordpress.stackexchange.com/questions/407541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165118/"
] | I've added a `wp_login` action and it's getting executed. Then within that function, I'm adding a filter to `the_content` so that a script gets inserted upon certain conditions but it's not getting executed. The filter within the `wp_login` action is:
```
add_filter( 'the_content', 'my_function', 10, 1 );
```
If I move that filter to outside `wp_login` it works.
I've also tried adding actions '`wp_loaded`' and '`wp_enqueue_scripts`' but no go either.
Do the actions get cleared at some stage after `wp_login`? | You've misunderstood how hooks, and PHP, work.
Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run `add_action()` that queues up a callback function to run whenever the corresponding `do_action()` is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.
So, if you try to run `add_filter( 'the_content', 'my_function', 10, 1 );` on `wp_login`, the `my_function()` callback will only be applied to `the_content` if the `the_content` is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.
What you are *actually* trying to do is filter `the_content` if the current user is logged in. The proper way to do that is to check if the user is logged in inside `my_function()` and to add your filter for every request:
```
function my_function( $content ) {
if ( is_user_logged_in() ) {
// Do something with $content.
}
return $content;
}
add_filter( 'the_content', 'my_function' );
```
Note that `add_filter()` is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used `is_user_logged_in()` *inside* the callback function, instead of around `add_filter()`. This is because when `add_filter()` will be run it hasn't been determined if the user is logged in or not yet. |
407,559 | <p>I've got a custom field set up using Advanced Custom Fields - the field is named "Company Logo" and is an image field which is returning an image url. I've tried the array and the image ID but nothing seems to work.</p>
<p>I'm attempting to use <code><img src="[acf field='company_logo']"></code></p>
<p>however it fails and displays</p>
<p><code><img src="[acf field='company_logo']"></code></p>
<p>in the page source - no idea how to get it to actually show the correct info.
Any ideas how to get it to show the image?</p>
| [
{
"answer_id": 407547,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You've misunderstood how hooks, and PHP, work.</p>\n<p>Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run <code>add_action()</code> that queues up a callback function to run whenever the corresponding <code>do_action()</code> is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.</p>\n<p>So, if you try to run <code>add_filter( 'the_content', 'my_function', 10, 1 );</code> on <code>wp_login</code>, the <code>my_function()</code> callback will only be applied to <code>the_content</code> if the <code>the_content</code> is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.</p>\n<p>What you are <em>actually</em> trying to do is filter <code>the_content</code> if the current user is logged in. The proper way to do that is to check if the user is logged in inside <code>my_function()</code> and to add your filter for every request:</p>\n<pre><code>function my_function( $content ) {\n if ( is_user_logged_in() ) {\n // Do something with $content.\n }\n\n return $content;\n}\nadd_filter( 'the_content', 'my_function' );\n</code></pre>\n<p>Note that <code>add_filter()</code> is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used <code>is_user_logged_in()</code> <em>inside</em> the callback function, instead of around <code>add_filter()</code>. This is because when <code>add_filter()</code> will be run it hasn't been determined if the user is logged in or not yet.</p>\n"
},
{
"answer_id": 407550,
"author": "Kristián Filo",
"author_id": 138610,
"author_profile": "https://wordpress.stackexchange.com/users/138610",
"pm_score": 1,
"selected": false,
"text": "<p>I've read your question and comments once again and I finally get what you are trying to achieve here. Calling <code>the_content</code> filter from inside <code>wp_login</code> callback will not work (as explained in Jacob's answer in detail).</p>\n<p>Solution in my link I posted as a comment above will also not work, it's meant for a different scenario.</p>\n<p>Your best bet would be to assign custom <code>user_meta</code> value to each user, that would prevent second and any other subsequent runs of your code. Here's a simple example:</p>\n<pre><code>function custom_the_content( $content ) {\n\n // Only for logged in users\n if( is_user_logged_in() ) {\n\n // Get user ID\n $user_id = get_current_user_id();\n\n // Check if the content was already filtered for this user (if yes, do nothing)\n if( get_user_meta($user_id, 'content_filtered', true) ) {\n return;\n }\n\n // Filter the content (do anything)\n // ...\n\n // Set the user meta for subsequent checks\n update_user_meta($user_id, 'content_filtered', 'yes');\n }\n}\nadd_filter('the_content', 'custom_the_content');\n</code></pre>\n<p>Add your code (any changes to <code>the_content</code>) instead of the three dots in my example. The code should be altered only <strong>once</strong> for each logged in user.</p>\n<p><strong>EDIT:</strong> If you need to change the content every time the user logs in, you can just delete this custom user meta with the <code>wp_login</code> action (or you can use cookies, session variables or WordPress transients instead of database meta data, your choice).</p>\n"
}
] | 2022/07/11 | [
"https://wordpress.stackexchange.com/questions/407559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/221091/"
] | I've got a custom field set up using Advanced Custom Fields - the field is named "Company Logo" and is an image field which is returning an image url. I've tried the array and the image ID but nothing seems to work.
I'm attempting to use `<img src="[acf field='company_logo']">`
however it fails and displays
`<img src="[acf field='company_logo']">`
in the page source - no idea how to get it to actually show the correct info.
Any ideas how to get it to show the image? | You've misunderstood how hooks, and PHP, work.
Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run `add_action()` that queues up a callback function to run whenever the corresponding `do_action()` is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.
So, if you try to run `add_filter( 'the_content', 'my_function', 10, 1 );` on `wp_login`, the `my_function()` callback will only be applied to `the_content` if the `the_content` is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.
What you are *actually* trying to do is filter `the_content` if the current user is logged in. The proper way to do that is to check if the user is logged in inside `my_function()` and to add your filter for every request:
```
function my_function( $content ) {
if ( is_user_logged_in() ) {
// Do something with $content.
}
return $content;
}
add_filter( 'the_content', 'my_function' );
```
Note that `add_filter()` is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used `is_user_logged_in()` *inside* the callback function, instead of around `add_filter()`. This is because when `add_filter()` will be run it hasn't been determined if the user is logged in or not yet. |
407,578 | <p>I have FTP (SFTP) working on Filezilla and also on an "old" Wordpress site (I mean I set up the FTP for that site months ago), but it's not working on a new site.</p>
<p>I'm trying to duplicate that old Wordpress site on a new domain. I've copied all the files and ran the installer OK (I've changed the wp-config.php file before to use a different DB).</p>
<p>But I need the FTP to work inside the new Wordpress site/domain and I've been unable to do it. I've tried the same configuration from Filezilla (indicating the port and without the port, using FTP and SFTP) and nothing works.</p>
<p>Any idea of what could be the issue or how to troubleshoot this?</p>
<p>Also, is there a Wordpress page or file where I can check the FTP settings of my old Wordpress site? (it never asks me for FTP data anymore, it just works).</p>
<p>Thanks!</p>
<p><em>Extra info: All sites are on the same DigitalOcean server/droplet, I'm using Apache, SFTP for Filezilla and I've started using SSH recently, but the "old" Wordpress site was configured before using SSH and its FTP settings are still working OK</em></p>
| [
{
"answer_id": 407547,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You've misunderstood how hooks, and PHP, work.</p>\n<p>Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run <code>add_action()</code> that queues up a callback function to run whenever the corresponding <code>do_action()</code> is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.</p>\n<p>So, if you try to run <code>add_filter( 'the_content', 'my_function', 10, 1 );</code> on <code>wp_login</code>, the <code>my_function()</code> callback will only be applied to <code>the_content</code> if the <code>the_content</code> is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.</p>\n<p>What you are <em>actually</em> trying to do is filter <code>the_content</code> if the current user is logged in. The proper way to do that is to check if the user is logged in inside <code>my_function()</code> and to add your filter for every request:</p>\n<pre><code>function my_function( $content ) {\n if ( is_user_logged_in() ) {\n // Do something with $content.\n }\n\n return $content;\n}\nadd_filter( 'the_content', 'my_function' );\n</code></pre>\n<p>Note that <code>add_filter()</code> is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used <code>is_user_logged_in()</code> <em>inside</em> the callback function, instead of around <code>add_filter()</code>. This is because when <code>add_filter()</code> will be run it hasn't been determined if the user is logged in or not yet.</p>\n"
},
{
"answer_id": 407550,
"author": "Kristián Filo",
"author_id": 138610,
"author_profile": "https://wordpress.stackexchange.com/users/138610",
"pm_score": 1,
"selected": false,
"text": "<p>I've read your question and comments once again and I finally get what you are trying to achieve here. Calling <code>the_content</code> filter from inside <code>wp_login</code> callback will not work (as explained in Jacob's answer in detail).</p>\n<p>Solution in my link I posted as a comment above will also not work, it's meant for a different scenario.</p>\n<p>Your best bet would be to assign custom <code>user_meta</code> value to each user, that would prevent second and any other subsequent runs of your code. Here's a simple example:</p>\n<pre><code>function custom_the_content( $content ) {\n\n // Only for logged in users\n if( is_user_logged_in() ) {\n\n // Get user ID\n $user_id = get_current_user_id();\n\n // Check if the content was already filtered for this user (if yes, do nothing)\n if( get_user_meta($user_id, 'content_filtered', true) ) {\n return;\n }\n\n // Filter the content (do anything)\n // ...\n\n // Set the user meta for subsequent checks\n update_user_meta($user_id, 'content_filtered', 'yes');\n }\n}\nadd_filter('the_content', 'custom_the_content');\n</code></pre>\n<p>Add your code (any changes to <code>the_content</code>) instead of the three dots in my example. The code should be altered only <strong>once</strong> for each logged in user.</p>\n<p><strong>EDIT:</strong> If you need to change the content every time the user logs in, you can just delete this custom user meta with the <code>wp_login</code> action (or you can use cookies, session variables or WordPress transients instead of database meta data, your choice).</p>\n"
}
] | 2022/07/12 | [
"https://wordpress.stackexchange.com/questions/407578",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223970/"
] | I have FTP (SFTP) working on Filezilla and also on an "old" Wordpress site (I mean I set up the FTP for that site months ago), but it's not working on a new site.
I'm trying to duplicate that old Wordpress site on a new domain. I've copied all the files and ran the installer OK (I've changed the wp-config.php file before to use a different DB).
But I need the FTP to work inside the new Wordpress site/domain and I've been unable to do it. I've tried the same configuration from Filezilla (indicating the port and without the port, using FTP and SFTP) and nothing works.
Any idea of what could be the issue or how to troubleshoot this?
Also, is there a Wordpress page or file where I can check the FTP settings of my old Wordpress site? (it never asks me for FTP data anymore, it just works).
Thanks!
*Extra info: All sites are on the same DigitalOcean server/droplet, I'm using Apache, SFTP for Filezilla and I've started using SSH recently, but the "old" Wordpress site was configured before using SSH and its FTP settings are still working OK* | You've misunderstood how hooks, and PHP, work.
Hooks are not persistent. Each time you visit a page in WordPress the PHP scripts that comprise WordPress all get run. Every time. This includes plugins and the theme's the functions.php file. So when you run `add_action()` that queues up a callback function to run whenever the corresponding `do_action()` is run. Once everything has run and the page has rendered nothing is remembered. The only persistent information is whatever gets stored in the database, and hook callbacks are not stored in the database.
So, if you try to run `add_filter( 'the_content', 'my_function', 10, 1 );` on `wp_login`, the `my_function()` callback will only be applied to `the_content` if the `the_content` is displayed for that single request where the user is logged in. This is almost certainly never going to happen because users are typically redirected after being logged in, and that redirect is a separate request.
What you are *actually* trying to do is filter `the_content` if the current user is logged in. The proper way to do that is to check if the user is logged in inside `my_function()` and to add your filter for every request:
```
function my_function( $content ) {
if ( is_user_logged_in() ) {
// Do something with $content.
}
return $content;
}
add_filter( 'the_content', 'my_function' );
```
Note that `add_filter()` is at the 'top level', and not inside another hook. It will run on every request, but the content will only be modified if the user is logged in. Also note that we used `is_user_logged_in()` *inside* the callback function, instead of around `add_filter()`. This is because when `add_filter()` will be run it hasn't been determined if the user is logged in or not yet. |
407,600 | <p>I am learning WordPress Plugin Development. My Code is like below.</p>
<pre><code>class Admin
{
public function __construct()
{
add_action( 'admin_menu', [$this,'news_meta_boxes'] );
}
public function news_meta_boxes()
{
add_meta_box('news_settings', 'News Settings', [ $this, 'post_settings_html' ], 'news', 'normal', 'default');
add_meta_box('display_settings', 'Display Settings', [ $this, 'display_settings_html' ], 'news', 'normal', 'default');
add_meta_box('style_settings', 'Color Settings', [ $this, 'style_settings_html' ], 'news', 'normal', 'default');
}
public function post_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
public function display_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
public function style_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
}
</code></pre>
<p>How can I use <code>$stored_meta = get_post_meta($post->ID);</code> globally like member variable ?</p>
| [
{
"answer_id": 407607,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>First thing you can do is to switch to using <a href=\"https://developer.wordpress.org/reference/hooks/add_meta_boxes_post_type/\" rel=\"nofollow noreferrer\">add_meta_boxes_{$post_type}</a> action to register your metaboxes. This way the register method only fires for your custom post type. This action also gives you the current post as a parameter and can be used to fetch the post meta data.</p>\n<p>Another thing is to pass custom callback args to the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">add_meta_box()</a> function as the last argument. This data is then available in the render callback. The callback argument could be used to pass the meta data to the render function. Alternatively get the meta data in the render method by getting the current post ID from the post object that is passed as the first parameter to the method.</p>\n<p>The following example demonstrates these improvements. In my example I've also split the metabox configuration to its own method and assume the metabox html is located in a separate template file (<em>to keep the render method cleaner</em>).</p>\n<p>Note the metakey usage in the <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta()</a>. If you happen to save the data from the metabox as an array, then you can do this to only pass the needed data to the specific metabox.</p>\n<pre><code>class Admin\n{\n\n public function __construct()\n {\n add_action( 'add_meta_boxes_news', [$this,'register_news_metaboxes'] );\n }\n\n public function register_news_metaboxes(WP_Post $post)\n {\n foreach ($this->metaboxes() as $metabox_id => $metabox) {\n add_meta_box(\n $metabox_id,\n $metabox['title'],\n [$this, 'render_metabox'],\n $post->post_type,\n $metabox['context'],\n $metabox['priority'],\n [\n 'post_meta' => get_post_meta(\n $post->ID,\n $metabox['metakey'] ?: $metabox_id,\n true\n ), // get meta by key maybe?\n 'template' => $metabox['template'],\n ]\n );\n }\n }\n\n public function render_metabox(WP_Post $post, array $metabox)\n {\n // $metabox array keys: id, title, callback, args\n // var_dump($metabox);\n $callbackArgs = $metabox['args'];\n $postMeta = $callbackArgs['post_meta'];\n $templateFile = $callbackArgs['template'];\n\n if ( file_exists($templateFile) ) {\n // the declared variables and function parameters\n // are available in the included file\n // e.g. $postMeta\n include_once $templateFile;\n }\n }\n\n protected function metaboxes()\n {\n return [\n 'news_settings' => [\n 'title' => 'News Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n 'display_settings' => [\n 'title' => 'Display Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n 'style_settings' => [\n 'title' => 'Color Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n ];\n }\n}\n</code></pre>\n<p><em>Modify as needed.</em></p>\n"
},
{
"answer_id": 407608,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p><em>You shouldn’t</em>.</p>\n<p>To get the data for the correct post you should be using the <code>$post</code> variable passed to the callback function. This represents the post being edited. Therefore to get the metadata for the correct post you should call <code>get_post_meta()</code> inside the callback function.</p>\n"
}
] | 2022/07/13 | [
"https://wordpress.stackexchange.com/questions/407600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65189/"
] | I am learning WordPress Plugin Development. My Code is like below.
```
class Admin
{
public function __construct()
{
add_action( 'admin_menu', [$this,'news_meta_boxes'] );
}
public function news_meta_boxes()
{
add_meta_box('news_settings', 'News Settings', [ $this, 'post_settings_html' ], 'news', 'normal', 'default');
add_meta_box('display_settings', 'Display Settings', [ $this, 'display_settings_html' ], 'news', 'normal', 'default');
add_meta_box('style_settings', 'Color Settings', [ $this, 'style_settings_html' ], 'news', 'normal', 'default');
}
public function post_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
public function display_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
public function style_settings_html($post)
{
$stored_meta = get_post_meta($post->ID); // I would like to use it globally as like member variable
// more code here
}
}
```
How can I use `$stored_meta = get_post_meta($post->ID);` globally like member variable ? | *You shouldn’t*.
To get the data for the correct post you should be using the `$post` variable passed to the callback function. This represents the post being edited. Therefore to get the metadata for the correct post you should call `get_post_meta()` inside the callback function. |
407,604 | <p>i have a question about improving my solution.</p>
<p>For my task i build a Gutenberg block which shows the latest 5 Posts. This Posts show also the Category Name in the Frontend part which have different styling each.</p>
<p>so I'm using the get_post() function to get all Posts, but there comes no Categories which is the reason i also used wp_get_post_categories() function.</p>
<p>This works fine , i used a foreach in a foreach to get my results. But it kinda feel Hardcoded especially the checking if Category "News" or "informative" is used is definitely hard coded.</p>
<p>is there a better solution how can i archive it that i can get the Posts with there bonded Post categories?</p>
<p>this was the best i can get for now and it works but im not happy with this solution.</p>
<p>my code:</p>
<pre><code>...
$post = get_posts(
[
'posts_per_page' => 5,
]
);
...
ob_start();
some echos for html
...
foreach ($post AS $p)
{
$category = wp_get_post_categories($p->ID);
foreach ($category AS $cat)
{
echo '<div>';
echo '<div class="blog-image">';
echo '<img alt="" content="'.get_the_post_thumbnail($p->ID).'">';
echo '</div>';
echo '<div class="blog-data">';
echo '<div class="data-top">';
if(get_cat_name((int) $cat) === 'News')
{
echo '<div class="blog-type"><span class="news">'.get_cat_name((int) $cat).'</span></div>';
}elseif (get_cat_name((int) $cat) === 'Informative')
{
echo '<div class="blog-type"><span class="informative">'.get_cat_name((int) $cat).'</span></div>';
}
echo '<h3 class="blog-title">'.$p->post_title.'</h3>';
echo '</div>';
echo '<div class="data-bottom">';
echo '<div class="blog-info">';
echo '<p class="blog-date">'.date("d F Y", strtotime( $p->post_date)).'</p>';
echo '<div class="blog-link"><a href='.$p->guid.' >Read more</a></div> ';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
echo '<br/>';
}
...
more echos to close all html tags
return ob_get_clean();
</code></pre>
<p>here is also how it should look:</p>
<p><a href="https://i.stack.imgur.com/in9Xq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/in9Xq.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 407607,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>First thing you can do is to switch to using <a href=\"https://developer.wordpress.org/reference/hooks/add_meta_boxes_post_type/\" rel=\"nofollow noreferrer\">add_meta_boxes_{$post_type}</a> action to register your metaboxes. This way the register method only fires for your custom post type. This action also gives you the current post as a parameter and can be used to fetch the post meta data.</p>\n<p>Another thing is to pass custom callback args to the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">add_meta_box()</a> function as the last argument. This data is then available in the render callback. The callback argument could be used to pass the meta data to the render function. Alternatively get the meta data in the render method by getting the current post ID from the post object that is passed as the first parameter to the method.</p>\n<p>The following example demonstrates these improvements. In my example I've also split the metabox configuration to its own method and assume the metabox html is located in a separate template file (<em>to keep the render method cleaner</em>).</p>\n<p>Note the metakey usage in the <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta()</a>. If you happen to save the data from the metabox as an array, then you can do this to only pass the needed data to the specific metabox.</p>\n<pre><code>class Admin\n{\n\n public function __construct()\n {\n add_action( 'add_meta_boxes_news', [$this,'register_news_metaboxes'] );\n }\n\n public function register_news_metaboxes(WP_Post $post)\n {\n foreach ($this->metaboxes() as $metabox_id => $metabox) {\n add_meta_box(\n $metabox_id,\n $metabox['title'],\n [$this, 'render_metabox'],\n $post->post_type,\n $metabox['context'],\n $metabox['priority'],\n [\n 'post_meta' => get_post_meta(\n $post->ID,\n $metabox['metakey'] ?: $metabox_id,\n true\n ), // get meta by key maybe?\n 'template' => $metabox['template'],\n ]\n );\n }\n }\n\n public function render_metabox(WP_Post $post, array $metabox)\n {\n // $metabox array keys: id, title, callback, args\n // var_dump($metabox);\n $callbackArgs = $metabox['args'];\n $postMeta = $callbackArgs['post_meta'];\n $templateFile = $callbackArgs['template'];\n\n if ( file_exists($templateFile) ) {\n // the declared variables and function parameters\n // are available in the included file\n // e.g. $postMeta\n include_once $templateFile;\n }\n }\n\n protected function metaboxes()\n {\n return [\n 'news_settings' => [\n 'title' => 'News Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n 'display_settings' => [\n 'title' => 'Display Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n 'style_settings' => [\n 'title' => 'Color Settings',\n 'context' => 'normal',\n 'priority' => 'default',\n 'metakey' => '',\n 'template' => 'path/to/template.php',\n ],\n ];\n }\n}\n</code></pre>\n<p><em>Modify as needed.</em></p>\n"
},
{
"answer_id": 407608,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p><em>You shouldn’t</em>.</p>\n<p>To get the data for the correct post you should be using the <code>$post</code> variable passed to the callback function. This represents the post being edited. Therefore to get the metadata for the correct post you should call <code>get_post_meta()</code> inside the callback function.</p>\n"
}
] | 2022/07/13 | [
"https://wordpress.stackexchange.com/questions/407604",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223996/"
] | i have a question about improving my solution.
For my task i build a Gutenberg block which shows the latest 5 Posts. This Posts show also the Category Name in the Frontend part which have different styling each.
so I'm using the get\_post() function to get all Posts, but there comes no Categories which is the reason i also used wp\_get\_post\_categories() function.
This works fine , i used a foreach in a foreach to get my results. But it kinda feel Hardcoded especially the checking if Category "News" or "informative" is used is definitely hard coded.
is there a better solution how can i archive it that i can get the Posts with there bonded Post categories?
this was the best i can get for now and it works but im not happy with this solution.
my code:
```
...
$post = get_posts(
[
'posts_per_page' => 5,
]
);
...
ob_start();
some echos for html
...
foreach ($post AS $p)
{
$category = wp_get_post_categories($p->ID);
foreach ($category AS $cat)
{
echo '<div>';
echo '<div class="blog-image">';
echo '<img alt="" content="'.get_the_post_thumbnail($p->ID).'">';
echo '</div>';
echo '<div class="blog-data">';
echo '<div class="data-top">';
if(get_cat_name((int) $cat) === 'News')
{
echo '<div class="blog-type"><span class="news">'.get_cat_name((int) $cat).'</span></div>';
}elseif (get_cat_name((int) $cat) === 'Informative')
{
echo '<div class="blog-type"><span class="informative">'.get_cat_name((int) $cat).'</span></div>';
}
echo '<h3 class="blog-title">'.$p->post_title.'</h3>';
echo '</div>';
echo '<div class="data-bottom">';
echo '<div class="blog-info">';
echo '<p class="blog-date">'.date("d F Y", strtotime( $p->post_date)).'</p>';
echo '<div class="blog-link"><a href='.$p->guid.' >Read more</a></div> ';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
echo '<br/>';
}
...
more echos to close all html tags
return ob_get_clean();
```
here is also how it should look:
[](https://i.stack.imgur.com/in9Xq.png) | *You shouldn’t*.
To get the data for the correct post you should be using the `$post` variable passed to the callback function. This represents the post being edited. Therefore to get the metadata for the correct post you should call `get_post_meta()` inside the callback function. |
407,610 | <p>This snippet used to work fine but with the update to PHP 8.0 it now breaks the site when a WC order is switched to this custom status</p>
<pre><code>//Add custom bulk action in dropdown
add_filter( 'bulk_actions-edit-shop_order', 'register_bulk_action_printed' );
function register_bulk_action_printed( $bulk_actions ) {
$bulk_actions['mark_as_printed'] = 'Change status to Printed';
return $bulk_actions;
}
//Bulk action handler
add_action( 'admin_action_mark_as_printed', 'bulk_process_status_printed' );
function bulk_process_status_printed() {
if( !isset( $_REQUEST['post'] ) && !is_array( $_REQUEST['post'] ) )
return;
foreach( $_REQUEST['post'] as $order_id ) {
$order = new WC_Order( $order_id );
$order_note = 'That\'s what happened by bulk edit:';
$order->update_status( 'wc-printed', $order_note, true );
}
$location = add_query_arg( array(
'post_type' => 'shop_order',
'marked_as_printed' => 1, // marked_as_printed=1 is just the $_GET variable for notices
'changed' => count( $_REQUEST['post'] ), // number of changed orders
'ids' => join( $_REQUEST['post'], ',' ),
'post_status' => 'all'
), 'edit.php' );
wp_redirect( admin_url( $location ) );
exit;
}
/*
* Notices
*/
add_action('admin_notices', 'custom_order_status_notices_printed');
function custom_order_status_notices_printed() {
global $pagenow, $typenow;
if( $typenow == 'shop_order'
&& $pagenow == 'edit.php'
&& isset( $_REQUEST['marked_as_printed'] )
&& $_REQUEST['marked_as_printed'] == 1
&& isset( $_REQUEST['changed'] ) ) {
$message = sprintf( _n( 'Order status changed.', '%s order statuses changed.', $_REQUEST['changed'] ), number_format_i18n( $_REQUEST['changed'] ) );
echo "<div class=\"updated\"><p>{$message}</p></div>";
}
}
</code></pre>
<p>This is the error that I get:</p>
<pre><code>PHP Fatal error: Uncaught TypeError: join(): Argument #2 ($array) must be of type ?array, string given in /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code:32\nStack trace:\n#0 /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code(32): join(Array, ',')\n#1 /nas/content/live/allstaruhlmann/wp-includes/class-wp-hook.php(307): bulk_process_status_printed('')\n#2 /nas/content/live/allstaruhlmann/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters('', Array)\n#3 /nas/content/live/allstaruhlmann/wp-includes/plugin.php(476): WP_Hook->do_action(Array)\n#4 /nas/content/live/allstaruhlmann/wp-admin/admin.php(419): do_action('admin_action_ma...')\n#5 /nas/content/live/allstaruhlmann/wp-admin/edit.php(10): require_once('/nas/content/li...')\n#6 {main}\n thrown in /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code on line 32, referer: https://allstaruhlmann.com/wp-admin/edit.php?post_type=shop_order
</code></pre>
| [
{
"answer_id": 407611,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 3,
"selected": true,
"text": "<p>On this line in bulk_process_status_printed():</p>\n<pre class=\"lang-php prettyprint-override\"><code>'ids' => join( $_REQUEST['post'], ',' ),\n</code></pre>\n<p>you've got the arguments backwards: it should be <a href=\"https://www.php.net/manual/en/function.implode.php\" rel=\"nofollow noreferrer\">join(separator, array)</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>'ids' => join( ',', $_REQUEST['post'] ),\n</code></pre>\n<p>This is actually a PHP 8 change not WordPress 6</p>\n<blockquote>\n<p>8.0.0 - Passing the separator after the array is no longer supported.</p>\n</blockquote>\n"
},
{
"answer_id": 407631,
"author": "Jahangeer Iqbal",
"author_id": 224027,
"author_profile": "https://wordpress.stackexchange.com/users/224027",
"pm_score": 0,
"selected": false,
"text": "<p>The critical error in WordPress is generally caused by a malfunctioning plugin, script, or code that prevents WordPress from functioning properly.</p>\n<p>WordPress is unable to load the rest of the files it needs unless you resolve this issue.</p>\n"
}
] | 2022/07/13 | [
"https://wordpress.stackexchange.com/questions/407610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148232/"
] | This snippet used to work fine but with the update to PHP 8.0 it now breaks the site when a WC order is switched to this custom status
```
//Add custom bulk action in dropdown
add_filter( 'bulk_actions-edit-shop_order', 'register_bulk_action_printed' );
function register_bulk_action_printed( $bulk_actions ) {
$bulk_actions['mark_as_printed'] = 'Change status to Printed';
return $bulk_actions;
}
//Bulk action handler
add_action( 'admin_action_mark_as_printed', 'bulk_process_status_printed' );
function bulk_process_status_printed() {
if( !isset( $_REQUEST['post'] ) && !is_array( $_REQUEST['post'] ) )
return;
foreach( $_REQUEST['post'] as $order_id ) {
$order = new WC_Order( $order_id );
$order_note = 'That\'s what happened by bulk edit:';
$order->update_status( 'wc-printed', $order_note, true );
}
$location = add_query_arg( array(
'post_type' => 'shop_order',
'marked_as_printed' => 1, // marked_as_printed=1 is just the $_GET variable for notices
'changed' => count( $_REQUEST['post'] ), // number of changed orders
'ids' => join( $_REQUEST['post'], ',' ),
'post_status' => 'all'
), 'edit.php' );
wp_redirect( admin_url( $location ) );
exit;
}
/*
* Notices
*/
add_action('admin_notices', 'custom_order_status_notices_printed');
function custom_order_status_notices_printed() {
global $pagenow, $typenow;
if( $typenow == 'shop_order'
&& $pagenow == 'edit.php'
&& isset( $_REQUEST['marked_as_printed'] )
&& $_REQUEST['marked_as_printed'] == 1
&& isset( $_REQUEST['changed'] ) ) {
$message = sprintf( _n( 'Order status changed.', '%s order statuses changed.', $_REQUEST['changed'] ), number_format_i18n( $_REQUEST['changed'] ) );
echo "<div class=\"updated\"><p>{$message}</p></div>";
}
}
```
This is the error that I get:
```
PHP Fatal error: Uncaught TypeError: join(): Argument #2 ($array) must be of type ?array, string given in /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code:32\nStack trace:\n#0 /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code(32): join(Array, ',')\n#1 /nas/content/live/allstaruhlmann/wp-includes/class-wp-hook.php(307): bulk_process_status_printed('')\n#2 /nas/content/live/allstaruhlmann/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters('', Array)\n#3 /nas/content/live/allstaruhlmann/wp-includes/plugin.php(476): WP_Hook->do_action(Array)\n#4 /nas/content/live/allstaruhlmann/wp-admin/admin.php(419): do_action('admin_action_ma...')\n#5 /nas/content/live/allstaruhlmann/wp-admin/edit.php(10): require_once('/nas/content/li...')\n#6 {main}\n thrown in /nas/content/live/allstaruhlmann/wp-content/plugins/code-snippets/php/snippet-ops.php(484) : eval()'d code on line 32, referer: https://allstaruhlmann.com/wp-admin/edit.php?post_type=shop_order
``` | On this line in bulk\_process\_status\_printed():
```php
'ids' => join( $_REQUEST['post'], ',' ),
```
you've got the arguments backwards: it should be [join(separator, array)](https://www.php.net/manual/en/function.implode.php):
```php
'ids' => join( ',', $_REQUEST['post'] ),
```
This is actually a PHP 8 change not WordPress 6
>
> 8.0.0 - Passing the separator after the array is no longer supported.
>
>
> |
407,653 | <p>I have a custom post type I've created, and I've added an admin submenu page to display some data it generates. So far, so good. I'm displaying the data with my local extension of <code>WP_List_Table</code>, and I want one of the columns to link to a detailed view of the item in the row. So,</p>
<p>Add menu:</p>
<pre><code>add_submenu_page('edit.php?post_type=cwr_ticket_page',
__( 'Tickets', $this->plugin_text_domain ), // page title
__( 'Sold Tickets', $this->plugin_text_domain ), // menu title
'read', // capability
'cwr-tickets', // menu slug
array( $this, 'load_ticket_list_table' ) // callback
</code></pre>
<p>"Sold Tickets" correctly shows up as a sub-menu on my "Ticket Pages" admin menu.</p>
<p>The resulting url is <code>http://localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&page=cwr-tickets</code>, and that page correctly renders my table, all nicely using WP styles, with sortable columns and pagination, etc.... But one of my columns is "Details" and I want it to contain a link to a deeper view of the data represented in the given row.</p>
<p>So for the entries in my "Details" column, I want something like</p>
<p><code><a href="http://localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&page=cwr-tickets&view=details&ticketID=abc123">view</a></code></p>
<p>The question is, how to build that URL. I thought I could use <code>add_query_arg</code>, but it's behaving oddly.</p>
<p>My <code>column_default</code> method override looks like this:</p>
<pre><code>public function column_default( $item, $column_name ) {
switch ( $column_name ) {
...
case 'details':
$args = array (
'view' => 'details',
'ticketID' => '12345' //placeholder for development
);
return '<a href="'
. esc_url( add_query_arg( $args,
menu_page_url( 'cwr-tickets', false ) ) )
. '">View</a>';
...
}
}
</code></pre>
<p>I've tried it both with and without the <code>esc_url</code> wrapper, but either way, it ends up moving the existing <code>page</code> query arg to the end, and prepending it with <code>#038;</code> instead of the ampersand. That is, I get</p>
<p><code><a href="//localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&view=details&ticketID=12345#038;page=cwr-tickets">View</a></code></p>
<p>By the way, I'm in no way wed to this use of <code>menu_page_url</code> and <code>add_query_arg</code>; the question is, how to (properly / the WordPress way) construct this CPT admin submenu URL for the links?</p>
| [
{
"answer_id": 407672,
"author": "philolegein",
"author_id": 194028,
"author_profile": "https://wordpress.stackexchange.com/users/194028",
"pm_score": 0,
"selected": false,
"text": "<p>It appears this has been causing consternation for 11+ years, as it was reported as <a href=\"https://core.trac.wordpress.org/ticket/18274\" rel=\"nofollow noreferrer\">bug #18274</a> back then. The root cause was determined to be that <code>menu_page_url</code> runs through <code>esc_url</code> even when <code>display</code> is set to <code>false</code>, and it was decided that although that's probably undesirable, it was "too late" (<a href=\"https://core.trac.wordpress.org/ticket/18274#comment:9\" rel=\"nofollow noreferrer\">comment #9</a> from lead developer @nacin).</p>\n<p>I can't find a follow-on addition to WordPress core that returns the URL properly (i.e., unencoded), so I don't know if there's a "right WordPress way" to do this, but my workaround was to extract the relevant code from <a href=\"https://developer.wordpress.org/reference/functions/menu_page_url/#source\" rel=\"nofollow noreferrer\">menu_page_url</a> and not run it through <code>esc_url</code>:</p>\n<pre><code> case 'details':\n global $_parent_pages;\n $parent_slug = $_parent_pages[ 'cwr-tickets' ];\n $url = admin_url( add_query_arg( 'page', 'cwr-tickets',\n $parent_slug ) );\n $args = array (\n 'view' => 'details',\n 'ticketID' => '12345'\n );\n return '<a href="'\n . esc_url( add_query_arg( $args,\n $url ) )\n . '">View</a>';\n</code></pre>\n"
},
{
"answer_id": 407673,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>From your question:</p>\n<blockquote>\n<p>I've tried it both with and without the <code>esc_url</code> wrapper, but either\nway, it ends up moving the existing <code>page</code> query arg to the end, and\nprepending it with <code>#038;</code> instead of the ampersand.</p>\n</blockquote>\n<p>And from your answer:</p>\n<blockquote>\n<p>The root cause was determined to be that <code>menu_page_url</code> runs through\n<code>esc_url</code> even when <code>display</code> is set to <code>false</code></p>\n</blockquote>\n<p>So yes, that's correct, and you could alternatively manually construct the URL like so: <code>admin_url( 'edit.php?post_type=cwr_ticket_page&page=cwr-tickets' )</code>.</p>\n<p>But as for this:</p>\n<blockquote>\n<p>how to (properly / the WordPress way) construct this CPT admin submenu URL for the links</p>\n</blockquote>\n<p>Since you're linking to the same page, then just use <code>add_query_arg( $args )</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$link = '<a href="' . esc_url( add_query_arg( $args ) ) . '">View</a>';\n</code></pre>\n<p>Because <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\"><code>add_query_arg()</code></a> will default to using the current URL.</p>\n"
}
] | 2022/07/14 | [
"https://wordpress.stackexchange.com/questions/407653",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/194028/"
] | I have a custom post type I've created, and I've added an admin submenu page to display some data it generates. So far, so good. I'm displaying the data with my local extension of `WP_List_Table`, and I want one of the columns to link to a detailed view of the item in the row. So,
Add menu:
```
add_submenu_page('edit.php?post_type=cwr_ticket_page',
__( 'Tickets', $this->plugin_text_domain ), // page title
__( 'Sold Tickets', $this->plugin_text_domain ), // menu title
'read', // capability
'cwr-tickets', // menu slug
array( $this, 'load_ticket_list_table' ) // callback
```
"Sold Tickets" correctly shows up as a sub-menu on my "Ticket Pages" admin menu.
The resulting url is `http://localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&page=cwr-tickets`, and that page correctly renders my table, all nicely using WP styles, with sortable columns and pagination, etc.... But one of my columns is "Details" and I want it to contain a link to a deeper view of the data represented in the given row.
So for the entries in my "Details" column, I want something like
`<a href="http://localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&page=cwr-tickets&view=details&ticketID=abc123">view</a>`
The question is, how to build that URL. I thought I could use `add_query_arg`, but it's behaving oddly.
My `column_default` method override looks like this:
```
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
...
case 'details':
$args = array (
'view' => 'details',
'ticketID' => '12345' //placeholder for development
);
return '<a href="'
. esc_url( add_query_arg( $args,
menu_page_url( 'cwr-tickets', false ) ) )
. '">View</a>';
...
}
}
```
I've tried it both with and without the `esc_url` wrapper, but either way, it ends up moving the existing `page` query arg to the end, and prepending it with `#038;` instead of the ampersand. That is, I get
`<a href="//localhost:8181/wp-admin/edit.php?post_type=cwr_ticket_page&view=details&ticketID=12345#038;page=cwr-tickets">View</a>`
By the way, I'm in no way wed to this use of `menu_page_url` and `add_query_arg`; the question is, how to (properly / the WordPress way) construct this CPT admin submenu URL for the links? | From your question:
>
> I've tried it both with and without the `esc_url` wrapper, but either
> way, it ends up moving the existing `page` query arg to the end, and
> prepending it with `#038;` instead of the ampersand.
>
>
>
And from your answer:
>
> The root cause was determined to be that `menu_page_url` runs through
> `esc_url` even when `display` is set to `false`
>
>
>
So yes, that's correct, and you could alternatively manually construct the URL like so: `admin_url( 'edit.php?post_type=cwr_ticket_page&page=cwr-tickets' )`.
But as for this:
>
> how to (properly / the WordPress way) construct this CPT admin submenu URL for the links
>
>
>
Since you're linking to the same page, then just use `add_query_arg( $args )`:
```php
$link = '<a href="' . esc_url( add_query_arg( $args ) ) . '">View</a>';
```
Because [`add_query_arg()`](https://developer.wordpress.org/reference/functions/add_query_arg/) will default to using the current URL. |
407,741 | <p>I am reading a book called "Learn to Create WordPress Themes by Building 5 Projects" . In that to retrieve the parent for pages, they have a function to get the parent of the pages. The function is as follows,</p>
<pre><code>function page_is_parent(){
global $post;
$pages = get_pages('child_of='.$post->ID);
return count($pages);
}
</code></pre>
<p>Explanation given in the book is as follows,</p>
<blockquote>
<p>Now we just have About. We can navigate using the menu here. However, if we go to Sample Page or any other page, it's going to still have this even though there's no child links. So, we'll create another short function in the <code>functions.php</code> file and call <code>page_is_parent</code>. Then, we'll say global <code>$post</code> and set <code>$pages</code> equal to <code>get_pages()</code>, and in here, we'll say <code>'child_of='</code> and concatenate the post ID. Next, we'll say return and then, we want the number of pages, so we'll <code>count($pages)</code>:</p>
</blockquote>
<p>But I feel the <code>$pages = get_pages('child_of='.$post->ID);</code> is weird since they pass a string <code>'child_of='.$post->ID</code> Please explain why a string is passed and why it is concatenated.</p>
| [
{
"answer_id": 407743,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>It is concatenated because that's how we <a href=\"https://www.php.net/manual/en/language.operators.string.php\" rel=\"nofollow noreferrer\">combine strings together in PHP</a>, and string is passed because arguments <strong>can be passed as a query string or an array of <code>key => value</code> pairs</strong>.</p>\n<p>See the <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\"><code>get_pages()</code> documentation</a> for more details.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// So both of these will work:\n\n// 1. Pass string of arguments.\n$pages = get_pages( 'child_of=' . $post->ID );\n\n// 2. Pass array of arguments.\n$pages = get_pages( array(\n 'child_of' => $post->ID,\n) );\n</code></pre>\n<p>So if I had to give you a reason why would I use the former (the first one in the above example), then it'd be: because it actually works and simpler in the case of the argument in question.</p>\n<p>And one could also use double quotes instead, e.g. <code>"child_of={$post->ID}"</code>, but if you need explanation on that, you should ask on Stack Overflow :)</p>\n"
},
{
"answer_id": 407744,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Indeed - in <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\">the <code>get_pages()</code> documentation</a> we can see that it accepts either a string or an array as an argument. It does seem a little bit weird to call a function with the arguments concatenated into a string, doesn't it?</p>\n<p>Under the hood, the <code>get_pages()</code> function uses <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">the <code>WP_Query</code> class</a> in order to query for Page-type posts, and the root of the ambiguity boils down to <code>WP_Query</code>'s implementation. The class was built such that it can accept a string of query arguments which will be converted into a more appropriate data structure - an associative array of arguments - before creating the actual SQL query to retrieve data from the database. The reason <code>WP_Query</code> was built this way is to accommodate queries which are specified via the "querystring" or "search string" in the URL (the list of key/value pairs which begins after a <code>?</code> and is delineated with an <code>&</code> thereafter).</p>\n<p>In my opinion, I would agree with your skepticism - it doesn't make sense to me to use a query in string format when writing an internal function such as the one described by the book, more specifically for two reasons:</p>\n<ul>\n<li>String concatenation is inelegant and harder to interpret for humans and code analysis tools alike. The only reason <code>WP_Query</code> is capable of interpreting string arguments to begin with is out of necessity for parsing URLs.</li>\n<li>Query arguments as a string require <code>WP_Query</code> to perform a tiny amount of additional work to convert them back into usable data.</li>\n</ul>\n<p>In my subjective opinion, without describing why it might implement the function in the manner which it has, the book's example <em>should</em> be implemented with an associative array instead:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function page_is_parent(){\n global $post;\n\n $pages = get_pages(\n [\n 'child_of' => $post->ID,\n ]\n );\n\n return count( $pages ); \n}\n</code></pre>\n<hr />\n<h2>Additional Critique</h2>\n<p>I would go further to critique a few other points of that function.</p>\n<ul>\n<li>I feel it is named inappropriately - the name the author has given to the function does not describe what it does. The function returns the number of pages which the current Page is a parent to. It can be used for the purpose implied by the author's chosen name in that it will return a "truthy" value if the current page is a parent to one or more pages and a "falsey" <code>0</code> if it is not. But the name does not actually describe what the function actually does which can lead to misuse. <code>if( page_is_parent() > 1 )</code> hardly makes sense to anyone but the person who wrote the function.</li>\n<li>Whenever possible, it is best to avoid directly accessing WordPress's global values in order to avoid circumventing filtration and sanitization logic which might otherwise be provided by accessor APIs. Instead of <code>global $post</code>, we have a convenient substitute in the form of <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow noreferrer\"><code>get_post()</code></a> which will access the same global if necessary.</li>\n</ul>\n<p>The above in mind, I personally would implement the proposed function as follows:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function get_child_page_count() {\n $post = get_post();\n\n $child_pages = get_pages(\n [\n 'child_of' => $post->ID,\n ]\n );\n\n return count( $child_pages );\n}\n</code></pre>\n<p>You can read <code>if( get_child_page_count() > 1 )</code> and know exactly what's going on a whole lot better than <code>if( page_is_parent() > 1)</code> - that's super-nice, isn't it?</p>\n<hr />\n<h2>An Advanced Form</h2>\n<p>The book may well get into this at some point, but for the purposes of counting the number of child pages, the provided query is inefficient. <code>get_pages()</code> retrieves the full data for every child page when all the function cares about is how many there are.</p>\n<p><code>WP_Query</code> provides a mechanism which <code>get_pages()</code> does not - the ability to only ask for certain columns instead of full rows via <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter\" rel=\"nofollow noreferrer\">the <code>fields</code> parameter</a>. Further, the <code>WP_Query</code> object provides <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#properties\" rel=\"nofollow noreferrer\">a <code>found_posts</code> property</a> detailing how many posts matched the query in total even if they were not returned "on the current page." So ultimately, we can ask for a single matching page's ID but still retrieve the total number of matching pages. This should speed things up a wee bit - not enough to matter when you're only dealing with a moderate number of child pages, but it can definitely make a difference when you're working with <em>a lot</em> of pages.</p>\n<p>As a final point of critique, we can expand the function such that not only will it consider the current post when utilized within The Loop, but we can also pass an argument to have it calculate the number of child Pages for a specific Page/Page ID.</p>\n<p>All together, I would implement the function as follows:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function get_child_page_count( $page = null ) {\n // Retrieve the post object specified by the $page argument, or from\n // the global $post if the argument is omitted.\n $post = get_post( $page );\n\n $query = new WP_Query(\n [\n 'post_type' => 'page', // Query for pages...\n 'post_parent' => $post->ID, // ...which have a parent of the page passed as an argument (or the current page if omitted)...\n 'fields' => 'ids', // ...and only retrieve their IDs...\n 'posts_per_page' => 1, // ...but only retrieve 1 from the database.\n ]\n );\n\n return $query->found_posts; // Return the total number of matching posts.\n}\n</code></pre>\n<p>Of course, you could also write that query as</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query( 'post_type=page&post_parent=' . $post->ID . '&fields=ids&posts_per_page=1' );\n</code></pre>\n<p>...but that's utter nonsense, in my book ;)</p>\n"
}
] | 2022/07/17 | [
"https://wordpress.stackexchange.com/questions/407741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/224123/"
] | I am reading a book called "Learn to Create WordPress Themes by Building 5 Projects" . In that to retrieve the parent for pages, they have a function to get the parent of the pages. The function is as follows,
```
function page_is_parent(){
global $post;
$pages = get_pages('child_of='.$post->ID);
return count($pages);
}
```
Explanation given in the book is as follows,
>
> Now we just have About. We can navigate using the menu here. However, if we go to Sample Page or any other page, it's going to still have this even though there's no child links. So, we'll create another short function in the `functions.php` file and call `page_is_parent`. Then, we'll say global `$post` and set `$pages` equal to `get_pages()`, and in here, we'll say `'child_of='` and concatenate the post ID. Next, we'll say return and then, we want the number of pages, so we'll `count($pages)`:
>
>
>
But I feel the `$pages = get_pages('child_of='.$post->ID);` is weird since they pass a string `'child_of='.$post->ID` Please explain why a string is passed and why it is concatenated. | It is concatenated because that's how we [combine strings together in PHP](https://www.php.net/manual/en/language.operators.string.php), and string is passed because arguments **can be passed as a query string or an array of `key => value` pairs**.
See the [`get_pages()` documentation](https://developer.wordpress.org/reference/functions/get_pages/) for more details.
```php
// So both of these will work:
// 1. Pass string of arguments.
$pages = get_pages( 'child_of=' . $post->ID );
// 2. Pass array of arguments.
$pages = get_pages( array(
'child_of' => $post->ID,
) );
```
So if I had to give you a reason why would I use the former (the first one in the above example), then it'd be: because it actually works and simpler in the case of the argument in question.
And one could also use double quotes instead, e.g. `"child_of={$post->ID}"`, but if you need explanation on that, you should ask on Stack Overflow :) |
407,748 | <p>I'm starting to develop Gutenberg blocks. After</p>
<pre><code>npx @wordpress/create-block gutenpride
</code></pre>
<p>I have my gutenpride block ready to use. Since the generated plugin contains a structure for only one block I wonder what changes should I make to add another similar block in the same plugin.</p>
<p>So, for the default structure in the gutenpride plugin, what changes should I make to add another block? Thank you.</p>
<p><strong>UPDATE: I've discovered that I can find answers on this topic searching for "multi block plugin" (I couldn't find anything before). <a href="https://wordpress.stackexchange.com/questions/390282/possible-to-use-wordpress-create-block-with-multiple-blocks/390838#390838">This question for example</a>. So, this question could be a possible duplicated. I'm still researching.</strong></p>
| [
{
"answer_id": 407752,
"author": "aitor",
"author_id": 77722,
"author_profile": "https://wordpress.stackexchange.com/users/77722",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li>Add a subfolder in <code>your-plugin/src</code> with the block name</li>\n<li>Put all <code>src</code> files inside this folder</li>\n<li>Repeat 1 and 2 for other blocks that you want to add.</li>\n</ol>\n<p>At this moment, the <code>src</code> folder looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/zgqDZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zgqDZ.png\" alt=\"enter image description here\" /></a></p>\n<p>Be careful to edit properly each block.json to give them a name, etc.</p>\n<ol start=\"4\">\n<li>replace de single block registration to multiblock in <code>your-plugin.php</code> file</li>\n</ol>\n<pre><code>function create_block_your_plugin_block_init() {\n register_block_type( __DIR__ . '/build/block-1' );\n register_block_type( __DIR__ . '/build/block-2' );\n}\nadd_action( 'init', 'create_block_your_plugin_block_init' );\n</code></pre>\n<ol start=\"5\">\n<li>Optionally, you can rename <code>src</code> folder to any name you like, for example, <code>blocks</code>. In that case, add <code>--webpack-src-dir=blocks</code> flag with the new name to <code>package.json</code> start script:</li>\n</ol>\n<pre><code>"scripts": {\n "build": "wp-scripts build",\n "format": "wp-scripts format",\n "lint:css": "wp-scripts lint-style",\n "lint:js": "wp-scripts lint-js",\n "packages-update": "wp-scripts packages-update",\n "plugin-zip": "wp-scripts plugin-zip",\n "start": "wp-scripts start --webpack-src-dir=blocks"\n},\n</code></pre>\n<ol start=\"6\">\n<li>run npm start to build <code>build</code> folder</li>\n</ol>\n<p>That's all.</p>\n"
},
{
"answer_id": 413534,
"author": "user2088350",
"author_id": 118537,
"author_profile": "https://wordpress.stackexchange.com/users/118537",
"pm_score": 0,
"selected": false,
"text": "<p>I think the first answer is easy to follow. It's pretty simple, but I needed some time to make all changes correctly.</p>\n<p>I began by copying all code for each block from ./src to a /blocks/block-1 and /blocks/block-2 directory.</p>\n<p>Modified the <strong>plugin_name.php</strong> file and the <strong>package.json</strong> in the plugin directory.</p>\n<p>Changed names in block.json to reflect the name as plugin_name/block-1 and plugin_name/block-2.\nFor styles wp-block-plugin-name-block-1 and wp-block-plugin-name-block-2 in styles in <strong>edit.js, save.js and editor.scss and styles.scss.</strong> for each block.</p>\n<p>In the plugin_name.php file <strong>include for each block</strong> inside an action 'init', this makes the blocks appear in the block directory:</p>\n<pre><code>function plugin_name_block_init()\n{\nregister_block_type( __DIR__ . '/build/block-1' );\nregister_block_type( __DIR__ . '/build/block-2' );\n}\nadd_action( 'init','plugin_name_block_init');\n</code></pre>\n<p>The <strong>package.json</strong> modified to start or build all blocks. So from now the scripts look for each block.json and index.js inside block directories placed inside directory 'blocks'. Inside the 'scripts':</p>\n<pre><code>"build": "wp-scripts build --webpack-src-dir=blocks",\n"start": "wp-scripts start --webpack-src-dir=blocks",\n</code></pre>\n<p>And last, I made changes to styles names to each file editor.scss and editor.scss, and also edit.js and save.js for each block.</p>\n<p>Now it works for me development (npm start) or build (npm run build). Modifies both blocks at the same time.</p>\n<p>I think it can be modified to only build a block each time:</p>\n<pre><code>"start:block-1": "wp-scripts start --webpack-src-dir=blocks/block-1",\n</code></pre>\n<p>Works if you call it: <strong>npm run start:block-1</strong> (not npm start:block-1)</p>\n"
}
] | 2022/07/17 | [
"https://wordpress.stackexchange.com/questions/407748",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77722/"
] | I'm starting to develop Gutenberg blocks. After
```
npx @wordpress/create-block gutenpride
```
I have my gutenpride block ready to use. Since the generated plugin contains a structure for only one block I wonder what changes should I make to add another similar block in the same plugin.
So, for the default structure in the gutenpride plugin, what changes should I make to add another block? Thank you.
**UPDATE: I've discovered that I can find answers on this topic searching for "multi block plugin" (I couldn't find anything before). [This question for example](https://wordpress.stackexchange.com/questions/390282/possible-to-use-wordpress-create-block-with-multiple-blocks/390838#390838). So, this question could be a possible duplicated. I'm still researching.** | 1. Add a subfolder in `your-plugin/src` with the block name
2. Put all `src` files inside this folder
3. Repeat 1 and 2 for other blocks that you want to add.
At this moment, the `src` folder looks like this:
[](https://i.stack.imgur.com/zgqDZ.png)
Be careful to edit properly each block.json to give them a name, etc.
4. replace de single block registration to multiblock in `your-plugin.php` file
```
function create_block_your_plugin_block_init() {
register_block_type( __DIR__ . '/build/block-1' );
register_block_type( __DIR__ . '/build/block-2' );
}
add_action( 'init', 'create_block_your_plugin_block_init' );
```
5. Optionally, you can rename `src` folder to any name you like, for example, `blocks`. In that case, add `--webpack-src-dir=blocks` flag with the new name to `package.json` start script:
```
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start --webpack-src-dir=blocks"
},
```
6. run npm start to build `build` folder
That's all. |
407,759 | <p>Looking to <code>ORDER BY</code> the result of <a href="https://developer.wordpress.org/reference/classes/wp_query/" rel="nofollow noreferrer">WP_Query</a> based on presence of post thumbnail.</p>
<pre><code> $query_args = [
'post_type' => 'custom_project',
'post_status' => 'publish',
'posts_per_page' => 20,
'orderby' => array( 'meta_value_num' => 'DESC' ),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
),
array(
'key' => '_thumbnail_id',
'value' => "whatever",
'compare' => 'NOT EXISTS'
)
),
'paged' => false,
'orderby' => 'title'
];
</code></pre>
<p>Producing:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN \
wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN \
wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id AND mt1.meta_key \
= '_thumbnail_id' ) WHERE 1=1 AND (
wp_postmeta.meta_key = '_thumbnail_id'
OR
mt1.post_id IS NULL
) AND wp_posts.post_type = 'custom_project' \
AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY \
wp_posts.post_title DESC LIMIT 0, 20
</code></pre>
<p>If I add <code>'meta_key' => '_thumbnail_id'</code>, this only returns posts that contain a featured image. Otherwise, no sorting. I have unsuccessfully tried variations with with <code>compare</code> values and including <code>'_thumbnail_id'</code> in a second tax query array and am considering just using <code>array_sort</code> after the fact, but hoping for a more elegant solution.</p>
<p>Have tried two different solutions from <a href="https://wordpress.stackexchange.com/a/219031/48604">this post</a>, but unsuccessful using <code>wp 5.8.1</code>.</p>
<h4>Desired Result:</h4>
<ol>
<li>I have a thumbnail</li>
<li>I have a thumbnail</li>
<li>I have a thumbnail</li>
<li>I have a thumbnail</li>
<li>I don't have a thumbnail</li>
<li>I don't have a thumbnail</li>
</ol>
| [
{
"answer_id": 407752,
"author": "aitor",
"author_id": 77722,
"author_profile": "https://wordpress.stackexchange.com/users/77722",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li>Add a subfolder in <code>your-plugin/src</code> with the block name</li>\n<li>Put all <code>src</code> files inside this folder</li>\n<li>Repeat 1 and 2 for other blocks that you want to add.</li>\n</ol>\n<p>At this moment, the <code>src</code> folder looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/zgqDZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zgqDZ.png\" alt=\"enter image description here\" /></a></p>\n<p>Be careful to edit properly each block.json to give them a name, etc.</p>\n<ol start=\"4\">\n<li>replace de single block registration to multiblock in <code>your-plugin.php</code> file</li>\n</ol>\n<pre><code>function create_block_your_plugin_block_init() {\n register_block_type( __DIR__ . '/build/block-1' );\n register_block_type( __DIR__ . '/build/block-2' );\n}\nadd_action( 'init', 'create_block_your_plugin_block_init' );\n</code></pre>\n<ol start=\"5\">\n<li>Optionally, you can rename <code>src</code> folder to any name you like, for example, <code>blocks</code>. In that case, add <code>--webpack-src-dir=blocks</code> flag with the new name to <code>package.json</code> start script:</li>\n</ol>\n<pre><code>"scripts": {\n "build": "wp-scripts build",\n "format": "wp-scripts format",\n "lint:css": "wp-scripts lint-style",\n "lint:js": "wp-scripts lint-js",\n "packages-update": "wp-scripts packages-update",\n "plugin-zip": "wp-scripts plugin-zip",\n "start": "wp-scripts start --webpack-src-dir=blocks"\n},\n</code></pre>\n<ol start=\"6\">\n<li>run npm start to build <code>build</code> folder</li>\n</ol>\n<p>That's all.</p>\n"
},
{
"answer_id": 413534,
"author": "user2088350",
"author_id": 118537,
"author_profile": "https://wordpress.stackexchange.com/users/118537",
"pm_score": 0,
"selected": false,
"text": "<p>I think the first answer is easy to follow. It's pretty simple, but I needed some time to make all changes correctly.</p>\n<p>I began by copying all code for each block from ./src to a /blocks/block-1 and /blocks/block-2 directory.</p>\n<p>Modified the <strong>plugin_name.php</strong> file and the <strong>package.json</strong> in the plugin directory.</p>\n<p>Changed names in block.json to reflect the name as plugin_name/block-1 and plugin_name/block-2.\nFor styles wp-block-plugin-name-block-1 and wp-block-plugin-name-block-2 in styles in <strong>edit.js, save.js and editor.scss and styles.scss.</strong> for each block.</p>\n<p>In the plugin_name.php file <strong>include for each block</strong> inside an action 'init', this makes the blocks appear in the block directory:</p>\n<pre><code>function plugin_name_block_init()\n{\nregister_block_type( __DIR__ . '/build/block-1' );\nregister_block_type( __DIR__ . '/build/block-2' );\n}\nadd_action( 'init','plugin_name_block_init');\n</code></pre>\n<p>The <strong>package.json</strong> modified to start or build all blocks. So from now the scripts look for each block.json and index.js inside block directories placed inside directory 'blocks'. Inside the 'scripts':</p>\n<pre><code>"build": "wp-scripts build --webpack-src-dir=blocks",\n"start": "wp-scripts start --webpack-src-dir=blocks",\n</code></pre>\n<p>And last, I made changes to styles names to each file editor.scss and editor.scss, and also edit.js and save.js for each block.</p>\n<p>Now it works for me development (npm start) or build (npm run build). Modifies both blocks at the same time.</p>\n<p>I think it can be modified to only build a block each time:</p>\n<pre><code>"start:block-1": "wp-scripts start --webpack-src-dir=blocks/block-1",\n</code></pre>\n<p>Works if you call it: <strong>npm run start:block-1</strong> (not npm start:block-1)</p>\n"
}
] | 2022/07/17 | [
"https://wordpress.stackexchange.com/questions/407759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48604/"
] | Looking to `ORDER BY` the result of [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/) based on presence of post thumbnail.
```
$query_args = [
'post_type' => 'custom_project',
'post_status' => 'publish',
'posts_per_page' => 20,
'orderby' => array( 'meta_value_num' => 'DESC' ),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
),
array(
'key' => '_thumbnail_id',
'value' => "whatever",
'compare' => 'NOT EXISTS'
)
),
'paged' => false,
'orderby' => 'title'
];
```
Producing:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN \
wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN \
wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id AND mt1.meta_key \
= '_thumbnail_id' ) WHERE 1=1 AND (
wp_postmeta.meta_key = '_thumbnail_id'
OR
mt1.post_id IS NULL
) AND wp_posts.post_type = 'custom_project' \
AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY \
wp_posts.post_title DESC LIMIT 0, 20
```
If I add `'meta_key' => '_thumbnail_id'`, this only returns posts that contain a featured image. Otherwise, no sorting. I have unsuccessfully tried variations with with `compare` values and including `'_thumbnail_id'` in a second tax query array and am considering just using `array_sort` after the fact, but hoping for a more elegant solution.
Have tried two different solutions from [this post](https://wordpress.stackexchange.com/a/219031/48604), but unsuccessful using `wp 5.8.1`.
#### Desired Result:
1. I have a thumbnail
2. I have a thumbnail
3. I have a thumbnail
4. I have a thumbnail
5. I don't have a thumbnail
6. I don't have a thumbnail | 1. Add a subfolder in `your-plugin/src` with the block name
2. Put all `src` files inside this folder
3. Repeat 1 and 2 for other blocks that you want to add.
At this moment, the `src` folder looks like this:
[](https://i.stack.imgur.com/zgqDZ.png)
Be careful to edit properly each block.json to give them a name, etc.
4. replace de single block registration to multiblock in `your-plugin.php` file
```
function create_block_your_plugin_block_init() {
register_block_type( __DIR__ . '/build/block-1' );
register_block_type( __DIR__ . '/build/block-2' );
}
add_action( 'init', 'create_block_your_plugin_block_init' );
```
5. Optionally, you can rename `src` folder to any name you like, for example, `blocks`. In that case, add `--webpack-src-dir=blocks` flag with the new name to `package.json` start script:
```
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start --webpack-src-dir=blocks"
},
```
6. run npm start to build `build` folder
That's all. |
407,784 | <p>How to Pass ID and fetch post meta data through Short Code like <code>[my-shortcode id="12"]</code> ?</p>
<p>My code is like below.</p>
<pre><code>add_shortcode( 'my-shortcode', 'shortcode_function' );
function shortcode_function( $id ) {
//I would like to get $id value 12 here
return $id;
}
</code></pre>
| [
{
"answer_id": 407785,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the ID by extracting the shortcode attributes. Check out the example below:</p>\n<pre><code>function shortcode_function($atts) {\n extract(shortcode_atts(array('id' => ''), $atts));\n return $id;\n}\nadd_shortcode('my-shortcode', 'shortcode_function');\n</code></pre>\n<p>In this example you set a fallback ID of empty string. You can also set it to <code>false</code> if you want. In the array within <code>shortcode_atts</code> you can define multiple attributes and handle them as you please.</p>\n"
},
{
"answer_id": 407787,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Your short code function receives the attributes as the first argument:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( $attributes ) {\n</code></pre>\n<p>Here <code>$attributes</code> is an array, and the attributes/values are inside that variable,</p>\n<p>e.g. for <code>[my-shortcode abc="123" xyz="789"]</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo $attributes['abc']; // prints 123\necho $attributes['xyz']; // prints 789\n</code></pre>\n<p>You should also provide defaults and an opportunity to filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$attributes = shortcode_atts( [\n 'id' => '',\n], $attributes );\n</code></pre>\n<p>This way if the <code>id</code> is missing you don't get PHP warnings, e.g. if we wrote <code>[my-shortcode]</code> by accident.</p>\n<h2>Improving The Shortcode</h2>\n<p>First, lets add type hints. This will avoid a common pitfall/bug that people fall into:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n</code></pre>\n<p>Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.</p>\n<p>This give us:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n // get the attributes\n $attributes = shortcode_atts( [\n 'id' => 'default ID value goes here',\n ], $attributes );\n $id = $attributes['id'];\n\n // generate the shortcode's content:\n return 'My ID is:' . $id;\n}\nadd_shortcode( 'my-shortcode', 'shortcode_function' );\n</code></pre>\n"
}
] | 2022/07/18 | [
"https://wordpress.stackexchange.com/questions/407784",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65189/"
] | How to Pass ID and fetch post meta data through Short Code like `[my-shortcode id="12"]` ?
My code is like below.
```
add_shortcode( 'my-shortcode', 'shortcode_function' );
function shortcode_function( $id ) {
//I would like to get $id value 12 here
return $id;
}
``` | Your short code function receives the attributes as the first argument:
```php
function shortcode_function( $attributes ) {
```
Here `$attributes` is an array, and the attributes/values are inside that variable,
e.g. for `[my-shortcode abc="123" xyz="789"]`:
```php
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
```
You should also provide defaults and an opportunity to filter:
```php
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
```
This way if the `id` is missing you don't get PHP warnings, e.g. if we wrote `[my-shortcode]` by accident.
Improving The Shortcode
-----------------------
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
```php
function shortcode_function( array $attributes ) : string {
```
Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
```php
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );
``` |
407,826 | <p>I'm developing a custom Gutenberg block and would like to use the same JavaScript code on frontend and backend.</p>
<p>In the save function of the block I generate the following html code (abridged):</p>
<pre><code>return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
</code></pre>
<p>The frontend code reads the data attribute and creates the tbody element with 50 rows that are fetched from an API via fetch(), like so:</p>
<pre><code>const tables = document.querySelectorAll('.my-plugin-table')
tables.forEach(table => {
const tbody = document.createElement('tbody')
table.appendChild(tbody)
const rows = table.dataset.row
const apiURL = 'https://xxxxxxx?rows=' + rows
fetch(apiRUL)
.then(response => response.json())
.then(data => {
const trs = []
data.elements.forEach(element => {
const tr = document.createElement('tr')
const td1 = document.createElement('td')
const td2 = document.createElement('td')
td1.innerHTML = element.key
td2.innerHTML = element.label
tr.replaceChildren(td1, td2)
trs.push(tr)
})
tbody.replaceChildren(trs)
})
})
</code></pre>
<p>In the edit function of the block I use the identical html code:</p>
<pre><code>return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
</code></pre>
<p>What is the best practice here to use the frontend JavaScript in the backend as well? I need to access the dom element inside the editor. I tried it with <code>wp.data.select( 'core/block-editor' ).getBlocks()</code> but to no avail.</p>
<p>Can you maybe give me a hint what would be the best solution in the Gutenberg and WordPress way?</p>
| [
{
"answer_id": 407785,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the ID by extracting the shortcode attributes. Check out the example below:</p>\n<pre><code>function shortcode_function($atts) {\n extract(shortcode_atts(array('id' => ''), $atts));\n return $id;\n}\nadd_shortcode('my-shortcode', 'shortcode_function');\n</code></pre>\n<p>In this example you set a fallback ID of empty string. You can also set it to <code>false</code> if you want. In the array within <code>shortcode_atts</code> you can define multiple attributes and handle them as you please.</p>\n"
},
{
"answer_id": 407787,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Your short code function receives the attributes as the first argument:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( $attributes ) {\n</code></pre>\n<p>Here <code>$attributes</code> is an array, and the attributes/values are inside that variable,</p>\n<p>e.g. for <code>[my-shortcode abc="123" xyz="789"]</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo $attributes['abc']; // prints 123\necho $attributes['xyz']; // prints 789\n</code></pre>\n<p>You should also provide defaults and an opportunity to filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$attributes = shortcode_atts( [\n 'id' => '',\n], $attributes );\n</code></pre>\n<p>This way if the <code>id</code> is missing you don't get PHP warnings, e.g. if we wrote <code>[my-shortcode]</code> by accident.</p>\n<h2>Improving The Shortcode</h2>\n<p>First, lets add type hints. This will avoid a common pitfall/bug that people fall into:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n</code></pre>\n<p>Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.</p>\n<p>This give us:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n // get the attributes\n $attributes = shortcode_atts( [\n 'id' => 'default ID value goes here',\n ], $attributes );\n $id = $attributes['id'];\n\n // generate the shortcode's content:\n return 'My ID is:' . $id;\n}\nadd_shortcode( 'my-shortcode', 'shortcode_function' );\n</code></pre>\n"
}
] | 2022/07/19 | [
"https://wordpress.stackexchange.com/questions/407826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107117/"
] | I'm developing a custom Gutenberg block and would like to use the same JavaScript code on frontend and backend.
In the save function of the block I generate the following html code (abridged):
```
return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
```
The frontend code reads the data attribute and creates the tbody element with 50 rows that are fetched from an API via fetch(), like so:
```
const tables = document.querySelectorAll('.my-plugin-table')
tables.forEach(table => {
const tbody = document.createElement('tbody')
table.appendChild(tbody)
const rows = table.dataset.row
const apiURL = 'https://xxxxxxx?rows=' + rows
fetch(apiRUL)
.then(response => response.json())
.then(data => {
const trs = []
data.elements.forEach(element => {
const tr = document.createElement('tr')
const td1 = document.createElement('td')
const td2 = document.createElement('td')
td1.innerHTML = element.key
td2.innerHTML = element.label
tr.replaceChildren(td1, td2)
trs.push(tr)
})
tbody.replaceChildren(trs)
})
})
```
In the edit function of the block I use the identical html code:
```
return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
```
What is the best practice here to use the frontend JavaScript in the backend as well? I need to access the dom element inside the editor. I tried it with `wp.data.select( 'core/block-editor' ).getBlocks()` but to no avail.
Can you maybe give me a hint what would be the best solution in the Gutenberg and WordPress way? | Your short code function receives the attributes as the first argument:
```php
function shortcode_function( $attributes ) {
```
Here `$attributes` is an array, and the attributes/values are inside that variable,
e.g. for `[my-shortcode abc="123" xyz="789"]`:
```php
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
```
You should also provide defaults and an opportunity to filter:
```php
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
```
This way if the `id` is missing you don't get PHP warnings, e.g. if we wrote `[my-shortcode]` by accident.
Improving The Shortcode
-----------------------
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
```php
function shortcode_function( array $attributes ) : string {
```
Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
```php
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );
``` |
407,877 | <p>I'm looking to set a cookie for one of my WordPress applications. Despite my research, I can't find why WordPress ignores the creation of the cookie.
Here is my code place in my app.
What do you think of my code? do they have errors?
wordpress 6.0.1
php 8.0
<a href="https://lysto.fr/tools/?categorie=461" rel="nofollow noreferrer">https://lysto.fr/tools/?categorie=461</a> (ajouter un article pour declancher la creation du cookie)</p>
<p>Bonjour
Je cherche à définir un cookie pour une de mes applications WordPress. Malgré mes recherches, je ne trouve pas pourquoi WordPress ignore la création du cookie.
Voici mon code placer dans mon application.
Que pensez-vous de mon code ? comporte t'ils des erreurs ?
wordpress 6.0.1
php 8.0
<a href="https://lysto.fr/tools/?categorie=461" rel="nofollow noreferrer">https://lysto.fr/tools/?categorie=461</a> (add an article to trigger the creation of the cookie)</p>
<pre><code>if (!isset ($_COOKIE['panier'])){
function cookie_panier() {
$cookie_user_id = uniqid();
setcookie( 'panier', $cookie_user_id, time()+60*60*24*12 );
}
add_action('init', 'cookie_panier');
}
</code></pre>
<p>The site generates errors that are linked in the absence of this cookie
Line 27 retrieves the value of the 'cart' cookie. The cookie does not exist, the browser displays me;</p>
<blockquote>
<p>Warning: Undefined variable $panier_value in
/homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/inc_data_panier.php
on line 27</p>
</blockquote>
<p>Do you think the following error can prevent the cookie from being created?</p>
<blockquote>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php:17)
in
/homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php
on line 7</p>
</blockquote>
<p>Le site génère des erreurs qui sont lier en l’absence de ce cookie
La ligne 27 récupère la valeur du cookie ‘panier’. Le cookie n’existant pas, le navigateur m’affiche ;
Warning: Undefined variable $panier_value in /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/inc_data_panier.php on line 27</p>
<p>Pensez-vous que l’erreur suivante peut empêcher le cookie de ce créé ?</p>
<p>Warning: Cannot modify header information - headers already sent by (output started at /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php:17) in /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php on line 7</p>
<p>Here is the code of this file 'inc_data_panier.php'</p>
<pre><code><?php
function data_panier(){
global $wpdb ;
$result=$wpdb->get_results("SELECT user_item_id, position, item_id, item_q, item_name, item_price FROM {$wpdb->prefix}gc_panier where user_id = '".$_COOKIE['panier']."'ORDER BY position" ) ;
foreach ($result as $row) {
$user_item_id=$row->user_item_id;
$position=$row->position;
$panier_item_id=$row->item_id;
$panier_item_q=$row->item_q;
$panier_item_name=$row->item_name;
$panier_item_price=$row->item_price;
$panier_value[$panier_item_id]['user_item_id']=$user_item_id;
$panier_value[$panier_item_id]['position']=$position;
$panier_value[$panier_item_id]['id']=$panier_item_id;
$panier_value[$panier_item_id]['q']=$panier_item_q;
$panier_value[$panier_item_id]['name']=$panier_item_name;
$panier_value[$panier_item_id]['price']=$panier_item_price;
$result_item_ref_builder=$wpdb->get_results("SELECT item_ref_builder FROM {$wpdb->prefix}gc_articles where item_id LIKE '".$panier_item_id."%'") ;
foreach ($result_item_ref_builder as $row) {
$item_ref_builder=$row->item_ref_builder;
$panier_value[$panier_item_id]['item_ref_builder']=$item_ref_builder;
// $art[$item_id]['feature_sub_cathegorie_name'] =$item_ref_builder;
}
}
return $panier_value;
}
$panier_value=data_panier();
?>
</code></pre>
<p>Here is the code of this file 'panierBddCookie.php'</p>
<pre><code><?php
if (!isset ($_COOKIE['panier'])){
function cookie_panier() {
$cookie_user_id = uniqid();
setcookie( 'panier', $cookie_user_id, time() + DAY_IN_SECONDS, '/');
echo "</br>Le cookie panier n'esiste pas</br>la valeur du cookie devrait être ".$cookie_user_id."</br>";
}
add_action('init', 'cookie_panier');
}
if (isset($_POST['valid'])){
$q=$_POST['quantite'];
$item_id_panier=$_POST['item_id_panier'];
$item_name_panier=$_POST['item_name_panier'];
$item_price_panier=$_POST['item_price_panier'];
$cookie_user_id=$_COOKIE['panier'];
$user_item_id_panier = $cookie_user_id.$item_id_panier;
require('inc_data_panier.php');
// si l'utlisateur est present dans la table panier
if(isset($panier_value)){
foreach($panier_value as $id => $value){
// $position=$row->item_q;
$position[]=$panier_value[$id]['position'];
}
$der_position=max($position)+1;
foreach($panier_value as $id => $value){
// echo $panier_value[$id]['name'];
if($user_item_id_panier == $panier_value[$id]['user_item_id'])
{
$new_quantite = $q+$panier_value[$id]['q'];
$wpdb -> update ( $wpdb->prefix.'gc_panier',
array ( 'item_q' => $new_quantite ),
array ( 'user_item_id' => $panier_value[$id]['user_item_id'] ),
array ( '% d' )
);
}
else{
// entrée dans la base de donne du panier si l'article n'a pas été ajouter au panier lors de la creation du cookie
$wpdb->insert($wpdb->prefix.'gc_panier',
array(
'user_item_id' => $user_item_id_panier,
'position' => $der_position,
'user_id' => $cookie_user_id,
'item_id' => $item_id_panier,
'item_q' => $q,
'item_name' => $item_name_panier,
'item_price' => $item_price_panier
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
}
// le panier est vide , 1er entre dans la table avec cette utilisateur
else{
$wpdb->insert($wpdb->prefix.'gc_panier',
array(
'user_item_id' => $user_item_id_panier,
'position' => 1,
'user_id' => $cookie_user_id,
'item_id' => $item_id_panier,
'item_q' => $q,
'item_name' => $item_name_panier,
'item_price' => $item_price_panier
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
// ?>
</code></pre>
| [
{
"answer_id": 407785,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the ID by extracting the shortcode attributes. Check out the example below:</p>\n<pre><code>function shortcode_function($atts) {\n extract(shortcode_atts(array('id' => ''), $atts));\n return $id;\n}\nadd_shortcode('my-shortcode', 'shortcode_function');\n</code></pre>\n<p>In this example you set a fallback ID of empty string. You can also set it to <code>false</code> if you want. In the array within <code>shortcode_atts</code> you can define multiple attributes and handle them as you please.</p>\n"
},
{
"answer_id": 407787,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Your short code function receives the attributes as the first argument:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( $attributes ) {\n</code></pre>\n<p>Here <code>$attributes</code> is an array, and the attributes/values are inside that variable,</p>\n<p>e.g. for <code>[my-shortcode abc="123" xyz="789"]</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo $attributes['abc']; // prints 123\necho $attributes['xyz']; // prints 789\n</code></pre>\n<p>You should also provide defaults and an opportunity to filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$attributes = shortcode_atts( [\n 'id' => '',\n], $attributes );\n</code></pre>\n<p>This way if the <code>id</code> is missing you don't get PHP warnings, e.g. if we wrote <code>[my-shortcode]</code> by accident.</p>\n<h2>Improving The Shortcode</h2>\n<p>First, lets add type hints. This will avoid a common pitfall/bug that people fall into:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n</code></pre>\n<p>Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.</p>\n<p>This give us:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n // get the attributes\n $attributes = shortcode_atts( [\n 'id' => 'default ID value goes here',\n ], $attributes );\n $id = $attributes['id'];\n\n // generate the shortcode's content:\n return 'My ID is:' . $id;\n}\nadd_shortcode( 'my-shortcode', 'shortcode_function' );\n</code></pre>\n"
}
] | 2022/07/21 | [
"https://wordpress.stackexchange.com/questions/407877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/222956/"
] | I'm looking to set a cookie for one of my WordPress applications. Despite my research, I can't find why WordPress ignores the creation of the cookie.
Here is my code place in my app.
What do you think of my code? do they have errors?
wordpress 6.0.1
php 8.0
<https://lysto.fr/tools/?categorie=461> (ajouter un article pour declancher la creation du cookie)
Bonjour
Je cherche à définir un cookie pour une de mes applications WordPress. Malgré mes recherches, je ne trouve pas pourquoi WordPress ignore la création du cookie.
Voici mon code placer dans mon application.
Que pensez-vous de mon code ? comporte t'ils des erreurs ?
wordpress 6.0.1
php 8.0
<https://lysto.fr/tools/?categorie=461> (add an article to trigger the creation of the cookie)
```
if (!isset ($_COOKIE['panier'])){
function cookie_panier() {
$cookie_user_id = uniqid();
setcookie( 'panier', $cookie_user_id, time()+60*60*24*12 );
}
add_action('init', 'cookie_panier');
}
```
The site generates errors that are linked in the absence of this cookie
Line 27 retrieves the value of the 'cart' cookie. The cookie does not exist, the browser displays me;
>
> Warning: Undefined variable $panier\_value in
> /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/inc\_data\_panier.php
> on line 27
>
>
>
Do you think the following error can prevent the cookie from being created?
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php:17)
> in
> /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php
> on line 7
>
>
>
Le site génère des erreurs qui sont lier en l’absence de ce cookie
La ligne 27 récupère la valeur du cookie ‘panier’. Le cookie n’existant pas, le navigateur m’affiche ;
Warning: Undefined variable $panier\_value in /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/inc\_data\_panier.php on line 27
Pensez-vous que l’erreur suivante peut empêcher le cookie de ce créé ?
Warning: Cannot modify header information - headers already sent by (output started at /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php:17) in /homepages/44/d875690649/htdocs/tools/wp-content/plugins/catalogue/panierBddCookie.php on line 7
Here is the code of this file 'inc\_data\_panier.php'
```
<?php
function data_panier(){
global $wpdb ;
$result=$wpdb->get_results("SELECT user_item_id, position, item_id, item_q, item_name, item_price FROM {$wpdb->prefix}gc_panier where user_id = '".$_COOKIE['panier']."'ORDER BY position" ) ;
foreach ($result as $row) {
$user_item_id=$row->user_item_id;
$position=$row->position;
$panier_item_id=$row->item_id;
$panier_item_q=$row->item_q;
$panier_item_name=$row->item_name;
$panier_item_price=$row->item_price;
$panier_value[$panier_item_id]['user_item_id']=$user_item_id;
$panier_value[$panier_item_id]['position']=$position;
$panier_value[$panier_item_id]['id']=$panier_item_id;
$panier_value[$panier_item_id]['q']=$panier_item_q;
$panier_value[$panier_item_id]['name']=$panier_item_name;
$panier_value[$panier_item_id]['price']=$panier_item_price;
$result_item_ref_builder=$wpdb->get_results("SELECT item_ref_builder FROM {$wpdb->prefix}gc_articles where item_id LIKE '".$panier_item_id."%'") ;
foreach ($result_item_ref_builder as $row) {
$item_ref_builder=$row->item_ref_builder;
$panier_value[$panier_item_id]['item_ref_builder']=$item_ref_builder;
// $art[$item_id]['feature_sub_cathegorie_name'] =$item_ref_builder;
}
}
return $panier_value;
}
$panier_value=data_panier();
?>
```
Here is the code of this file 'panierBddCookie.php'
```
<?php
if (!isset ($_COOKIE['panier'])){
function cookie_panier() {
$cookie_user_id = uniqid();
setcookie( 'panier', $cookie_user_id, time() + DAY_IN_SECONDS, '/');
echo "</br>Le cookie panier n'esiste pas</br>la valeur du cookie devrait être ".$cookie_user_id."</br>";
}
add_action('init', 'cookie_panier');
}
if (isset($_POST['valid'])){
$q=$_POST['quantite'];
$item_id_panier=$_POST['item_id_panier'];
$item_name_panier=$_POST['item_name_panier'];
$item_price_panier=$_POST['item_price_panier'];
$cookie_user_id=$_COOKIE['panier'];
$user_item_id_panier = $cookie_user_id.$item_id_panier;
require('inc_data_panier.php');
// si l'utlisateur est present dans la table panier
if(isset($panier_value)){
foreach($panier_value as $id => $value){
// $position=$row->item_q;
$position[]=$panier_value[$id]['position'];
}
$der_position=max($position)+1;
foreach($panier_value as $id => $value){
// echo $panier_value[$id]['name'];
if($user_item_id_panier == $panier_value[$id]['user_item_id'])
{
$new_quantite = $q+$panier_value[$id]['q'];
$wpdb -> update ( $wpdb->prefix.'gc_panier',
array ( 'item_q' => $new_quantite ),
array ( 'user_item_id' => $panier_value[$id]['user_item_id'] ),
array ( '% d' )
);
}
else{
// entrée dans la base de donne du panier si l'article n'a pas été ajouter au panier lors de la creation du cookie
$wpdb->insert($wpdb->prefix.'gc_panier',
array(
'user_item_id' => $user_item_id_panier,
'position' => $der_position,
'user_id' => $cookie_user_id,
'item_id' => $item_id_panier,
'item_q' => $q,
'item_name' => $item_name_panier,
'item_price' => $item_price_panier
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
}
// le panier est vide , 1er entre dans la table avec cette utilisateur
else{
$wpdb->insert($wpdb->prefix.'gc_panier',
array(
'user_item_id' => $user_item_id_panier,
'position' => 1,
'user_id' => $cookie_user_id,
'item_id' => $item_id_panier,
'item_q' => $q,
'item_name' => $item_name_panier,
'item_price' => $item_price_panier
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
// ?>
``` | Your short code function receives the attributes as the first argument:
```php
function shortcode_function( $attributes ) {
```
Here `$attributes` is an array, and the attributes/values are inside that variable,
e.g. for `[my-shortcode abc="123" xyz="789"]`:
```php
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
```
You should also provide defaults and an opportunity to filter:
```php
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
```
This way if the `id` is missing you don't get PHP warnings, e.g. if we wrote `[my-shortcode]` by accident.
Improving The Shortcode
-----------------------
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
```php
function shortcode_function( array $attributes ) : string {
```
Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
```php
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );
``` |
407,955 | <p>I have one problem. I can't get the alt tag inside me repeater fields in ACF, I've tried multiple methods and nothing works for me, could you please help me? I can't fix this problem for a week :(
Something that I've tried and it should be working was this:</p>
<pre><code><?php while( have_rows('logo_list') ) : the_row();?>
<?php $image = get_sub_field('image'); ?>
<li><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"></li>
<?php endwhile;?>
</code></pre>
<p>And it went this result:
<a href="https://i.stack.imgur.com/4acNM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4acNM.png" alt="enter image description here" /></a>
What am I doing wrong?</p>
<p>The basic code was like this:</p>
<pre><code><?php while( have_rows('logo_list') ) : the_row();?>
<li><img src="<?php echo get_sub_field('image');?>" alt></li>
<?php endwhile;?>
</code></pre>
<p>Images format set as Array
Can you please help? I really don't know what to do :(</p>
<p>my fields
<a href="https://i.stack.imgur.com/47Iol.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/47Iol.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/JmjOw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JmjOw.png" alt="enter image description here" /></a></p>
<p>The results of output
<a href="https://i.stack.imgur.com/t9IZL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t9IZL.png" alt="enter image description here" /></a></p>
<p>FIELD SETTINGS
<a href="https://i.stack.imgur.com/QYFAc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QYFAc.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/BXwid.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BXwid.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/5Avl4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Avl4.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 407785,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the ID by extracting the shortcode attributes. Check out the example below:</p>\n<pre><code>function shortcode_function($atts) {\n extract(shortcode_atts(array('id' => ''), $atts));\n return $id;\n}\nadd_shortcode('my-shortcode', 'shortcode_function');\n</code></pre>\n<p>In this example you set a fallback ID of empty string. You can also set it to <code>false</code> if you want. In the array within <code>shortcode_atts</code> you can define multiple attributes and handle them as you please.</p>\n"
},
{
"answer_id": 407787,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Your short code function receives the attributes as the first argument:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( $attributes ) {\n</code></pre>\n<p>Here <code>$attributes</code> is an array, and the attributes/values are inside that variable,</p>\n<p>e.g. for <code>[my-shortcode abc="123" xyz="789"]</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo $attributes['abc']; // prints 123\necho $attributes['xyz']; // prints 789\n</code></pre>\n<p>You should also provide defaults and an opportunity to filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$attributes = shortcode_atts( [\n 'id' => '',\n], $attributes );\n</code></pre>\n<p>This way if the <code>id</code> is missing you don't get PHP warnings, e.g. if we wrote <code>[my-shortcode]</code> by accident.</p>\n<h2>Improving The Shortcode</h2>\n<p>First, lets add type hints. This will avoid a common pitfall/bug that people fall into:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n</code></pre>\n<p>Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.</p>\n<p>This give us:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n // get the attributes\n $attributes = shortcode_atts( [\n 'id' => 'default ID value goes here',\n ], $attributes );\n $id = $attributes['id'];\n\n // generate the shortcode's content:\n return 'My ID is:' . $id;\n}\nadd_shortcode( 'my-shortcode', 'shortcode_function' );\n</code></pre>\n"
}
] | 2022/07/24 | [
"https://wordpress.stackexchange.com/questions/407955",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/224338/"
] | I have one problem. I can't get the alt tag inside me repeater fields in ACF, I've tried multiple methods and nothing works for me, could you please help me? I can't fix this problem for a week :(
Something that I've tried and it should be working was this:
```
<?php while( have_rows('logo_list') ) : the_row();?>
<?php $image = get_sub_field('image'); ?>
<li><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"></li>
<?php endwhile;?>
```
And it went this result:
[](https://i.stack.imgur.com/4acNM.png)
What am I doing wrong?
The basic code was like this:
```
<?php while( have_rows('logo_list') ) : the_row();?>
<li><img src="<?php echo get_sub_field('image');?>" alt></li>
<?php endwhile;?>
```
Images format set as Array
Can you please help? I really don't know what to do :(
my fields
[](https://i.stack.imgur.com/47Iol.png)
[](https://i.stack.imgur.com/JmjOw.png)
The results of output
[](https://i.stack.imgur.com/t9IZL.png)
FIELD SETTINGS
[](https://i.stack.imgur.com/QYFAc.png)
[](https://i.stack.imgur.com/BXwid.png)
[](https://i.stack.imgur.com/5Avl4.png) | Your short code function receives the attributes as the first argument:
```php
function shortcode_function( $attributes ) {
```
Here `$attributes` is an array, and the attributes/values are inside that variable,
e.g. for `[my-shortcode abc="123" xyz="789"]`:
```php
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
```
You should also provide defaults and an opportunity to filter:
```php
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
```
This way if the `id` is missing you don't get PHP warnings, e.g. if we wrote `[my-shortcode]` by accident.
Improving The Shortcode
-----------------------
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
```php
function shortcode_function( array $attributes ) : string {
```
Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
```php
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );
``` |
407,995 | <p>I have a page where I want to add a custom class to all the images.</p>
<p>How to add this?</p>
<p>Thank you.</p>
| [
{
"answer_id": 407785,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the ID by extracting the shortcode attributes. Check out the example below:</p>\n<pre><code>function shortcode_function($atts) {\n extract(shortcode_atts(array('id' => ''), $atts));\n return $id;\n}\nadd_shortcode('my-shortcode', 'shortcode_function');\n</code></pre>\n<p>In this example you set a fallback ID of empty string. You can also set it to <code>false</code> if you want. In the array within <code>shortcode_atts</code> you can define multiple attributes and handle them as you please.</p>\n"
},
{
"answer_id": 407787,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Your short code function receives the attributes as the first argument:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( $attributes ) {\n</code></pre>\n<p>Here <code>$attributes</code> is an array, and the attributes/values are inside that variable,</p>\n<p>e.g. for <code>[my-shortcode abc="123" xyz="789"]</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo $attributes['abc']; // prints 123\necho $attributes['xyz']; // prints 789\n</code></pre>\n<p>You should also provide defaults and an opportunity to filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$attributes = shortcode_atts( [\n 'id' => '',\n], $attributes );\n</code></pre>\n<p>This way if the <code>id</code> is missing you don't get PHP warnings, e.g. if we wrote <code>[my-shortcode]</code> by accident.</p>\n<h2>Improving The Shortcode</h2>\n<p>First, lets add type hints. This will avoid a common pitfall/bug that people fall into:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n</code></pre>\n<p>Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.</p>\n<p>This give us:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function shortcode_function( array $attributes ) : string {\n // get the attributes\n $attributes = shortcode_atts( [\n 'id' => 'default ID value goes here',\n ], $attributes );\n $id = $attributes['id'];\n\n // generate the shortcode's content:\n return 'My ID is:' . $id;\n}\nadd_shortcode( 'my-shortcode', 'shortcode_function' );\n</code></pre>\n"
}
] | 2022/07/25 | [
"https://wordpress.stackexchange.com/questions/407995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183833/"
] | I have a page where I want to add a custom class to all the images.
How to add this?
Thank you. | Your short code function receives the attributes as the first argument:
```php
function shortcode_function( $attributes ) {
```
Here `$attributes` is an array, and the attributes/values are inside that variable,
e.g. for `[my-shortcode abc="123" xyz="789"]`:
```php
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
```
You should also provide defaults and an opportunity to filter:
```php
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
```
This way if the `id` is missing you don't get PHP warnings, e.g. if we wrote `[my-shortcode]` by accident.
Improving The Shortcode
-----------------------
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
```php
function shortcode_function( array $attributes ) : string {
```
Here we've told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
```php
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );
``` |
408,051 | <p>I'm using a plugin that doesn't provide many hooks for its actions. I would like to be able to hook in when the plugin adds a row to a plugin-specific table, and update some other data elsewhere. (For context, it's a CRM. Whenever a log is added to its logs table, I would also like to update the CRM users table, updating the status column for the user associated to the log.)</p>
<p>I know there are hooks like <code>pre_get_posts</code> to modify a main query. However, since the insert isn't a <code>get_posts()</code> query, I am looking for something similar that fires when data is inserted, and then I'll narrow it down to only when data is inserted into this particular table.</p>
| [
{
"answer_id": 408054,
"author": "Brennan",
"author_id": 149131,
"author_profile": "https://wordpress.stackexchange.com/users/149131",
"pm_score": 3,
"selected": false,
"text": "<p>If you have access to the database, you could potentially create a trigger for that plugin-specific table. This bypasses the need for a hook. Depending on how they handle database schema updates, it might even stick around after a plugin update. <em>I've never tried triggers on WP tables though, so take this with a grain of salt.</em></p>\n<p>E.g.</p>\n<pre><code>CREATE TRIGGER after_customer_insert\nAFTER INSERT\nON wp_plugin_customers FOR EACH ROW\nBEGIN\n IF NEW.PhoneNumber IS NOT NULL THEN\n UPDATE wp_plugin_other_table SET column = NEW.PhoneNumber\n WHERE other_column = NEW.CustomerCompany;\n END IF;\nEND\n</code></pre>\n<p>Edit: You could also ask the plugin author about adding a hook. Sometimes they oblige.</p>\n"
},
{
"answer_id": 408211,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 2,
"selected": false,
"text": "<p>As you probably already noticed yourself <code>$wpdb</code> doesn't have any hooks that you can use.</p>\n<p>The answer @brennan gave already sounds like an interesting approach, but probably won't help if you have to solve it in code without access to the DB to create the trigger.</p>\n<p>I have another idea, that although hacky, might also work depending on what exactly your requirements are.</p>\n<p>So you said "[…] able to hook in when the plugin adds a row to a plugin-specific table […]". So I assume you really only are talking about adding rows, not editing existing. I am also assuming that the table has some auto incrementing ID.</p>\n<p>If that is the case what about this approach:</p>\n<ol>\n<li>Store the highest ID of a row in the relevant table, e.g. in an option.</li>\n<li>Check if the stored ID is lower than the current highest ID.</li>\n<li>Get all rows from the last stored ID to the current ID.</li>\n<li>Do whatever you need to do with that information.</li>\n</ol>\n<p><em>When</em> you do this really depends on the exact requirements of your "update some other data elsewhere". You could do it in the <code>shutdown</code> hook, in CRON that runs every couple minutes, some hook from the plugin that reliably runs after updates or - thinking about your "updating the status column for the user associated to the log" - right before the reading of the user status.</p>\n<p><em>EDIT: <a href=\"https://wordpress.stackexchange.com/questions/408051/hook-for-inserting/408211?noredirect=1#comment596397_408211\">the comment by @birgire</a> just made me realize another thing: You can try hooking to <a href=\"https://developer.wordpress.org/reference/hooks/query/\" rel=\"nofollow noreferrer\"><code>query</code></a> to set a flag if the query is the one you care about and only do the check from above if that flag is set to true. This should be way better from a performance perspective.</em></p>\n<p>I am intentionally leaving out any specific code, but I hope the approach is clear.</p>\n"
}
] | 2022/07/27 | [
"https://wordpress.stackexchange.com/questions/408051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
] | I'm using a plugin that doesn't provide many hooks for its actions. I would like to be able to hook in when the plugin adds a row to a plugin-specific table, and update some other data elsewhere. (For context, it's a CRM. Whenever a log is added to its logs table, I would also like to update the CRM users table, updating the status column for the user associated to the log.)
I know there are hooks like `pre_get_posts` to modify a main query. However, since the insert isn't a `get_posts()` query, I am looking for something similar that fires when data is inserted, and then I'll narrow it down to only when data is inserted into this particular table. | If you have access to the database, you could potentially create a trigger for that plugin-specific table. This bypasses the need for a hook. Depending on how they handle database schema updates, it might even stick around after a plugin update. *I've never tried triggers on WP tables though, so take this with a grain of salt.*
E.g.
```
CREATE TRIGGER after_customer_insert
AFTER INSERT
ON wp_plugin_customers FOR EACH ROW
BEGIN
IF NEW.PhoneNumber IS NOT NULL THEN
UPDATE wp_plugin_other_table SET column = NEW.PhoneNumber
WHERE other_column = NEW.CustomerCompany;
END IF;
END
```
Edit: You could also ask the plugin author about adding a hook. Sometimes they oblige. |
408,081 | <p>On the post editor field, I have added an <code>iframe</code> code. But on the frontend, it is not showing the content with the <code>iframe</code> code.</p>
<p>I have added the below code to print the excerpt on the blog page:</p>
<pre class="lang-php prettyprint-override"><code><?php echo get_post_field('post_content', $post['id']) ; ?>
</code></pre>
<p>It is not in the single post page, but I have tried to print the post content instead of excerpt on the Blog page.</p>
<p>Can you please point me where I am making the mistake?</p>
| [
{
"answer_id": 408054,
"author": "Brennan",
"author_id": 149131,
"author_profile": "https://wordpress.stackexchange.com/users/149131",
"pm_score": 3,
"selected": false,
"text": "<p>If you have access to the database, you could potentially create a trigger for that plugin-specific table. This bypasses the need for a hook. Depending on how they handle database schema updates, it might even stick around after a plugin update. <em>I've never tried triggers on WP tables though, so take this with a grain of salt.</em></p>\n<p>E.g.</p>\n<pre><code>CREATE TRIGGER after_customer_insert\nAFTER INSERT\nON wp_plugin_customers FOR EACH ROW\nBEGIN\n IF NEW.PhoneNumber IS NOT NULL THEN\n UPDATE wp_plugin_other_table SET column = NEW.PhoneNumber\n WHERE other_column = NEW.CustomerCompany;\n END IF;\nEND\n</code></pre>\n<p>Edit: You could also ask the plugin author about adding a hook. Sometimes they oblige.</p>\n"
},
{
"answer_id": 408211,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 2,
"selected": false,
"text": "<p>As you probably already noticed yourself <code>$wpdb</code> doesn't have any hooks that you can use.</p>\n<p>The answer @brennan gave already sounds like an interesting approach, but probably won't help if you have to solve it in code without access to the DB to create the trigger.</p>\n<p>I have another idea, that although hacky, might also work depending on what exactly your requirements are.</p>\n<p>So you said "[…] able to hook in when the plugin adds a row to a plugin-specific table […]". So I assume you really only are talking about adding rows, not editing existing. I am also assuming that the table has some auto incrementing ID.</p>\n<p>If that is the case what about this approach:</p>\n<ol>\n<li>Store the highest ID of a row in the relevant table, e.g. in an option.</li>\n<li>Check if the stored ID is lower than the current highest ID.</li>\n<li>Get all rows from the last stored ID to the current ID.</li>\n<li>Do whatever you need to do with that information.</li>\n</ol>\n<p><em>When</em> you do this really depends on the exact requirements of your "update some other data elsewhere". You could do it in the <code>shutdown</code> hook, in CRON that runs every couple minutes, some hook from the plugin that reliably runs after updates or - thinking about your "updating the status column for the user associated to the log" - right before the reading of the user status.</p>\n<p><em>EDIT: <a href=\"https://wordpress.stackexchange.com/questions/408051/hook-for-inserting/408211?noredirect=1#comment596397_408211\">the comment by @birgire</a> just made me realize another thing: You can try hooking to <a href=\"https://developer.wordpress.org/reference/hooks/query/\" rel=\"nofollow noreferrer\"><code>query</code></a> to set a flag if the query is the one you care about and only do the check from above if that flag is set to true. This should be way better from a performance perspective.</em></p>\n<p>I am intentionally leaving out any specific code, but I hope the approach is clear.</p>\n"
}
] | 2022/07/28 | [
"https://wordpress.stackexchange.com/questions/408081",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185965/"
] | On the post editor field, I have added an `iframe` code. But on the frontend, it is not showing the content with the `iframe` code.
I have added the below code to print the excerpt on the blog page:
```php
<?php echo get_post_field('post_content', $post['id']) ; ?>
```
It is not in the single post page, but I have tried to print the post content instead of excerpt on the Blog page.
Can you please point me where I am making the mistake? | If you have access to the database, you could potentially create a trigger for that plugin-specific table. This bypasses the need for a hook. Depending on how they handle database schema updates, it might even stick around after a plugin update. *I've never tried triggers on WP tables though, so take this with a grain of salt.*
E.g.
```
CREATE TRIGGER after_customer_insert
AFTER INSERT
ON wp_plugin_customers FOR EACH ROW
BEGIN
IF NEW.PhoneNumber IS NOT NULL THEN
UPDATE wp_plugin_other_table SET column = NEW.PhoneNumber
WHERE other_column = NEW.CustomerCompany;
END IF;
END
```
Edit: You could also ask the plugin author about adding a hook. Sometimes they oblige. |
408,101 | <p>To clarify -- these files in the error were NOT edited at the time of the error, I checked twice. And I checked again by doing a diff with a fresh WordPress install. I had to remove the broken line -- shown below -- because it crashes WordPress. This line does not crash all WordPress blogs, obviously, and I have another blog on the same LEMP stack without the fatal error. How is "kses" activated in this case? Is it the content of the blog? I don't know, but I don't see any plugin or theme in the stack trace.</p>
<p>Here's the error:</p>
<pre><code>[error] FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught TypeError: in_array(): Argument #2 ($haystack) must be of type array, null given in /home/www-data/example.com/wp-includes/kses.php:1871
#0 /home/www-data/example.com/wp-includes/kses.php(1871): in_array()
#1 [internal function]: wp_kses_named_entities()
#2 /home/www-data/example.com/wp-includes/kses.php(1842): preg_replace_callback()
#3 /home/www-data/example.com/wp-includes/formatting.php(981): wp_kses_normalize_entities()
</code></pre>
<p>This line does not work in PHP8:</p>
<pre><code>return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&amp;$i;" : "&$i;";
</code></pre>
<p>There's no plugin or theme referring to "allowedentitynames" as per grep.</p>
| [
{
"answer_id": 408102,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p><em><strong>Never edit core files, and definitely do not make this change.</strong></em></p>\n<p>Looking at the source the problem doesn't seem related to PHP 8.1 at all. Something in a theme or plugin is causing <code>$allowedentitynames</code> to be <code>null</code>, which it should not be. See <a href=\"https://core.trac.wordpress.org/ticket/47357\" rel=\"nofollow noreferrer\">this trac ticket</a> for a previous discussion with somebody who encountered this issue.</p>\n"
},
{
"answer_id": 408144,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>When you use the deprecated <code>CUSTOM_TAGS</code> constant, you have to define the variables WordPress would normally create in <code>kses.php</code> at the top. If you do not then you will encounter this issue.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Specifies the default allowable HTML tags.\n *\n * Using `CUSTOM_TAGS` is not recommended and should be considered deprecated. The\n * {@see 'wp_kses_allowed_html'} filter is more powerful and supplies context.\n *\n * @see wp_kses_allowed_html()\n * @since 1.2.0\n *\n * @var array[]|false Array of default allowable HTML tags, or false to use the defaults.\n */\nif ( ! defined( 'CUSTOM_TAGS' ) ) {\n define( 'CUSTOM_TAGS', false );\n}\n</code></pre>\n<p>Instead, you should use the <code>wp_kses_allowed_html</code> filter to modify which tags are allowed, using the <code>context</code> parameter to control when and where the adjusted tags are usable:</p>\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_kses_allowed_html/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_kses_allowed_html/</a></p>\n<p>Just keep in mind that the list of tags is chosen to avoid allowing dangerous things into posts and comments. E.g. iframes or script tags. Changing these will have significant security consequences.</p>\n<blockquote>\n<p>How is "kses" activated in this case? Is it the content of the blog?</p>\n</blockquote>\n<p><code>kses</code> functions are used everywhere in WordPress and play a pivotal role in security. E.g. <code>wp_kses_post</code> is used to strip out dangerous tags when saving a post, and <code>wp_kses</code> can strip out tags and attributes that don't fit a whitelist. <code>wp_kses</code> and it's wrapper functions act as both pseudo-escaping and as sanitisation functions.</p>\n"
}
] | 2022/07/29 | [
"https://wordpress.stackexchange.com/questions/408101",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3453/"
] | To clarify -- these files in the error were NOT edited at the time of the error, I checked twice. And I checked again by doing a diff with a fresh WordPress install. I had to remove the broken line -- shown below -- because it crashes WordPress. This line does not crash all WordPress blogs, obviously, and I have another blog on the same LEMP stack without the fatal error. How is "kses" activated in this case? Is it the content of the blog? I don't know, but I don't see any plugin or theme in the stack trace.
Here's the error:
```
[error] FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught TypeError: in_array(): Argument #2 ($haystack) must be of type array, null given in /home/www-data/example.com/wp-includes/kses.php:1871
#0 /home/www-data/example.com/wp-includes/kses.php(1871): in_array()
#1 [internal function]: wp_kses_named_entities()
#2 /home/www-data/example.com/wp-includes/kses.php(1842): preg_replace_callback()
#3 /home/www-data/example.com/wp-includes/formatting.php(981): wp_kses_normalize_entities()
```
This line does not work in PHP8:
```
return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&$i;" : "&$i;";
```
There's no plugin or theme referring to "allowedentitynames" as per grep. | When you use the deprecated `CUSTOM_TAGS` constant, you have to define the variables WordPress would normally create in `kses.php` at the top. If you do not then you will encounter this issue.
```php
/**
* Specifies the default allowable HTML tags.
*
* Using `CUSTOM_TAGS` is not recommended and should be considered deprecated. The
* {@see 'wp_kses_allowed_html'} filter is more powerful and supplies context.
*
* @see wp_kses_allowed_html()
* @since 1.2.0
*
* @var array[]|false Array of default allowable HTML tags, or false to use the defaults.
*/
if ( ! defined( 'CUSTOM_TAGS' ) ) {
define( 'CUSTOM_TAGS', false );
}
```
Instead, you should use the `wp_kses_allowed_html` filter to modify which tags are allowed, using the `context` parameter to control when and where the adjusted tags are usable:
<https://developer.wordpress.org/reference/hooks/wp_kses_allowed_html/>
Just keep in mind that the list of tags is chosen to avoid allowing dangerous things into posts and comments. E.g. iframes or script tags. Changing these will have significant security consequences.
>
> How is "kses" activated in this case? Is it the content of the blog?
>
>
>
`kses` functions are used everywhere in WordPress and play a pivotal role in security. E.g. `wp_kses_post` is used to strip out dangerous tags when saving a post, and `wp_kses` can strip out tags and attributes that don't fit a whitelist. `wp_kses` and it's wrapper functions act as both pseudo-escaping and as sanitisation functions. |
408,225 | <p>When you set up blocks in the block editor (Gutenberg), you typically get options on how to align them (i.e. none, wide, full). Or, if your theme doesn't have them, you can use the function <code>add_theme_support ();</code> to include them. This is really helpful because then I can style them with CSS like something below:</p>
<pre><code>.alignfull {
width: 100vw !important;
max-width: 100vw !important;
position: relative;
left: 50% !important;
right: 50% !important;
margin-left: -50vw !important;
margin-right: -50vw !important;
margin-top: 0;
margin-bottom: 0;
}
</code></pre>
<p>Is there a hook I could include in my theme's <code>functions.php</code> to add another alignment option? A custom one I could style with my CSS?</p>
<p>Do I have to hook into each block to accomplish this or can it be something where if alignment is supported, the option will be included?</p>
<p>Ideally, I would love to have an option for my <a href="https://wordpress.org/support/article/columns-block/" rel="nofollow noreferrer">Column</a> block to have a smaller width alignment option for content editors to choose from.</p>
<p><a href="https://i.stack.imgur.com/n3zPf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n3zPf.png" alt="column block alignment" /></a></p>
<p>I <a href="https://github.com/WordPress/gutenberg/issues/27629" rel="nofollow noreferrer">found an issue raised about it from Dec 2020</a> with not much luck. Adding a CSS class under "Advanced" is not ideal when you are trying to keep bumpers on for the content editor.</p>
| [
{
"answer_id": 408219,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>In versions of WordPress prior to 4.2 terms could belong to multiple taxonomies. This is no longer the case and in WordPress 4.2 or newer new terms cannot belong to multiple taxonomies and any existing terms that belong to multiple taxonomies are split into multiple terms whenever they are updated.</p>\n<p>You can read this post for an introduction to the change from before it was made: <a href=\"https://make.wordpress.org/core/2015/02/16/taxonomy-term-splitting-in-4-2-a-developer-guide/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2015/02/16/taxonomy-term-splitting-in-4-2-a-developer-guide/</a></p>\n<p>There is also this article which describes the splitting process: <a href=\"https://developer.wordpress.org/plugins/taxonomies/split-terms-wp-4-2/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/taxonomies/split-terms-wp-4-2/</a></p>\n<p>So unless you are dealing with pre-4.2 data the values of these columns should always be the same.</p>\n"
},
{
"answer_id": 408268,
"author": "Steve Kinzey",
"author_id": 84603,
"author_profile": "https://wordpress.stackexchange.com/users/84603",
"pm_score": 0,
"selected": false,
"text": "<p>The <strong>term_id</strong> is the ID of a term in the terms table. A term is a word that can belong in any taxonomy (category, tag, custom taxonomy), and taxonomy can contain the same term. For example, you decide to have a term by the name of shoes; the term_id is a number that represents this word. The number is independent of the taxonomies within which you list shoes.</p>\n<p>Additionally, the <strong>term_taxonomy_id</strong> is the unique ID for the term+taxonomy pair. If you use the term shoes as both a post tag and a category, the term_taxonomy_id will be different for both.</p>\n<p>Moreover, both have an auto-increment in the table structure, so as you add a post that includes a term and a taxonomy (even uncategorized), both the term_id and term_taxonomy_id will increase automatically, and <strong>in all but a few cases, they will be the same</strong>.</p>\n<p>You use the term_id value for functions that expect a category ID. The term_taxonomy_id can serve as a query variable; otherwise, it is rarely used.</p>\n"
}
] | 2022/08/02 | [
"https://wordpress.stackexchange.com/questions/408225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12294/"
] | When you set up blocks in the block editor (Gutenberg), you typically get options on how to align them (i.e. none, wide, full). Or, if your theme doesn't have them, you can use the function `add_theme_support ();` to include them. This is really helpful because then I can style them with CSS like something below:
```
.alignfull {
width: 100vw !important;
max-width: 100vw !important;
position: relative;
left: 50% !important;
right: 50% !important;
margin-left: -50vw !important;
margin-right: -50vw !important;
margin-top: 0;
margin-bottom: 0;
}
```
Is there a hook I could include in my theme's `functions.php` to add another alignment option? A custom one I could style with my CSS?
Do I have to hook into each block to accomplish this or can it be something where if alignment is supported, the option will be included?
Ideally, I would love to have an option for my [Column](https://wordpress.org/support/article/columns-block/) block to have a smaller width alignment option for content editors to choose from.
[](https://i.stack.imgur.com/n3zPf.png)
I [found an issue raised about it from Dec 2020](https://github.com/WordPress/gutenberg/issues/27629) with not much luck. Adding a CSS class under "Advanced" is not ideal when you are trying to keep bumpers on for the content editor. | In versions of WordPress prior to 4.2 terms could belong to multiple taxonomies. This is no longer the case and in WordPress 4.2 or newer new terms cannot belong to multiple taxonomies and any existing terms that belong to multiple taxonomies are split into multiple terms whenever they are updated.
You can read this post for an introduction to the change from before it was made: <https://make.wordpress.org/core/2015/02/16/taxonomy-term-splitting-in-4-2-a-developer-guide/>
There is also this article which describes the splitting process: <https://developer.wordpress.org/plugins/taxonomies/split-terms-wp-4-2/>
So unless you are dealing with pre-4.2 data the values of these columns should always be the same. |
408,330 | <p>As a plugin developer who wants to provide better documentations to my customers I'm also including a dev section inside my docs.</p>
<p>This section should contain all provided hooks and filters by my plugin including the filename and line. Also, I want to grab the documentation above each hook to display it as documentation of the hook / filter.</p>
<p>Instead of going through every file, I'm very sure that there's a script out there which already does this kind of work.</p>
<p>At least the script should create a TXT file which contains all that stuff.</p>
<p>If someone knows a script to accomplish this I would be really glad if you can share it with me. If I don't get an useful answer, I'll sit down myself, develop a script like this and publish it to GitHub so everyone can use it!</p>
| [
{
"answer_id": 408733,
"author": "Johnny97",
"author_id": 151233,
"author_profile": "https://wordpress.stackexchange.com/users/151233",
"pm_score": 2,
"selected": true,
"text": "<p>I've tried using the parser, but it's build for WP docs and is a bit too complex for my needs. So I've invented my own little plugin: HookR.</p>\n<p>HookR provides a shortcode where you can pass a path to the uploads folder and a file inside containing all plugins hooks within a JSON format:</p>\n<pre><code>{\n "created": "1660810923",\n "src": "/Users/anonymous/Sites/development/wp-content/plugins/abc",\n "hooks": [\n {\n "name": "abc_encryptor_encrypt",\n "type": "filter",\n "desc": "This filter filters the value which should be encrypted",\n "since": "1.7.0",\n "attrs": [\n {\n "name": "$value",\n "type": "string",\n "desc": "The value which should be encrypted"\n },\n {\n "name": "$key",\n "type": "string",\n "desc": "The encryptor key"\n }\n ],\n "src": [\n {\n "file": "class-abc-encryptor.php",\n "line": 57\n }\n ]\n }\n ]\n}\n</code></pre>\n<p>The result on each page with the included shortcode will look like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Mkdy6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Mkdy6.png\" alt=\"enter image description here\" /></a></p>\n<p>The JSON file can be created by a Python script. If I get enough upvotes and comments, I may consider publishing the plugin at WP.</p>\n"
},
{
"answer_id": 408736,
"author": "flytomoon777",
"author_id": 223518,
"author_profile": "https://wordpress.stackexchange.com/users/223518",
"pm_score": 0,
"selected": false,
"text": "<p>You can use WordPress <a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"nofollow noreferrer\">Query Monitor Plugin</a></p>\n<p>It give you access the details of the queries made to the database, CSS, active hooks, and the HTTP API calls by clicking the entries in the dropdown list.</p>\n"
}
] | 2022/08/05 | [
"https://wordpress.stackexchange.com/questions/408330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151233/"
] | As a plugin developer who wants to provide better documentations to my customers I'm also including a dev section inside my docs.
This section should contain all provided hooks and filters by my plugin including the filename and line. Also, I want to grab the documentation above each hook to display it as documentation of the hook / filter.
Instead of going through every file, I'm very sure that there's a script out there which already does this kind of work.
At least the script should create a TXT file which contains all that stuff.
If someone knows a script to accomplish this I would be really glad if you can share it with me. If I don't get an useful answer, I'll sit down myself, develop a script like this and publish it to GitHub so everyone can use it! | I've tried using the parser, but it's build for WP docs and is a bit too complex for my needs. So I've invented my own little plugin: HookR.
HookR provides a shortcode where you can pass a path to the uploads folder and a file inside containing all plugins hooks within a JSON format:
```
{
"created": "1660810923",
"src": "/Users/anonymous/Sites/development/wp-content/plugins/abc",
"hooks": [
{
"name": "abc_encryptor_encrypt",
"type": "filter",
"desc": "This filter filters the value which should be encrypted",
"since": "1.7.0",
"attrs": [
{
"name": "$value",
"type": "string",
"desc": "The value which should be encrypted"
},
{
"name": "$key",
"type": "string",
"desc": "The encryptor key"
}
],
"src": [
{
"file": "class-abc-encryptor.php",
"line": 57
}
]
}
]
}
```
The result on each page with the included shortcode will look like this:
[](https://i.stack.imgur.com/Mkdy6.png)
The JSON file can be created by a Python script. If I get enough upvotes and comments, I may consider publishing the plugin at WP. |
408,331 | <p>I've been having issues using wp_mail and mail functions in an application when specifying header elements in the function.</p>
<p>I usually set up the header as an <em>associative</em> array, as in</p>
<pre><code>$mailheader = array(
'MIME-Version' => '1.0',
'Content-type' => ' text/html; charset=utf-8',
'From' => '[email protected]' ,
);
</code></pre>
<p>Using the mail() command, the headers are processed correctly, and the message is sent as an HTML mail.</p>
<pre><code>mail("[email protected]", "my subject", "<p>A message here.</p>", $mailheader);
</code></pre>
<p>But if I use the same command with the wp_mail function (on a WP 6.x site), the message is sent as plain text:</p>
<pre><code>wp_mail("[email protected]", "my subject", "<p>A message here.</p>", $mailheader);
</code></pre>
<p>If you want to use an <em>associative</em> array for the headers in wp_mail, you have to convert it text:</p>
<pre><code> foreach ($mailheader as $key => $value) {
$header_wp .= "$key: $value \r\n"; // for wp-mail header which doesn't do arrays
}
</code></pre>
<p>(Note the use of double quotes in the statement, so the \r\n is processed properly.)</p>
<p>And then use this wp_mail command:</p>
<pre><code>wp_mail("[email protected]", "my subject", "<p>A message here.</p>", $header_wp );
</code></pre>
<p>This will result in an HTML-formatted message when using wp_mail.</p>
<p>I have verified this on different WP 6.01 sites with PHP versions 7.3 and 8.x. The processing of the header by wp_mail happens before it is sent to phpMailer.</p>
<p>I spent a couple of weeks fighting this one, so wanted to alert others.</p>
<p>I'll put the correct code in my answer to the question.</p>
<p><strong>Added</strong></p>
<p>I adjusted my question to emphasize that a two-dimensional header array will not work with wp_mail(), but will work with mail(). If you set up a two-dimensional array, you will need to convert to text string or a one-dimensional array (as noted in SallyCJ's answer).</p>
<p>** Added 2 **</p>
<p>Oops...got my term wrong. It is an associative array that does not work with wp_mail. See my example $mailheader associative array.</p>
| [
{
"answer_id": 408332,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Added</strong></p>\n<p>Although wp_mail will accept a one-dimensional array, it will not accept a <em>associative</em> array, as in</p>\n<pre><code>$mailheader = array(\n 'MIME-Version' => '1.0',\n 'Content-type' => ' text/html; charset=utf-8',\n 'From' => '[email protected]' ,\n);\n</code></pre>\n<p>The <em>associative</em> array, which is allowed by the PHP mail() function, will <strong>not</strong> work with wp_mail().</p>\n<p><strong>Original</strong></p>\n<p>To properly use headers in wp_mail, the header must be a string, not an array. Example code</p>\n<pre><code> foreach ($mailheader as $key => $value) {\n\n $header_wp .= "$key: $value \\r\\n"; // for wp-mail header which doesn't do arrays\n }\n</code></pre>\n<p>(Note the use of double quotes in the statement, so the \\r\\n is processed properly.)</p>\n<p>And then use this wp_mail command:</p>\n<pre><code>wp_mail("[email protected]", "my subject", "<p>A message here.</p>", $header_wp );\n</code></pre>\n<p>This will result in an HTML-formatted message when using wp_mail. If you use an array as the header in wp_mail, the message will be sent as plain text.</p>\n<p><strong>Correction</strong> used the wrong term for the type of array - it is associative, not two-dimensional. The associative array will not work in wp_mail.</p>\n"
},
{
"answer_id": 408334,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>Both the <a href=\"https://www.php.net/manual/en/function.mail.php\" rel=\"nofollow noreferrer\"><code>mail()</code> function in PHP</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\"><code>wp_mail()</code> in WordPress</a> do support passing an array or string of headers, but the difference is:</p>\n<ul>\n<li><p>With <code>mail()</code>, the array keys are the header names and its values are the respective header values, e.g. <code>array( 'Content-type' => 'text/html; charset=utf-8' )</code>.</p>\n</li>\n<li><p><code>wp_mail()</code> on the other hand, expects that the header name and value are put in the array <strong>values</strong>, e.g. <code>array( 'Content-type: text/html; charset=utf-8' )</code>.</p>\n</li>\n</ul>\n<p>So this statement is not necessarily true:</p>\n<blockquote>\n<p>If you want to use an array for the headers in wp_mail, you have to\nconvert it text</p>\n</blockquote>\n<p>Because you could actually instead convert the format of your <code>$mailheader</code> array to:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$mailheader = array(\n 'MIME-Version: 1.0',\n 'Content-type: text/html; charset=utf-8',\n 'From: [email protected]',\n);\n</code></pre>\n<p>Or create a headers array specifically for <code>wp_mail()</code>, from that array, like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$headers = array();\nforeach ( $mailheader as $key => $value ) {\n $headers[] = "$key: $value";\n}\n</code></pre>\n<p>Example by Codex (see <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/#comment-348\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/#comment-348</a>):</p>\n<blockquote>\n<p>To send HTML formatted mail, you also can specify the Content-Type\nHTTP header in the <code>$headers</code> parameter:</p>\n<pre><code>$to = '[email protected]';\n$subject = 'The subject';\n$body = 'The email body content';\n$headers = array('Content-Type: text/html; charset=UTF-8');\n\nwp_mail( $to, $subject, $body, $headers );\n</code></pre>\n</blockquote>\n<p>And the documentation also stated that:</p>\n<ul>\n<li>\n<blockquote>\n<p><code>$headers</code> can be a string or an array, but it may be easiest to use\nin the array form.</p>\n</blockquote>\n</li>\n<li>\n<blockquote>\n<p>When you are using the array form, you do not need to supply line\nbreaks ("\\n" or "\\r\\n").</p>\n</blockquote>\n<p>And thus, we could save time from trying to figure out whether CRLF (<code>\\r\\n</code>) or LF (<code>\\n</code>) should be used..</p>\n</li>\n</ul>\n"
}
] | 2022/08/05 | [
"https://wordpress.stackexchange.com/questions/408331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | I've been having issues using wp\_mail and mail functions in an application when specifying header elements in the function.
I usually set up the header as an *associative* array, as in
```
$mailheader = array(
'MIME-Version' => '1.0',
'Content-type' => ' text/html; charset=utf-8',
'From' => '[email protected]' ,
);
```
Using the mail() command, the headers are processed correctly, and the message is sent as an HTML mail.
```
mail("[email protected]", "my subject", "<p>A message here.</p>", $mailheader);
```
But if I use the same command with the wp\_mail function (on a WP 6.x site), the message is sent as plain text:
```
wp_mail("[email protected]", "my subject", "<p>A message here.</p>", $mailheader);
```
If you want to use an *associative* array for the headers in wp\_mail, you have to convert it text:
```
foreach ($mailheader as $key => $value) {
$header_wp .= "$key: $value \r\n"; // for wp-mail header which doesn't do arrays
}
```
(Note the use of double quotes in the statement, so the \r\n is processed properly.)
And then use this wp\_mail command:
```
wp_mail("[email protected]", "my subject", "<p>A message here.</p>", $header_wp );
```
This will result in an HTML-formatted message when using wp\_mail.
I have verified this on different WP 6.01 sites with PHP versions 7.3 and 8.x. The processing of the header by wp\_mail happens before it is sent to phpMailer.
I spent a couple of weeks fighting this one, so wanted to alert others.
I'll put the correct code in my answer to the question.
**Added**
I adjusted my question to emphasize that a two-dimensional header array will not work with wp\_mail(), but will work with mail(). If you set up a two-dimensional array, you will need to convert to text string or a one-dimensional array (as noted in SallyCJ's answer).
\*\* Added 2 \*\*
Oops...got my term wrong. It is an associative array that does not work with wp\_mail. See my example $mailheader associative array. | Both the [`mail()` function in PHP](https://www.php.net/manual/en/function.mail.php) and [`wp_mail()` in WordPress](https://developer.wordpress.org/reference/functions/wp_mail/) do support passing an array or string of headers, but the difference is:
* With `mail()`, the array keys are the header names and its values are the respective header values, e.g. `array( 'Content-type' => 'text/html; charset=utf-8' )`.
* `wp_mail()` on the other hand, expects that the header name and value are put in the array **values**, e.g. `array( 'Content-type: text/html; charset=utf-8' )`.
So this statement is not necessarily true:
>
> If you want to use an array for the headers in wp\_mail, you have to
> convert it text
>
>
>
Because you could actually instead convert the format of your `$mailheader` array to:
```php
$mailheader = array(
'MIME-Version: 1.0',
'Content-type: text/html; charset=utf-8',
'From: [email protected]',
);
```
Or create a headers array specifically for `wp_mail()`, from that array, like so:
```php
$headers = array();
foreach ( $mailheader as $key => $value ) {
$headers[] = "$key: $value";
}
```
Example by Codex (see <https://developer.wordpress.org/reference/functions/wp_mail/#comment-348>):
>
> To send HTML formatted mail, you also can specify the Content-Type
> HTTP header in the `$headers` parameter:
>
>
>
> ```
> $to = '[email protected]';
> $subject = 'The subject';
> $body = 'The email body content';
> $headers = array('Content-Type: text/html; charset=UTF-8');
>
> wp_mail( $to, $subject, $body, $headers );
>
> ```
>
>
And the documentation also stated that:
* >
> `$headers` can be a string or an array, but it may be easiest to use
> in the array form.
>
>
>
* >
> When you are using the array form, you do not need to supply line
> breaks ("\n" or "\r\n").
>
>
>
And thus, we could save time from trying to figure out whether CRLF (`\r\n`) or LF (`\n`) should be used.. |
408,410 | <p>I'm trying to find a way to show different content if a post is set to "password protected", once the user entered the correct password.</p>
<p>I want to show the price of an art piece only on posts that are set to password protected.</p>
<p>I can't find any php code to achieve this, since all I can find includes cookies management.</p>
<p>something like :</p>
<pre><code><?php if($post is set to password protected): ?>
show price
<?php endif; ?>
</code></pre>
<p>is there a way to do this ? there must some data stored into the database somewhere right ?</p>
<p>any help would be greatly appreciated ;)</p>
| [
{
"answer_id": 408414,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>There's two main ways:</p>\n<ol>\n<li>You can use the <a href=\"https://developer.wordpress.org/reference/functions/post_password_required/\" rel=\"nofollow noreferrer\"><code>post_password_required()</code></a> function. This function returns <code>true</code> if the post has a password and <code>false</code> if the post doesn't have a password, but it also returns <code>false</code> if the post had a password but the user has entered it and unlocked the post.</li>\n<li>You can get the post object with <code>$post = get_post()</code> and then check <code>empty( $post->post_password )</code>. This will tell you whether a post has a password regardless of whether or not the password has been entered.</li>\n</ol>\n"
},
{
"answer_id": 413760,
"author": "Fellipe Sanches",
"author_id": 171011,
"author_profile": "https://wordpress.stackexchange.com/users/171011",
"pm_score": 0,
"selected": false,
"text": "<p>For those prefer use SQL...</p>\n<pre><code>SELECT * FROM `wp_posts` WHERE `post_password` != ''\n</code></pre>\n<p>Note: mind to check about empty chars (like a empty space) in post_password field, it might confuse you.</p>\n"
}
] | 2022/08/09 | [
"https://wordpress.stackexchange.com/questions/408410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40572/"
] | I'm trying to find a way to show different content if a post is set to "password protected", once the user entered the correct password.
I want to show the price of an art piece only on posts that are set to password protected.
I can't find any php code to achieve this, since all I can find includes cookies management.
something like :
```
<?php if($post is set to password protected): ?>
show price
<?php endif; ?>
```
is there a way to do this ? there must some data stored into the database somewhere right ?
any help would be greatly appreciated ;) | There's two main ways:
1. You can use the [`post_password_required()`](https://developer.wordpress.org/reference/functions/post_password_required/) function. This function returns `true` if the post has a password and `false` if the post doesn't have a password, but it also returns `false` if the post had a password but the user has entered it and unlocked the post.
2. You can get the post object with `$post = get_post()` and then check `empty( $post->post_password )`. This will tell you whether a post has a password regardless of whether or not the password has been entered. |
408,447 | <p>I have a contact form 7 form and in that I have an acceptance checkbox for terms and condition and I want to make that checkbox required and add some class when checkbox is not checked and prevent form from submission.So I tried using preventDefault().</p>
<pre><code><script>
$(".wpcf7-form).submit(function(event){
if($("#checkbox1").hasClass("check") == false){
event.preventDefault();
$("#checkbox1).addClass("error");
} else {
$("#checkbox1).removeClass("error");
});
</script>
</code></pre>
<p>Now addclass line is working and for some reason preventDefault() is not working it is submitting my form everytime regardless of checkbox state.I want to make that checkobx required but I dont want to use acceptance's optional field as I dont want to disable my submit button.
Any help will be helpful and thanks in advance.</p>
| [
{
"answer_id": 408454,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 0,
"selected": false,
"text": "<p>You can disable your submit button when your condition is met. That should do the job.</p>\n<pre><code>$('.wpcf7-form').submit(function(event) {\n var submitButton = $(this).find('input[type="submit"]');\n if ( $('#checkbox1').hasClass('check') == false ) {\n $('#checkbox1').addClass('error');\n submitButton.disabled = true;\n }\n else {\n $('#checkbox1').removeClass('error');\n submitButton.disabled = false;\n }\n});\n</code></pre>\n"
},
{
"answer_id": 408715,
"author": "RDX023",
"author_id": 224467,
"author_profile": "https://wordpress.stackexchange.com/users/224467",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone still trying figure out the solution there is a additional settings which works like normal contact form 7 validation for other field just use <code>acceptance_as_validation: on</code>.</p>\n"
}
] | 2022/08/10 | [
"https://wordpress.stackexchange.com/questions/408447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/224467/"
] | I have a contact form 7 form and in that I have an acceptance checkbox for terms and condition and I want to make that checkbox required and add some class when checkbox is not checked and prevent form from submission.So I tried using preventDefault().
```
<script>
$(".wpcf7-form).submit(function(event){
if($("#checkbox1").hasClass("check") == false){
event.preventDefault();
$("#checkbox1).addClass("error");
} else {
$("#checkbox1).removeClass("error");
});
</script>
```
Now addclass line is working and for some reason preventDefault() is not working it is submitting my form everytime regardless of checkbox state.I want to make that checkobx required but I dont want to use acceptance's optional field as I dont want to disable my submit button.
Any help will be helpful and thanks in advance. | If anyone still trying figure out the solution there is a additional settings which works like normal contact form 7 validation for other field just use `acceptance_as_validation: on`. |
408,506 | <p>Assume all the code below is in a theme's <code>function.php</code></p>
<p>If I add <code>get_post()</code> at the top, It'd get <code>null</code>, which is totally expected since I'm not in the loop, or nothing has been done.</p>
<p>But I add</p>
<pre><code>add_filter('template_include', 'call_get_post'));
function call_get_posT(){
var_dump(get_post())
}
</code></pre>
<p>Then I'll get the info for the latest <code>post</code>.</p>
<p>I tried this in a fresh install of WP locally so I'd assume this is expected behavior, but I don't understand it. I'm not in the loop, and I haven't called anything to start a query, why would <code>get_post()</code> return the first post? Same result if I use <code>global $post</code>.</p>
<p>Can someone explain what's going on here?</p>
| [
{
"answer_id": 408507,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress queries the correct posts from the database automatically on every page load based on the URL. It needs to do that to know which template to load. Part of this process involves initialising the global <code>$post</code> variable to the first post found (or last, I can’t remember right now which one it will be). On single posts this will be the only post.</p>\n<p>You don’t need to initiate any query yourself for WordPress to query posts. If fact, if you're manually querying posts for the main list of posts on your blog page (or category archive etc.) you're doing it wrong. The purpose of the standard loop is to simply loop through those posts so that they can be displayed.</p>\n"
},
{
"answer_id": 408509,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>I tried this in a fresh install of WP locally so I'd assume this is expected behavior, but I don't understand it. I'm not in the loop,</p>\n</blockquote>\n<p>No but that doesn't mean a main query doesn't exist, it just means your code to display it hasn't run yet</p>\n<blockquote>\n<p>and I haven't called anything to start a query,</p>\n</blockquote>\n<p>But the main query has started and completed, it needs to in order for conditionals used to decide which template to load to work.</p>\n<blockquote>\n<p>why would get_post() return the first post? Same result if I use global $post.</p>\n</blockquote>\n<p>Why wouldn't it? Note that you get the same result because they are literally the same thing.</p>\n<p>When you load a URL several things happen:</p>\n<ul>\n<li>the pretty URL gets matched against a rule that turns it into an ugly URL aka <code>index.php?foo=bar</code></li>\n<li>those URL parameters get whitelisted and fed into the main query <code>WP_Query</code>, which is what the main loop functions operate on.</li>\n<li>that query is used to power functions like <code>is_single</code> or <code>is_archive</code> etc</li>\n<li>WP uses those functions to make a decision about which theme template or block template to load.</li>\n</ul>\n<p>So the main query has already fetched the posts, and the first post is already available. <strong>If it wasn't, there'd be no way to catch 404s or load page templates for pages.</strong></p>\n<p>Ofcourse, you've not called <code>the_post()</code> yet which might be why there's some confusion, but that makes more sense if you know these things:</p>\n<ul>\n<li>if you don't tell <code>get_post</code> which post to get, it defaults to the current post, aka <code>global $post</code>. It's the very first thing it does in the function\n<ul>\n<li>if you call this too early it can return <code>null</code></li>\n</ul>\n</li>\n<li>In the main WP class there's a function named <code>register_globals</code> that sets up initial values for major globals, including <code>$post</code>, which at the time of writing has a line that looks like this: <code>$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;</code>\n<ul>\n<li>it too will set it to <code>null</code> if no posts were found to avoid problems</li>\n</ul>\n</li>\n</ul>\n<p>Remember, <em><strong>all</strong></em> frontend pages have a main query, even if you use <code>get_posts</code> or <code>new WP_Query</code> in your templates.</p>\n"
}
] | 2022/08/11 | [
"https://wordpress.stackexchange.com/questions/408506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108358/"
] | Assume all the code below is in a theme's `function.php`
If I add `get_post()` at the top, It'd get `null`, which is totally expected since I'm not in the loop, or nothing has been done.
But I add
```
add_filter('template_include', 'call_get_post'));
function call_get_posT(){
var_dump(get_post())
}
```
Then I'll get the info for the latest `post`.
I tried this in a fresh install of WP locally so I'd assume this is expected behavior, but I don't understand it. I'm not in the loop, and I haven't called anything to start a query, why would `get_post()` return the first post? Same result if I use `global $post`.
Can someone explain what's going on here? | >
> I tried this in a fresh install of WP locally so I'd assume this is expected behavior, but I don't understand it. I'm not in the loop,
>
>
>
No but that doesn't mean a main query doesn't exist, it just means your code to display it hasn't run yet
>
> and I haven't called anything to start a query,
>
>
>
But the main query has started and completed, it needs to in order for conditionals used to decide which template to load to work.
>
> why would get\_post() return the first post? Same result if I use global $post.
>
>
>
Why wouldn't it? Note that you get the same result because they are literally the same thing.
When you load a URL several things happen:
* the pretty URL gets matched against a rule that turns it into an ugly URL aka `index.php?foo=bar`
* those URL parameters get whitelisted and fed into the main query `WP_Query`, which is what the main loop functions operate on.
* that query is used to power functions like `is_single` or `is_archive` etc
* WP uses those functions to make a decision about which theme template or block template to load.
So the main query has already fetched the posts, and the first post is already available. **If it wasn't, there'd be no way to catch 404s or load page templates for pages.**
Ofcourse, you've not called `the_post()` yet which might be why there's some confusion, but that makes more sense if you know these things:
* if you don't tell `get_post` which post to get, it defaults to the current post, aka `global $post`. It's the very first thing it does in the function
+ if you call this too early it can return `null`
* In the main WP class there's a function named `register_globals` that sets up initial values for major globals, including `$post`, which at the time of writing has a line that looks like this: `$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;`
+ it too will set it to `null` if no posts were found to avoid problems
Remember, ***all*** frontend pages have a main query, even if you use `get_posts` or `new WP_Query` in your templates. |
408,528 | <p>I am an old-school embedded C programmer but a WP noob, so please bear with me.</p>
<p>Here is what I have done so far:-</p>
<h1>Added a Shortcode in a Theme</h1>
<ol>
<li>My function prints out 'Hello World' and is registered to a shortcode in the OceanWP theme, and stored here:</li>
</ol>
<p><strong>> wp-content / themes / oceanwp / custom-shortcodes.php:</strong></p>
<pre><code><?php
// [helloworld]
function helloworld_func( $atts ) {
return "Hello World";
}
add_shortcode( 'helloworld', 'helloworld_func' );
</code></pre>
<ol start="2">
<li>I then added the shortcode to the following functions.php file:</li>
</ol>
<p><strong>>wp-content / themes / oceanwp / functions.php:</strong></p>
<pre><code>include ('custom-shortcodes.php');
</code></pre>
<ol start="3">
<li>I created a new WP Post and dropped the shortcode into it:</li>
</ol>
<pre><code>[helloworld]
</code></pre>
<ol start="4">
<li><strong>This works</strong> BUT: <br> if I subsequently add any code which gives an error, the page is affected, the whole theme is affected, the whole site is affected and even the whole WP Dashboard shows the error !</li>
</ol>
<p>(Reminds me of Windows 3.1 when a driver error crashed the whole OS. For me, the whole WP architecture sucks but I am stuck with it.)
/rant</p>
<ol start="5">
<li>I could create a child theme, but I prefer to:</li>
</ol>
<h1>Try to Add a Shortcode as a Plugin</h1>
<ol>
<li>So, I created a 'Hello World' plugin in the same way:</li>
</ol>
<p><strong>>wp-content / plugins / hello_world / hello_world_plugin.php</strong></p>
<pre><code>/**
* Plugin Name: HELLO WORLD PLUGIN
*/
// [hello_world_plugin]
function hello_world_plugin_func( $atts ) {
return "Hello World Plugin";
}
add_shortcode( 'hello_world_plugin', 'hello_world_plugin_func' );
</code></pre>
<ol start="2">
<li>Problem is: I do not know which functions.php file I need to add the following call to:</li>
</ol>
<pre><code>include ('hello_world_plugin.php');
</code></pre>
<p>so all I am seeing on the page is:</p>
<p>"[hello_world_plugin]"</p>
<p>I found the following file, but it does not seem to contain any other includes:</p>
<p><strong>>wp-includes / functions.php</strong></p>
<p>None of the other plugins seem to have a functions.php file, so I am assuming that my plugin does not need its own either...Is that right?</p>
<ol start="3">
<li>Furthermore, when I try to Activate my plugin, I get the following error on my WP Dashboard and on the whole damn page:</li>
</ol>
<pre><code>The plugin generated 213 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
</code></pre>
<p>So, here are my questions:-</p>
<p>A) Do I need to activate my Hello World plugin? If so, do I need to call the following:</p>
<pre><code>register_activation_hook()
</code></pre>
<p>On some tutorials, I saw similar plugin code, without any such hook...</p>
<p>B) In which functions.php file am I supposed to drop an include statement, so that the Hello World shortcode plugin is 'executable'?</p>
<p>I am sure the solution is going to be trivial (always is), but after reading through ALL the WP Dev docs (or what seems like it), I still cannot see what I am doing wrong.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 408539,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>In which functions.php file am I supposed to drop an include\nstatement, so that the Hello World shortcode plugin is 'executable'?</p>\n</blockquote>\n<p>None. You don't do this. The file with the <code>Plugin Name: HELLO WORLD PLUGIN</code> comment is your main plugin file. To load it you activate the plugin in <em>Plugins</em>. This is all described clearly in the <a href=\"https://developer.wordpress.org/plugins/plugin-basics/#how-wordpress-loads-plugins\" rel=\"nofollow noreferrer\">Plugin Handbook</a>:</p>\n<blockquote>\n<p>Now that you’re editing your new plugin’s PHP file, you’ll need to add\na plugin header comment. This is a specially formatted PHP block\ncomment that contains metadata about the plugin, such as its name,\nauthor, version, license, etc. The plugin header comment must comply\nwith the header requirements, and at the very least, contain the name\nof the plugin.</p>\n<p>Only one file in the plugin’s folder should have the header comment —\nif the plugin has multiple PHP files, only one of those files should\nhave the header comment.</p>\n<p>After you save the file, you should be able to see your plugin listed\nin your WordPress site. Log in to your WordPress site, and click\nPlugins on the left navigation pane of your WordPress Admin. This page\ndisplays a listing of all the plugins your WordPress site has. Your\nnew plugin should now be in that list!</p>\n</blockquote>\n<p>To address some of your other comments:</p>\n<blockquote>\n<p>Furthermore, when I try to Activate my plugin, I get the following error on my WP Dashboard and on the whole damn page:</p>\n<blockquote>\n<p>The plugin generated 213 characters of unexpected output during\nactivation. If you notice “headers already sent” messages, problems\nwith syndication feeds or other issues, try deactivating or removing\nthis plugin.</p>\n</blockquote>\n</blockquote>\n<p>It sounds like your plugin is missing an opening PHP tag, <code><?php</code>, so when your plugin is activated the web server is loading your code as text and printing it to the browser.</p>\n<blockquote>\n<p>if I subsequently add any code which gives an error, the page is\naffected, the whole theme is affected, the whole site is affected and\neven the whole WP Dashboard shows the error ! (Reminds me of Windows\n3.1 when a driver error crashed the whole OS. For me, the whole WP architecture sucks but I am stuck with it.) /rant</p>\n</blockquote>\n<p>If you write code with errors you will get errors. WordPress is not an operating system and plugins are not drivers. The same thing happens if you put bad code into a Laravel app, an Express.js app, or a million other frameworks. You are writing code that is running on the same server as WordPress. If that code has a fatal error in it then of course it's going to affect the rest of the site. That has nothing to do with WordPress's architecture.</p>\n"
},
{
"answer_id": 408545,
"author": "quixote",
"author_id": 224865,
"author_profile": "https://wordpress.stackexchange.com/users/224865",
"pm_score": 0,
"selected": false,
"text": "<p>I was missing the <?php at the top of the file. Thanks to all for your help !</p>\n"
}
] | 2022/08/12 | [
"https://wordpress.stackexchange.com/questions/408528",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/224865/"
] | I am an old-school embedded C programmer but a WP noob, so please bear with me.
Here is what I have done so far:-
Added a Shortcode in a Theme
============================
1. My function prints out 'Hello World' and is registered to a shortcode in the OceanWP theme, and stored here:
**> wp-content / themes / oceanwp / custom-shortcodes.php:**
```
<?php
// [helloworld]
function helloworld_func( $atts ) {
return "Hello World";
}
add_shortcode( 'helloworld', 'helloworld_func' );
```
2. I then added the shortcode to the following functions.php file:
**>wp-content / themes / oceanwp / functions.php:**
```
include ('custom-shortcodes.php');
```
3. I created a new WP Post and dropped the shortcode into it:
```
[helloworld]
```
4. **This works** BUT:
if I subsequently add any code which gives an error, the page is affected, the whole theme is affected, the whole site is affected and even the whole WP Dashboard shows the error !
(Reminds me of Windows 3.1 when a driver error crashed the whole OS. For me, the whole WP architecture sucks but I am stuck with it.)
/rant
5. I could create a child theme, but I prefer to:
Try to Add a Shortcode as a Plugin
==================================
1. So, I created a 'Hello World' plugin in the same way:
**>wp-content / plugins / hello\_world / hello\_world\_plugin.php**
```
/**
* Plugin Name: HELLO WORLD PLUGIN
*/
// [hello_world_plugin]
function hello_world_plugin_func( $atts ) {
return "Hello World Plugin";
}
add_shortcode( 'hello_world_plugin', 'hello_world_plugin_func' );
```
2. Problem is: I do not know which functions.php file I need to add the following call to:
```
include ('hello_world_plugin.php');
```
so all I am seeing on the page is:
"[hello\_world\_plugin]"
I found the following file, but it does not seem to contain any other includes:
**>wp-includes / functions.php**
None of the other plugins seem to have a functions.php file, so I am assuming that my plugin does not need its own either...Is that right?
3. Furthermore, when I try to Activate my plugin, I get the following error on my WP Dashboard and on the whole damn page:
```
The plugin generated 213 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
```
So, here are my questions:-
A) Do I need to activate my Hello World plugin? If so, do I need to call the following:
```
register_activation_hook()
```
On some tutorials, I saw similar plugin code, without any such hook...
B) In which functions.php file am I supposed to drop an include statement, so that the Hello World shortcode plugin is 'executable'?
I am sure the solution is going to be trivial (always is), but after reading through ALL the WP Dev docs (or what seems like it), I still cannot see what I am doing wrong.
Any ideas? | >
> In which functions.php file am I supposed to drop an include
> statement, so that the Hello World shortcode plugin is 'executable'?
>
>
>
None. You don't do this. The file with the `Plugin Name: HELLO WORLD PLUGIN` comment is your main plugin file. To load it you activate the plugin in *Plugins*. This is all described clearly in the [Plugin Handbook](https://developer.wordpress.org/plugins/plugin-basics/#how-wordpress-loads-plugins):
>
> Now that you’re editing your new plugin’s PHP file, you’ll need to add
> a plugin header comment. This is a specially formatted PHP block
> comment that contains metadata about the plugin, such as its name,
> author, version, license, etc. The plugin header comment must comply
> with the header requirements, and at the very least, contain the name
> of the plugin.
>
>
> Only one file in the plugin’s folder should have the header comment —
> if the plugin has multiple PHP files, only one of those files should
> have the header comment.
>
>
> After you save the file, you should be able to see your plugin listed
> in your WordPress site. Log in to your WordPress site, and click
> Plugins on the left navigation pane of your WordPress Admin. This page
> displays a listing of all the plugins your WordPress site has. Your
> new plugin should now be in that list!
>
>
>
To address some of your other comments:
>
> Furthermore, when I try to Activate my plugin, I get the following error on my WP Dashboard and on the whole damn page:
>
>
>
> >
> > The plugin generated 213 characters of unexpected output during
> > activation. If you notice “headers already sent” messages, problems
> > with syndication feeds or other issues, try deactivating or removing
> > this plugin.
> >
> >
> >
>
>
>
It sounds like your plugin is missing an opening PHP tag, `<?php`, so when your plugin is activated the web server is loading your code as text and printing it to the browser.
>
> if I subsequently add any code which gives an error, the page is
> affected, the whole theme is affected, the whole site is affected and
> even the whole WP Dashboard shows the error ! (Reminds me of Windows
> 3.1 when a driver error crashed the whole OS. For me, the whole WP architecture sucks but I am stuck with it.) /rant
>
>
>
If you write code with errors you will get errors. WordPress is not an operating system and plugins are not drivers. The same thing happens if you put bad code into a Laravel app, an Express.js app, or a million other frameworks. You are writing code that is running on the same server as WordPress. If that code has a fatal error in it then of course it's going to affect the rest of the site. That has nothing to do with WordPress's architecture. |
408,536 | <p>We have large media library with more than 300000 images.</p>
<p>We decide to delete all images < 2017 year manually using "FTP", from WP upload folder.</p>
<p>But after that in WP Admin > Media > Library, they still "exist" as <a href="https://prnt.sc/nLUFpjcy_7pS" rel="nofollow noreferrer">screenshot - broken media links in library</a></p>
<p>We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.</p>
<p>Is there any way to speed up the process, instead manually deleting it using "filter by year" and "Pagination
Number of items per page" show: 999 , where we always get "request timeout".</p>
| [
{
"answer_id": 408537,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 1,
"selected": false,
"text": "<p>Your images still exist in your Media Library because they are stored in the database, just like posts and pages. You can delete an image directly via FTP, but that doesn't magically delete its database row.</p>\n<p>Have you looked in the database yet?</p>\n<p>You have two options:</p>\n<p>(1) Open up your database directly, go to your <code>_posts</code> table, filter by <code>post_type</code> (you will need <code>attachment</code>) and bulk delete the rows from there.</p>\n<p>(2) Create a function that gets all your attachments (from 2017 and back) and delete them accordingly. You can use <code>get_posts()</code> for this. Loop through the returned array and delete them automatically by using <code>wp_delete_post()</code>.</p>\n<p>Which option to choose is up to you. When this is a one time deal and you have direct access to your database, option (1) would probably be the fastest. If you want to automatically delete all attachments older than X years, then you are better off creating a function for it.</p>\n"
},
{
"answer_id": 408538,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.</p>\n</blockquote>\n<p>If you have access to wp-cli you can try to delete attachments by <strong>year</strong> and <strong>month</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)\n</code></pre>\n<p>or just by <strong>year</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)\n</code></pre>\n<p>Remember to <strong>backup</strong> before testing!!</p>\n"
}
] | 2022/08/12 | [
"https://wordpress.stackexchange.com/questions/408536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/206699/"
] | We have large media library with more than 300000 images.
We decide to delete all images < 2017 year manually using "FTP", from WP upload folder.
But after that in WP Admin > Media > Library, they still "exist" as [screenshot - broken media links in library](https://prnt.sc/nLUFpjcy_7pS)
We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.
Is there any way to speed up the process, instead manually deleting it using "filter by year" and "Pagination
Number of items per page" show: 999 , where we always get "request timeout". | >
> We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.
>
>
>
If you have access to wp-cli you can try to delete attachments by **year** and **month** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)
```
or just by **year** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)
```
Remember to **backup** before testing!! |
408,590 | <p>edd restrict content plugin creates this shortcodes and these are working in pages and posts :</p>
<pre><code>[edd_restrict id="any"]sample restricted html or text[/edd_restrict]
</code></pre>
<p>but i want to use it in my theme not in the posts or pages. i tried this :</p>
<pre><code><?php echo do_shortcode( '[edd_restrict id="any"]' sample php '[/edd_restrict]' );?>
</code></pre>
<p>but theme shows me fatal error. so how can i use this shortcodes in wordress theme? sample text here will be a php code that i want to restrict.</p>
<p>want to put the line below between those shortcodes in my single.php in wordpress :</p>
<pre><code><li><?php if(get_post_meta($post->ID, 'download',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download',true)."' > دانلود با لینک مستقیم</a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download32',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download32',true)."'>لینک مستقیم نسخه 32bit / </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download64',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download64',true)."'>لینک مستقیم نسخه 64bit </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'downloadwin',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'downloadwin',true)."'>دانلود نسخه ویندوز </a> ";} else { echo ""; } ?></li>
</code></pre>
<p>or is this anyway to restrict custom fields in wordpress with edd content restriction? all these are custom fields that i want to restrics.</p>
| [
{
"answer_id": 408537,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 1,
"selected": false,
"text": "<p>Your images still exist in your Media Library because they are stored in the database, just like posts and pages. You can delete an image directly via FTP, but that doesn't magically delete its database row.</p>\n<p>Have you looked in the database yet?</p>\n<p>You have two options:</p>\n<p>(1) Open up your database directly, go to your <code>_posts</code> table, filter by <code>post_type</code> (you will need <code>attachment</code>) and bulk delete the rows from there.</p>\n<p>(2) Create a function that gets all your attachments (from 2017 and back) and delete them accordingly. You can use <code>get_posts()</code> for this. Loop through the returned array and delete them automatically by using <code>wp_delete_post()</code>.</p>\n<p>Which option to choose is up to you. When this is a one time deal and you have direct access to your database, option (1) would probably be the fastest. If you want to automatically delete all attachments older than X years, then you are better off creating a function for it.</p>\n"
},
{
"answer_id": 408538,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.</p>\n</blockquote>\n<p>If you have access to wp-cli you can try to delete attachments by <strong>year</strong> and <strong>month</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)\n</code></pre>\n<p>or just by <strong>year</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)\n</code></pre>\n<p>Remember to <strong>backup</strong> before testing!!</p>\n"
}
] | 2022/08/14 | [
"https://wordpress.stackexchange.com/questions/408590",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/224925/"
] | edd restrict content plugin creates this shortcodes and these are working in pages and posts :
```
[edd_restrict id="any"]sample restricted html or text[/edd_restrict]
```
but i want to use it in my theme not in the posts or pages. i tried this :
```
<?php echo do_shortcode( '[edd_restrict id="any"]' sample php '[/edd_restrict]' );?>
```
but theme shows me fatal error. so how can i use this shortcodes in wordress theme? sample text here will be a php code that i want to restrict.
want to put the line below between those shortcodes in my single.php in wordpress :
```
<li><?php if(get_post_meta($post->ID, 'download',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download',true)."' > دانلود با لینک مستقیم</a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download32',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download32',true)."'>لینک مستقیم نسخه 32bit / </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download64',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download64',true)."'>لینک مستقیم نسخه 64bit </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'downloadwin',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'downloadwin',true)."'>دانلود نسخه ویندوز </a> ";} else { echo ""; } ?></li>
```
or is this anyway to restrict custom fields in wordpress with edd content restriction? all these are custom fields that i want to restrics. | >
> We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.
>
>
>
If you have access to wp-cli you can try to delete attachments by **year** and **month** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)
```
or just by **year** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)
```
Remember to **backup** before testing!! |
408,612 | <p>I need to get the highest-level ancestor of the current page in the Block Editor.</p>
<p>I can use</p>
<pre><code>wp.data.select('core/editor').getCurrentPostAttribute('parent');
</code></pre>
<p>to get the immediate parent of the current page, but is there anything like the PHP <code>get_post_ancestors()</code> that gets all the ancestors back to the top-level page?</p>
<p>I've tried the following in the block, but this doesn't actually get the ID of the top ancestor:</p>
<pre><code>const findParent = (ancestor) => {
let ancestorData = wp
.apiFetch({ path: 'wp/v2/pages/' + ancestor })
.then((newData) => {
if (newData.parent > 0) {
while (ancestorData.parent > 0) {
wp.apiFetch({
path: 'wp/v2/pages/' + ancestorData.parent,
}).then((moreData) => {
ancestorData = moreData;
});
}
}
return ancestorData.id;
});
};
// Default (directChildren attribute is true): get children of the current page.
let ancestor = select('core/editor').getCurrentPostId();
if (false === directChildren) {
// If directChildren attribute is false, get children of the highest ancestor page.
ancestor = findParent(ancestor);
}
</code></pre>
| [
{
"answer_id": 408537,
"author": "DeltaG",
"author_id": 168537,
"author_profile": "https://wordpress.stackexchange.com/users/168537",
"pm_score": 1,
"selected": false,
"text": "<p>Your images still exist in your Media Library because they are stored in the database, just like posts and pages. You can delete an image directly via FTP, but that doesn't magically delete its database row.</p>\n<p>Have you looked in the database yet?</p>\n<p>You have two options:</p>\n<p>(1) Open up your database directly, go to your <code>_posts</code> table, filter by <code>post_type</code> (you will need <code>attachment</code>) and bulk delete the rows from there.</p>\n<p>(2) Create a function that gets all your attachments (from 2017 and back) and delete them accordingly. You can use <code>get_posts()</code> for this. Loop through the returned array and delete them automatically by using <code>wp_delete_post()</code>.</p>\n<p>Which option to choose is up to you. When this is a one time deal and you have direct access to your database, option (1) would probably be the fastest. If you want to automatically delete all attachments older than X years, then you are better off creating a function for it.</p>\n"
},
{
"answer_id": 408538,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.</p>\n</blockquote>\n<p>If you have access to wp-cli you can try to delete attachments by <strong>year</strong> and <strong>month</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)\n</code></pre>\n<p>or just by <strong>year</strong> with:</p>\n<pre><code>wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)\n</code></pre>\n<p>Remember to <strong>backup</strong> before testing!!</p>\n"
}
] | 2022/08/15 | [
"https://wordpress.stackexchange.com/questions/408612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
] | I need to get the highest-level ancestor of the current page in the Block Editor.
I can use
```
wp.data.select('core/editor').getCurrentPostAttribute('parent');
```
to get the immediate parent of the current page, but is there anything like the PHP `get_post_ancestors()` that gets all the ancestors back to the top-level page?
I've tried the following in the block, but this doesn't actually get the ID of the top ancestor:
```
const findParent = (ancestor) => {
let ancestorData = wp
.apiFetch({ path: 'wp/v2/pages/' + ancestor })
.then((newData) => {
if (newData.parent > 0) {
while (ancestorData.parent > 0) {
wp.apiFetch({
path: 'wp/v2/pages/' + ancestorData.parent,
}).then((moreData) => {
ancestorData = moreData;
});
}
}
return ancestorData.id;
});
};
// Default (directChildren attribute is true): get children of the current page.
let ancestor = select('core/editor').getCurrentPostId();
if (false === directChildren) {
// If directChildren attribute is false, get children of the highest ancestor page.
ancestor = findParent(ancestor);
}
``` | >
> We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year.
>
>
>
If you have access to wp-cli you can try to delete attachments by **year** and **month** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids)
```
or just by **year** with:
```
wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids)
```
Remember to **backup** before testing!! |
408,618 | <p>I am working on a website with 700+ pages. Most of the pages have similar keywords/slugs. Using the traditional Appearance > Menus editor is nearly impossible because I can't find the pages I am looking for (whether using Search or Most Recent or View All). I know the ID of my specific page. I know the ID of the menu I want to add it to.</p>
<p>Is there a function I can use to add a page to a menu by both of their IDs? Something like:</p>
<pre><code>$menu = 158; // THE ID OF MY MENU
$menu_item = 15891; // THE ID OF MY PAGE
$adding = wp_please_add_a_menu_item_to_menu($menu, $menu_item);
if($adding) {
echo 'Adding menu item worked!';
} else {
echo 'Adding menu item failed.';
}
</code></pre>
| [
{
"answer_id": 408620,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/\" rel=\"nofollow noreferrer\"><code>wp_update_nav_menu_item()</code></a> to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Insert a new navigation menu item for a page into the database.\n *\n * @link https://wordpress.stackexchange.com/questions/408618\n *\n * @param int $menu_id The ID of the menu to insert the new item into.\n * @param int|WP_Post|null $page A reference to the page for which to create a new menu item.\n * @param string $title The title of the nav item. Defaults to the page title.\n * @param int $parent The ID of the parent nav menu item, if applicable.\n * @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.\n * @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.\n **/\nfunction wpse408618_insert_nav_menu_page_item(\n $menu_id,\n $page,\n $title = null,\n $parent = 0,\n $position = 0\n) {\n $page = get_post( $page );\n\n if( !$page || $page->post_type !== 'page' )\n return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );\n\n $menu_item_data = array(\n 'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post-type',\n 'menu-item-parent-id' => $parent,\n 'menu-item-position' => $position,\n );\n\n return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );\n\nif( is_wp_error( $new_item_id ) )\n echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';\nelse\n echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;\n</code></pre>\n<p>You can refer to <a href=\"https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440\" rel=\"nofollow noreferrer\">the source of the <code>wp_update_nav_menu_item()</code> function</a> for a more complete list of possible nav menu item object attributes.</p>\n<p>It's also possible to use a hook such as the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items</code> filter</a> to add non-persistent items on the fly, if it makes more sense for your application.</p>\n"
},
{
"answer_id": 408623,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 1,
"selected": false,
"text": "<p>Based on @bosco response, I was able to make a simple PHP file outside of my Wordpress application, call <code>wp-load</code> to use Wordpress functions, and add the menu item using that function:</p>\n<pre><code>define( 'WP_USE_THEMES', false ); \nrequire( '../../../../wp-load.php' ); //YOUR FILE PATH MAY VARY\n\n$menu = 158; // ID OF YOUR MENU\n$menu_item = 15891; // ID OF THE PAGE YOU WANT TO ADD\n\n$page = get_post($menu_item); \n$title = get_the_title($page);\nwp_update_nav_menu_item($menu, 0, array(\n 'menu-item-title' => $title,\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post_type',\n));\n</code></pre>\n<p>The key to this <code>wp_update_nav_menu_item</code> function is the 2nd argument:</p>\n<blockquote>\n<p>$menu_item_db_id (int) (Required) The ID of the menu item. If 0,\ncreates a new menu item.</p>\n</blockquote>\n"
}
] | 2022/08/15 | [
"https://wordpress.stackexchange.com/questions/408618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12294/"
] | I am working on a website with 700+ pages. Most of the pages have similar keywords/slugs. Using the traditional Appearance > Menus editor is nearly impossible because I can't find the pages I am looking for (whether using Search or Most Recent or View All). I know the ID of my specific page. I know the ID of the menu I want to add it to.
Is there a function I can use to add a page to a menu by both of their IDs? Something like:
```
$menu = 158; // THE ID OF MY MENU
$menu_item = 15891; // THE ID OF MY PAGE
$adding = wp_please_add_a_menu_item_to_menu($menu, $menu_item);
if($adding) {
echo 'Adding menu item worked!';
} else {
echo 'Adding menu item failed.';
}
``` | You can use [`wp_update_nav_menu_item()`](https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/) to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.
```php
/**
* Insert a new navigation menu item for a page into the database.
*
* @link https://wordpress.stackexchange.com/questions/408618
*
* @param int $menu_id The ID of the menu to insert the new item into.
* @param int|WP_Post|null $page A reference to the page for which to create a new menu item.
* @param string $title The title of the nav item. Defaults to the page title.
* @param int $parent The ID of the parent nav menu item, if applicable.
* @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.
* @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.
**/
function wpse408618_insert_nav_menu_page_item(
$menu_id,
$page,
$title = null,
$parent = 0,
$position = 0
) {
$page = get_post( $page );
if( !$page || $page->post_type !== 'page' )
return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );
$menu_item_data = array(
'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),
'menu-item-object-id' => $page->ID,
'menu-item-object' => 'page',
'menu-item-status' => 'publish',
'menu-item-type' => 'post-type',
'menu-item-parent-id' => $parent,
'menu-item-position' => $position,
);
return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );
}
```
```php
$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );
if( is_wp_error( $new_item_id ) )
echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';
else
echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;
```
You can refer to [the source of the `wp_update_nav_menu_item()` function](https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440) for a more complete list of possible nav menu item object attributes.
It's also possible to use a hook such as the [`wp_get_nav_menu_items` filter](https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/) to add non-persistent items on the fly, if it makes more sense for your application. |
408,667 | <p>I have a code in my <code>functions.php</code> and I would like to use <code>wp_dropdown_categories</code> for displaying list product categories but I wont in "select" only "checkbox".</p>
<p>I edited my code in <code>functions.php</code> and it looks like this now:</p>
<pre class="lang-php prettyprint-override"><code>class List_Categories_Radiobuttons extends Walker_Category {
function start_el(&$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
$category_name = esc_attr( $category->name );
$radiobutton = '<input class="form-check-input" type="checkbox" value="' . $category_name . '" id="flexCheckDefault' . $category_name . '"><label class="form-check-label" for="flexCheckDefault' . $category_name . '">' . $category_name . '</label>';
$output .= '<span class="form-check">'.$radiobutton.'</span>';
}
function end_el(&$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
$output .= '';
}
}
</code></pre>
<p>and I add code in my template</p>
<pre><code><?php
$args = array(
'taxonomy' => 'pa_rozmiar',
'name' => 'pa_rozmiar',
'value_field' => 'slug',
'class' => 'd-none form-check',
'walker' => new List_Categories_Radiobuttons
);
wp_dropdown_categories( $args );
?>
</code></pre>
<p>I have a problem because the first position is outside my markers <code>span</code>. Where I am making a mistake?</p>
| [
{
"answer_id": 408620,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/\" rel=\"nofollow noreferrer\"><code>wp_update_nav_menu_item()</code></a> to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Insert a new navigation menu item for a page into the database.\n *\n * @link https://wordpress.stackexchange.com/questions/408618\n *\n * @param int $menu_id The ID of the menu to insert the new item into.\n * @param int|WP_Post|null $page A reference to the page for which to create a new menu item.\n * @param string $title The title of the nav item. Defaults to the page title.\n * @param int $parent The ID of the parent nav menu item, if applicable.\n * @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.\n * @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.\n **/\nfunction wpse408618_insert_nav_menu_page_item(\n $menu_id,\n $page,\n $title = null,\n $parent = 0,\n $position = 0\n) {\n $page = get_post( $page );\n\n if( !$page || $page->post_type !== 'page' )\n return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );\n\n $menu_item_data = array(\n 'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post-type',\n 'menu-item-parent-id' => $parent,\n 'menu-item-position' => $position,\n );\n\n return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );\n\nif( is_wp_error( $new_item_id ) )\n echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';\nelse\n echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;\n</code></pre>\n<p>You can refer to <a href=\"https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440\" rel=\"nofollow noreferrer\">the source of the <code>wp_update_nav_menu_item()</code> function</a> for a more complete list of possible nav menu item object attributes.</p>\n<p>It's also possible to use a hook such as the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items</code> filter</a> to add non-persistent items on the fly, if it makes more sense for your application.</p>\n"
},
{
"answer_id": 408623,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 1,
"selected": false,
"text": "<p>Based on @bosco response, I was able to make a simple PHP file outside of my Wordpress application, call <code>wp-load</code> to use Wordpress functions, and add the menu item using that function:</p>\n<pre><code>define( 'WP_USE_THEMES', false ); \nrequire( '../../../../wp-load.php' ); //YOUR FILE PATH MAY VARY\n\n$menu = 158; // ID OF YOUR MENU\n$menu_item = 15891; // ID OF THE PAGE YOU WANT TO ADD\n\n$page = get_post($menu_item); \n$title = get_the_title($page);\nwp_update_nav_menu_item($menu, 0, array(\n 'menu-item-title' => $title,\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post_type',\n));\n</code></pre>\n<p>The key to this <code>wp_update_nav_menu_item</code> function is the 2nd argument:</p>\n<blockquote>\n<p>$menu_item_db_id (int) (Required) The ID of the menu item. If 0,\ncreates a new menu item.</p>\n</blockquote>\n"
}
] | 2022/08/16 | [
"https://wordpress.stackexchange.com/questions/408667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/203605/"
] | I have a code in my `functions.php` and I would like to use `wp_dropdown_categories` for displaying list product categories but I wont in "select" only "checkbox".
I edited my code in `functions.php` and it looks like this now:
```php
class List_Categories_Radiobuttons extends Walker_Category {
function start_el(&$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
$category_name = esc_attr( $category->name );
$radiobutton = '<input class="form-check-input" type="checkbox" value="' . $category_name . '" id="flexCheckDefault' . $category_name . '"><label class="form-check-label" for="flexCheckDefault' . $category_name . '">' . $category_name . '</label>';
$output .= '<span class="form-check">'.$radiobutton.'</span>';
}
function end_el(&$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
$output .= '';
}
}
```
and I add code in my template
```
<?php
$args = array(
'taxonomy' => 'pa_rozmiar',
'name' => 'pa_rozmiar',
'value_field' => 'slug',
'class' => 'd-none form-check',
'walker' => new List_Categories_Radiobuttons
);
wp_dropdown_categories( $args );
?>
```
I have a problem because the first position is outside my markers `span`. Where I am making a mistake? | You can use [`wp_update_nav_menu_item()`](https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/) to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.
```php
/**
* Insert a new navigation menu item for a page into the database.
*
* @link https://wordpress.stackexchange.com/questions/408618
*
* @param int $menu_id The ID of the menu to insert the new item into.
* @param int|WP_Post|null $page A reference to the page for which to create a new menu item.
* @param string $title The title of the nav item. Defaults to the page title.
* @param int $parent The ID of the parent nav menu item, if applicable.
* @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.
* @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.
**/
function wpse408618_insert_nav_menu_page_item(
$menu_id,
$page,
$title = null,
$parent = 0,
$position = 0
) {
$page = get_post( $page );
if( !$page || $page->post_type !== 'page' )
return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );
$menu_item_data = array(
'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),
'menu-item-object-id' => $page->ID,
'menu-item-object' => 'page',
'menu-item-status' => 'publish',
'menu-item-type' => 'post-type',
'menu-item-parent-id' => $parent,
'menu-item-position' => $position,
);
return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );
}
```
```php
$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );
if( is_wp_error( $new_item_id ) )
echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';
else
echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;
```
You can refer to [the source of the `wp_update_nav_menu_item()` function](https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440) for a more complete list of possible nav menu item object attributes.
It's also possible to use a hook such as the [`wp_get_nav_menu_items` filter](https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/) to add non-persistent items on the fly, if it makes more sense for your application. |
408,779 | <p>We need to set posts to draft or to not be created if the_content contains certain words.</p>
<p>This is not something needed on current posts, it is needed on users who publish posts going forward. As an example, if users post a recipe and they have the words "word1" and "word2" within the content area, the post should not be published but set to draft.</p>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 408620,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/\" rel=\"nofollow noreferrer\"><code>wp_update_nav_menu_item()</code></a> to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Insert a new navigation menu item for a page into the database.\n *\n * @link https://wordpress.stackexchange.com/questions/408618\n *\n * @param int $menu_id The ID of the menu to insert the new item into.\n * @param int|WP_Post|null $page A reference to the page for which to create a new menu item.\n * @param string $title The title of the nav item. Defaults to the page title.\n * @param int $parent The ID of the parent nav menu item, if applicable.\n * @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.\n * @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.\n **/\nfunction wpse408618_insert_nav_menu_page_item(\n $menu_id,\n $page,\n $title = null,\n $parent = 0,\n $position = 0\n) {\n $page = get_post( $page );\n\n if( !$page || $page->post_type !== 'page' )\n return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );\n\n $menu_item_data = array(\n 'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post-type',\n 'menu-item-parent-id' => $parent,\n 'menu-item-position' => $position,\n );\n\n return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );\n\nif( is_wp_error( $new_item_id ) )\n echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';\nelse\n echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;\n</code></pre>\n<p>You can refer to <a href=\"https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440\" rel=\"nofollow noreferrer\">the source of the <code>wp_update_nav_menu_item()</code> function</a> for a more complete list of possible nav menu item object attributes.</p>\n<p>It's also possible to use a hook such as the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items</code> filter</a> to add non-persistent items on the fly, if it makes more sense for your application.</p>\n"
},
{
"answer_id": 408623,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 1,
"selected": false,
"text": "<p>Based on @bosco response, I was able to make a simple PHP file outside of my Wordpress application, call <code>wp-load</code> to use Wordpress functions, and add the menu item using that function:</p>\n<pre><code>define( 'WP_USE_THEMES', false ); \nrequire( '../../../../wp-load.php' ); //YOUR FILE PATH MAY VARY\n\n$menu = 158; // ID OF YOUR MENU\n$menu_item = 15891; // ID OF THE PAGE YOU WANT TO ADD\n\n$page = get_post($menu_item); \n$title = get_the_title($page);\nwp_update_nav_menu_item($menu, 0, array(\n 'menu-item-title' => $title,\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post_type',\n));\n</code></pre>\n<p>The key to this <code>wp_update_nav_menu_item</code> function is the 2nd argument:</p>\n<blockquote>\n<p>$menu_item_db_id (int) (Required) The ID of the menu item. If 0,\ncreates a new menu item.</p>\n</blockquote>\n"
}
] | 2022/08/19 | [
"https://wordpress.stackexchange.com/questions/408779",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225083/"
] | We need to set posts to draft or to not be created if the\_content contains certain words.
This is not something needed on current posts, it is needed on users who publish posts going forward. As an example, if users post a recipe and they have the words "word1" and "word2" within the content area, the post should not be published but set to draft.
Any help would be greatly appreciated. | You can use [`wp_update_nav_menu_item()`](https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/) to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.
```php
/**
* Insert a new navigation menu item for a page into the database.
*
* @link https://wordpress.stackexchange.com/questions/408618
*
* @param int $menu_id The ID of the menu to insert the new item into.
* @param int|WP_Post|null $page A reference to the page for which to create a new menu item.
* @param string $title The title of the nav item. Defaults to the page title.
* @param int $parent The ID of the parent nav menu item, if applicable.
* @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.
* @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.
**/
function wpse408618_insert_nav_menu_page_item(
$menu_id,
$page,
$title = null,
$parent = 0,
$position = 0
) {
$page = get_post( $page );
if( !$page || $page->post_type !== 'page' )
return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );
$menu_item_data = array(
'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),
'menu-item-object-id' => $page->ID,
'menu-item-object' => 'page',
'menu-item-status' => 'publish',
'menu-item-type' => 'post-type',
'menu-item-parent-id' => $parent,
'menu-item-position' => $position,
);
return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );
}
```
```php
$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );
if( is_wp_error( $new_item_id ) )
echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';
else
echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;
```
You can refer to [the source of the `wp_update_nav_menu_item()` function](https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440) for a more complete list of possible nav menu item object attributes.
It's also possible to use a hook such as the [`wp_get_nav_menu_items` filter](https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/) to add non-persistent items on the fly, if it makes more sense for your application. |
408,832 | <p>I'm trying to prevent a post from being published if it contains certain words using the folowing:</p>
<pre><code>function jhnppWord($content)
{
global $post;
$content = $post->post_content;
$words = 'word1';
if (strpos($content, '$words') !== false )
wp_die( __('Your post contains words that we do not allow. Please remove them and try again.') );
}
add_action('publish_post', 'jhnppWord');
</code></pre>
<p>With this, it either blocks any word you type or nothing at all, what am I missing?</p>
<p>How can I add multiple words to $words?</p>
| [
{
"answer_id": 408620,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/\" rel=\"nofollow noreferrer\"><code>wp_update_nav_menu_item()</code></a> to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Insert a new navigation menu item for a page into the database.\n *\n * @link https://wordpress.stackexchange.com/questions/408618\n *\n * @param int $menu_id The ID of the menu to insert the new item into.\n * @param int|WP_Post|null $page A reference to the page for which to create a new menu item.\n * @param string $title The title of the nav item. Defaults to the page title.\n * @param int $parent The ID of the parent nav menu item, if applicable.\n * @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.\n * @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.\n **/\nfunction wpse408618_insert_nav_menu_page_item(\n $menu_id,\n $page,\n $title = null,\n $parent = 0,\n $position = 0\n) {\n $page = get_post( $page );\n\n if( !$page || $page->post_type !== 'page' )\n return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );\n\n $menu_item_data = array(\n 'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post-type',\n 'menu-item-parent-id' => $parent,\n 'menu-item-position' => $position,\n );\n\n return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );\n\nif( is_wp_error( $new_item_id ) )\n echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';\nelse\n echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;\n</code></pre>\n<p>You can refer to <a href=\"https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440\" rel=\"nofollow noreferrer\">the source of the <code>wp_update_nav_menu_item()</code> function</a> for a more complete list of possible nav menu item object attributes.</p>\n<p>It's also possible to use a hook such as the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items</code> filter</a> to add non-persistent items on the fly, if it makes more sense for your application.</p>\n"
},
{
"answer_id": 408623,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 1,
"selected": false,
"text": "<p>Based on @bosco response, I was able to make a simple PHP file outside of my Wordpress application, call <code>wp-load</code> to use Wordpress functions, and add the menu item using that function:</p>\n<pre><code>define( 'WP_USE_THEMES', false ); \nrequire( '../../../../wp-load.php' ); //YOUR FILE PATH MAY VARY\n\n$menu = 158; // ID OF YOUR MENU\n$menu_item = 15891; // ID OF THE PAGE YOU WANT TO ADD\n\n$page = get_post($menu_item); \n$title = get_the_title($page);\nwp_update_nav_menu_item($menu, 0, array(\n 'menu-item-title' => $title,\n 'menu-item-object-id' => $page->ID,\n 'menu-item-object' => 'page',\n 'menu-item-status' => 'publish',\n 'menu-item-type' => 'post_type',\n));\n</code></pre>\n<p>The key to this <code>wp_update_nav_menu_item</code> function is the 2nd argument:</p>\n<blockquote>\n<p>$menu_item_db_id (int) (Required) The ID of the menu item. If 0,\ncreates a new menu item.</p>\n</blockquote>\n"
}
] | 2022/08/22 | [
"https://wordpress.stackexchange.com/questions/408832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225083/"
] | I'm trying to prevent a post from being published if it contains certain words using the folowing:
```
function jhnppWord($content)
{
global $post;
$content = $post->post_content;
$words = 'word1';
if (strpos($content, '$words') !== false )
wp_die( __('Your post contains words that we do not allow. Please remove them and try again.') );
}
add_action('publish_post', 'jhnppWord');
```
With this, it either blocks any word you type or nothing at all, what am I missing?
How can I add multiple words to $words? | You can use [`wp_update_nav_menu_item()`](https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/) to programmatically add a new menu item to the database. Since this change persists, you shouldn't execute this functionality on every page - it's best used as a one-off (though in that case it might be easier and more efficient to use WP CLI as suggested by WebElaine in the comments), or via some dashboard interaction if it's something you intend to use repeatedly.
```php
/**
* Insert a new navigation menu item for a page into the database.
*
* @link https://wordpress.stackexchange.com/questions/408618
*
* @param int $menu_id The ID of the menu to insert the new item into.
* @param int|WP_Post|null $page A reference to the page for which to create a new menu item.
* @param string $title The title of the nav item. Defaults to the page title.
* @param int $parent The ID of the parent nav menu item, if applicable.
* @param int $position The index within the menu/parent for the new item. Defaults to 0 to append.
* @return int|WP_Error The ID of the new menu item on success, or a WP_Error object on failure.
**/
function wpse408618_insert_nav_menu_page_item(
$menu_id,
$page,
$title = null,
$parent = 0,
$position = 0
) {
$page = get_post( $page );
if( !$page || $page->post_type !== 'page' )
return new WP_Error( 'wpse408618_invalid_page_arg', 'The supplied $page argument could not be resolved to a page-type post.' );
$menu_item_data = array(
'menu-item-title' => isset( $title ) ? $title : get_the_title( $page ),
'menu-item-object-id' => $page->ID,
'menu-item-object' => 'page',
'menu-item-status' => 'publish',
'menu-item-type' => 'post-type',
'menu-item-parent-id' => $parent,
'menu-item-position' => $position,
);
return wp_update_nav_menu_item( $menu_id, 0, $menu_item_data );
}
```
```php
$new_item_id = wpse408618_insert_nav_menu_page_item( 158, 15891 );
if( is_wp_error( $new_item_id ) )
echo 'Page nav menu item creation failed: "' . $new_item_id->get_error_message() . '"';
else
echo 'Page nav menu item creation succeeded! Item inserted with ID ' . $new_item_id;
```
You can refer to [the source of the `wp_update_nav_menu_item()` function](https://github.com/WordPress/wordpress-develop/blob/6.0/src/wp-includes/nav-menu.php#L440) for a more complete list of possible nav menu item object attributes.
It's also possible to use a hook such as the [`wp_get_nav_menu_items` filter](https://developer.wordpress.org/reference/hooks/wp_get_nav_menu_items/) to add non-persistent items on the fly, if it makes more sense for your application. |
408,860 | <p>I'm using <code>isSelected</code> to determine if a block is selected, but I'd also like to know if any innerblocks are selected.</p>
<p>I'm using <code>export default function Edit({ isSelected }) {}</code></p>
<p>I believe this is done with <code>useSelect</code> but I'm not sure how that works.</p>
| [
{
"answer_id": 408862,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>If you only need to know whether or not an inner-block is selected, you can leverage the <code>core/block-editor</code> store's <a href=\"https://developer.wordpress.org/block-editor/reference-guides/data/data-core-block-editor/#hasselectedinnerblock\" rel=\"nofollow noreferrer\"><code>hasSelectedInnerBlock()</code> selector</a>. For example, if using a <code>useSelect()</code> hook in a functional component, that might look as such:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { useSelect } from '@wordpress/data';\n\nexport default function Edit( { isSelected, clientId } ) {\n const is_inner_block_selected = useSelect(\n ( select ) => select( 'core/block-editor' ).hasSelectedInnerBlock( clientId )\n );\n\n // ...\n}\n</code></pre>\n<p>After which you might use a simple <code>isSelected || is_inner_block_selected</code> condition to execute your specific functionality - or some other hook with with a <code>[ isSelected, is_inner_block_selected ]</code> dependency.</p>\n<p>Of particular note, you can set the second argument of <code>hasSelectedInnerBlock()</code> to <code>true</code> for a deep check - that is, if you wish to know if <em>any descendant</em> is selected (in cases where you would like to know if the inner blocks themselves may have inner blocks which are selected):</p>\n<pre class=\"lang-js prettyprint-override\"><code>select( 'core/block-editor' ).hasSelectedInnerBlock( clientId, true )\n</code></pre>\n"
},
{
"answer_id": 410392,
"author": "Tomas Mulder",
"author_id": 160622,
"author_profile": "https://wordpress.stackexchange.com/users/160622",
"pm_score": 1,
"selected": false,
"text": "<p>I think @Elizabeth was trying to determine if a child block is selected <em>and also</em> if the block itself is selected. If so, building off of @bosco's example, you can create a utility function, like:</p>\n<pre><code>// in a file named useIsSelectedOrChild.js:\n\n/**\n * Self or Child Selected\n *\n * This is essentially isSelected, extended to include if a child\n * block is selected.\n */\nimport { useSelect } from '@wordpress/data';\n\nconst useIsSelectedOrChild = (clientId, isSelected = null) => {\n let isSelectedOrChild = useSelect((select) =>\n select('core/block-editor').hasSelectedInnerBlock(clientId)\n );\n if (!isSelectedOrChild && isSelected !== null) {\n isSelectedOrChild = isSelected;\n }\n return isSelectedOrChild;\n};\n\nexport default useIsSelectedOrChild;\n</code></pre>\n<p>Then you can simply import it into any blocks you want and reuse it:</p>\n<pre><code>import useIsSelectedOrChild from 'useIsSelectedOrChild';\n\nexport default function edit( { clientId, isSelected } ) {\n const isSelectedOrChild = useIsSelectedOrChild(clientId, isSelected);\n return (\n <div>Myself or a child is {isSelectedOrChild ? 'selected' : 'deselected'}</div>\n )\n}\n</code></pre>\n"
}
] | 2022/08/22 | [
"https://wordpress.stackexchange.com/questions/408860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120585/"
] | I'm using `isSelected` to determine if a block is selected, but I'd also like to know if any innerblocks are selected.
I'm using `export default function Edit({ isSelected }) {}`
I believe this is done with `useSelect` but I'm not sure how that works. | If you only need to know whether or not an inner-block is selected, you can leverage the `core/block-editor` store's [`hasSelectedInnerBlock()` selector](https://developer.wordpress.org/block-editor/reference-guides/data/data-core-block-editor/#hasselectedinnerblock). For example, if using a `useSelect()` hook in a functional component, that might look as such:
```js
import { useSelect } from '@wordpress/data';
export default function Edit( { isSelected, clientId } ) {
const is_inner_block_selected = useSelect(
( select ) => select( 'core/block-editor' ).hasSelectedInnerBlock( clientId )
);
// ...
}
```
After which you might use a simple `isSelected || is_inner_block_selected` condition to execute your specific functionality - or some other hook with with a `[ isSelected, is_inner_block_selected ]` dependency.
Of particular note, you can set the second argument of `hasSelectedInnerBlock()` to `true` for a deep check - that is, if you wish to know if *any descendant* is selected (in cases where you would like to know if the inner blocks themselves may have inner blocks which are selected):
```js
select( 'core/block-editor' ).hasSelectedInnerBlock( clientId, true )
``` |
408,888 | <p>I created an additional description field for categories, but what I write in html is saved in MSQL without html, how can I add HTML support to this field?</p>
<p>For example, I write a statement like this:</p>
<p><code><div class="class-name">It's very hot these days</div></code></p>
<p>I am looking at phpmyadmin and the only saved is "It's very hot today". Since only the text part is saved, the table, image, title.. etc none appear when I add it. I can't even make it <b>thick</b>.</p>
<p>Codes;</p>
<pre><code>/* Custom Field for Categories */
function dm_category_fields($term) {
if (current_filter() == 'category_edit_form_fields') {
$bottom_description = get_term_meta($term->term_id, 'bottom_description', true);
?>
<tr class="form-field">
<th valign="top" scope="row"><label for="term_fields[bottom_description]"><?php _e('Sayfa Sonu Açıklaması'); ?></label></th>
<td>
<textarea class="large-text" cols="50" rows="10" id="term_fields[bottom_description]" name="term_fields[bottom_description]"><?php echo esc_textarea($bottom_description); ?></textarea><br/>
<span class="description"><?php _e('Kategori içeriğinin sonuna bir şeyler eklemek için. Shortcode destekler.'); ?></span>
</td>
</tr>
<?php } elseif (current_filter() == 'category_add_form_fields') {
?>
<div class="form-field">
<label for="term_fields[bottom_description]"><?php _e('Sayfa Sonu Açıklaması'); ?></label>
<textarea cols="40" rows="10" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>
<p class="description"><?php _e('Kategori içeriğinin sonuna bir şeyler eklemek için. Shortcode destekler.'); ?></p>
</div>
<?php
}
}
add_action('category_add_form_fields', 'dm_category_fields', 10, 2);
add_action('category_edit_form_fields', 'dm_category_fields', 10, 2);
function wcr_save_category_fields($term_id) {
if (!isset($_POST['term_fields'])) {
return;
}
foreach ($_POST['term_fields'] as $key => $value) {
update_term_meta($term_id, $key, sanitize_text_field($value));
}
}
add_action('edited_category', 'wcr_save_category_fields', 10, 2);
add_action('create_category', 'wcr_save_category_fields', 10, 2);
</code></pre>
| [
{
"answer_id": 408892,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\"><code>sanitize_text_field()</code></a> is intended to sanitize a value for use as plain-text. HTML tags are stripped in the process.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\"><code>wp_kses()</code></a> may be a more appropriate sanitization helper for your use-case and can be passed a custom list of permitted HTML tags. Alternately, you can pass a context name to use a pre-defined set. To use the list which is used in the process of sanitizing post content, for instance:</p>\n<pre class=\"lang-php prettyprint-override\"><code>update_term_meta( $term_id, $key, wp_kses( $value, 'post' ) );\n</code></pre>\n<p>See the <a href=\"https://developer.wordpress.org/themes/theme-security/\" rel=\"nofollow noreferrer\">Theme Security</a> section of the <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">Theme Handbook</a> for more information on <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">Data Sanitization/Escaping</a> in WordPress.</p>\n"
},
{
"answer_id": 409040,
"author": "Murat Dinc",
"author_id": 161959,
"author_profile": "https://wordpress.stackexchange.com/users/161959",
"pm_score": 1,
"selected": true,
"text": "<p>I solved the problem, the codes that work are as follows;</p>\n<pre><code>/* Custom Field for Categories */\nfunction dm_category_fields($term) {\n if (current_filter() == 'category_edit_form_fields') {\n $bottom_description = get_term_meta($term->term_id, 'bottom_description', true);\n $description_field = 'bottom-description';\n $description_args = array(\n 'wpautop' => false,\n 'media_buttons' => true,\n 'textarea_rows' => 10,\n 'textarea_name' => 'term_fields[bottom_description]'\n );\n ?>\n <tr class="bottom-form-field">\n <th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>\n <td>\n <?php wp_editor( $bottom_description, $description_field, $description_args ); ?>\n <span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>\n </td>\n </tr>\n <?php\n } elseif ( current_filter() == 'category_add_form_fields' ) {\n ?>\n <div class="bottom-form-field">\n <label><?php _e('Page Break Description'); ?></label>\n <textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>\n <p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>\n </div>\n <?php\n }\n}\nadd_action('category_edit_form_fields', 'dm_category_fields', 10, 2);\nadd_action('category_add_form_fields', 'dm_category_fields', 10, 2);\nfunction dm_save_category_fields($term_id) {\n if (!isset($_POST['term_fields'])) {\n return;\n }\n foreach ($_POST['term_fields'] as $key => $value) {\n update_term_meta($term_id, $key, $value);\n }\n}\nadd_action('edited_category', 'dm_save_category_fields', 10, 2);\nadd_action('create_category', 'dm_save_category_fields', 10, 2);\n</code></pre>\n"
}
] | 2022/08/23 | [
"https://wordpress.stackexchange.com/questions/408888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161959/"
] | I created an additional description field for categories, but what I write in html is saved in MSQL without html, how can I add HTML support to this field?
For example, I write a statement like this:
`<div class="class-name">It's very hot these days</div>`
I am looking at phpmyadmin and the only saved is "It's very hot today". Since only the text part is saved, the table, image, title.. etc none appear when I add it. I can't even make it **thick**.
Codes;
```
/* Custom Field for Categories */
function dm_category_fields($term) {
if (current_filter() == 'category_edit_form_fields') {
$bottom_description = get_term_meta($term->term_id, 'bottom_description', true);
?>
<tr class="form-field">
<th valign="top" scope="row"><label for="term_fields[bottom_description]"><?php _e('Sayfa Sonu Açıklaması'); ?></label></th>
<td>
<textarea class="large-text" cols="50" rows="10" id="term_fields[bottom_description]" name="term_fields[bottom_description]"><?php echo esc_textarea($bottom_description); ?></textarea><br/>
<span class="description"><?php _e('Kategori içeriğinin sonuna bir şeyler eklemek için. Shortcode destekler.'); ?></span>
</td>
</tr>
<?php } elseif (current_filter() == 'category_add_form_fields') {
?>
<div class="form-field">
<label for="term_fields[bottom_description]"><?php _e('Sayfa Sonu Açıklaması'); ?></label>
<textarea cols="40" rows="10" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>
<p class="description"><?php _e('Kategori içeriğinin sonuna bir şeyler eklemek için. Shortcode destekler.'); ?></p>
</div>
<?php
}
}
add_action('category_add_form_fields', 'dm_category_fields', 10, 2);
add_action('category_edit_form_fields', 'dm_category_fields', 10, 2);
function wcr_save_category_fields($term_id) {
if (!isset($_POST['term_fields'])) {
return;
}
foreach ($_POST['term_fields'] as $key => $value) {
update_term_meta($term_id, $key, sanitize_text_field($value));
}
}
add_action('edited_category', 'wcr_save_category_fields', 10, 2);
add_action('create_category', 'wcr_save_category_fields', 10, 2);
``` | I solved the problem, the codes that work are as follows;
```
/* Custom Field for Categories */
function dm_category_fields($term) {
if (current_filter() == 'category_edit_form_fields') {
$bottom_description = get_term_meta($term->term_id, 'bottom_description', true);
$description_field = 'bottom-description';
$description_args = array(
'wpautop' => false,
'media_buttons' => true,
'textarea_rows' => 10,
'textarea_name' => 'term_fields[bottom_description]'
);
?>
<tr class="bottom-form-field">
<th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>
<td>
<?php wp_editor( $bottom_description, $description_field, $description_args ); ?>
<span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>
</td>
</tr>
<?php
} elseif ( current_filter() == 'category_add_form_fields' ) {
?>
<div class="bottom-form-field">
<label><?php _e('Page Break Description'); ?></label>
<textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>
<p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>
</div>
<?php
}
}
add_action('category_edit_form_fields', 'dm_category_fields', 10, 2);
add_action('category_add_form_fields', 'dm_category_fields', 10, 2);
function dm_save_category_fields($term_id) {
if (!isset($_POST['term_fields'])) {
return;
}
foreach ($_POST['term_fields'] as $key => $value) {
update_term_meta($term_id, $key, $value);
}
}
add_action('edited_category', 'dm_save_category_fields', 10, 2);
add_action('create_category', 'dm_save_category_fields', 10, 2);
``` |
409,095 | <p>I'm struggling to understand how I can use <code>pre_get_post</code> when the post's metadata is not stored in the wp_postmeta table. I use Pods (<a href="https://pods.io" rel="nofollow noreferrer">https://pods.io</a>) to create custom post types with custom fields, stored using the plugins <em>Table Storage</em> option.</p>
<p>My desired outcome is to use <code>orderby</code> on the <code>meta_value</code> stored in the custom <code>xyz_custom_table</code> table.</p>
<p>The following <code>xyz_order_post_by_meta</code> function is how I would do this with posts that store metadata in the wp_postmeta table. But this will not work with custom database tables.</p>
<pre><code>function xyz_order_post_by_meta($query)
{
if (
$query->is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive("xyz_cpt")
) {
$query->set("meta_key", "xyz_custom_meta");
$query->set("orderby", "meta_value");
$query->set("order", "ASC");
}
}
add_action("pre_get_posts", "xyz_order_post_by_meta", 9999);
</code></pre>
<p>Am I right in thinking I need to run a custom SQL query to get the value for <code>meta_value</code> to include in the above? If so, how would I write this? I've tried the following, which returns a list of the <code>meta_value</code> for each post. But I'm not sure how to write this as the array I think I need for <code>$query->set("orderby", "meta_value");</code> to give me the desired outcome?</p>
<pre><code>global $wpdb;
$table_name = "xyz_custom_table";
$retrieve_data = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($retrieve_data as $retrieved_data) {
echo $retrieved_data->xyz_custom_meta;
}
</code></pre>
| [
{
"answer_id": 408892,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\"><code>sanitize_text_field()</code></a> is intended to sanitize a value for use as plain-text. HTML tags are stripped in the process.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\"><code>wp_kses()</code></a> may be a more appropriate sanitization helper for your use-case and can be passed a custom list of permitted HTML tags. Alternately, you can pass a context name to use a pre-defined set. To use the list which is used in the process of sanitizing post content, for instance:</p>\n<pre class=\"lang-php prettyprint-override\"><code>update_term_meta( $term_id, $key, wp_kses( $value, 'post' ) );\n</code></pre>\n<p>See the <a href=\"https://developer.wordpress.org/themes/theme-security/\" rel=\"nofollow noreferrer\">Theme Security</a> section of the <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">Theme Handbook</a> for more information on <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">Data Sanitization/Escaping</a> in WordPress.</p>\n"
},
{
"answer_id": 409040,
"author": "Murat Dinc",
"author_id": 161959,
"author_profile": "https://wordpress.stackexchange.com/users/161959",
"pm_score": 1,
"selected": true,
"text": "<p>I solved the problem, the codes that work are as follows;</p>\n<pre><code>/* Custom Field for Categories */\nfunction dm_category_fields($term) {\n if (current_filter() == 'category_edit_form_fields') {\n $bottom_description = get_term_meta($term->term_id, 'bottom_description', true);\n $description_field = 'bottom-description';\n $description_args = array(\n 'wpautop' => false,\n 'media_buttons' => true,\n 'textarea_rows' => 10,\n 'textarea_name' => 'term_fields[bottom_description]'\n );\n ?>\n <tr class="bottom-form-field">\n <th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>\n <td>\n <?php wp_editor( $bottom_description, $description_field, $description_args ); ?>\n <span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>\n </td>\n </tr>\n <?php\n } elseif ( current_filter() == 'category_add_form_fields' ) {\n ?>\n <div class="bottom-form-field">\n <label><?php _e('Page Break Description'); ?></label>\n <textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>\n <p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>\n </div>\n <?php\n }\n}\nadd_action('category_edit_form_fields', 'dm_category_fields', 10, 2);\nadd_action('category_add_form_fields', 'dm_category_fields', 10, 2);\nfunction dm_save_category_fields($term_id) {\n if (!isset($_POST['term_fields'])) {\n return;\n }\n foreach ($_POST['term_fields'] as $key => $value) {\n update_term_meta($term_id, $key, $value);\n }\n}\nadd_action('edited_category', 'dm_save_category_fields', 10, 2);\nadd_action('create_category', 'dm_save_category_fields', 10, 2);\n</code></pre>\n"
}
] | 2022/08/30 | [
"https://wordpress.stackexchange.com/questions/409095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223134/"
] | I'm struggling to understand how I can use `pre_get_post` when the post's metadata is not stored in the wp\_postmeta table. I use Pods (<https://pods.io>) to create custom post types with custom fields, stored using the plugins *Table Storage* option.
My desired outcome is to use `orderby` on the `meta_value` stored in the custom `xyz_custom_table` table.
The following `xyz_order_post_by_meta` function is how I would do this with posts that store metadata in the wp\_postmeta table. But this will not work with custom database tables.
```
function xyz_order_post_by_meta($query)
{
if (
$query->is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive("xyz_cpt")
) {
$query->set("meta_key", "xyz_custom_meta");
$query->set("orderby", "meta_value");
$query->set("order", "ASC");
}
}
add_action("pre_get_posts", "xyz_order_post_by_meta", 9999);
```
Am I right in thinking I need to run a custom SQL query to get the value for `meta_value` to include in the above? If so, how would I write this? I've tried the following, which returns a list of the `meta_value` for each post. But I'm not sure how to write this as the array I think I need for `$query->set("orderby", "meta_value");` to give me the desired outcome?
```
global $wpdb;
$table_name = "xyz_custom_table";
$retrieve_data = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($retrieve_data as $retrieved_data) {
echo $retrieved_data->xyz_custom_meta;
}
``` | I solved the problem, the codes that work are as follows;
```
/* Custom Field for Categories */
function dm_category_fields($term) {
if (current_filter() == 'category_edit_form_fields') {
$bottom_description = get_term_meta($term->term_id, 'bottom_description', true);
$description_field = 'bottom-description';
$description_args = array(
'wpautop' => false,
'media_buttons' => true,
'textarea_rows' => 10,
'textarea_name' => 'term_fields[bottom_description]'
);
?>
<tr class="bottom-form-field">
<th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>
<td>
<?php wp_editor( $bottom_description, $description_field, $description_args ); ?>
<span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>
</td>
</tr>
<?php
} elseif ( current_filter() == 'category_add_form_fields' ) {
?>
<div class="bottom-form-field">
<label><?php _e('Page Break Description'); ?></label>
<textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>
<p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>
</div>
<?php
}
}
add_action('category_edit_form_fields', 'dm_category_fields', 10, 2);
add_action('category_add_form_fields', 'dm_category_fields', 10, 2);
function dm_save_category_fields($term_id) {
if (!isset($_POST['term_fields'])) {
return;
}
foreach ($_POST['term_fields'] as $key => $value) {
update_term_meta($term_id, $key, $value);
}
}
add_action('edited_category', 'dm_save_category_fields', 10, 2);
add_action('create_category', 'dm_save_category_fields', 10, 2);
``` |
409,113 | <p>On our website, we have a footer (built with WP-Bakery) that includes the typical information that is needed, plus there is a section that should show the different types of payment methods that we accept. But for an unknown reason, some of these SVG-Images (not even every time the same) are not visible. Looking at the page, e.g. with Chrome inspector, I can see the images are all there, but they don't show.
We tried different types of SVG-Images, for example the normal SVG or the optimized SVG. We tried to add a width and height to the pictures in the HTML text, and we exchanged the SVG to different SVG pictures to check if the files have any errors. It's still not working, and maybe you know what we should do?</p>
| [
{
"answer_id": 408892,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\"><code>sanitize_text_field()</code></a> is intended to sanitize a value for use as plain-text. HTML tags are stripped in the process.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\"><code>wp_kses()</code></a> may be a more appropriate sanitization helper for your use-case and can be passed a custom list of permitted HTML tags. Alternately, you can pass a context name to use a pre-defined set. To use the list which is used in the process of sanitizing post content, for instance:</p>\n<pre class=\"lang-php prettyprint-override\"><code>update_term_meta( $term_id, $key, wp_kses( $value, 'post' ) );\n</code></pre>\n<p>See the <a href=\"https://developer.wordpress.org/themes/theme-security/\" rel=\"nofollow noreferrer\">Theme Security</a> section of the <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">Theme Handbook</a> for more information on <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">Data Sanitization/Escaping</a> in WordPress.</p>\n"
},
{
"answer_id": 409040,
"author": "Murat Dinc",
"author_id": 161959,
"author_profile": "https://wordpress.stackexchange.com/users/161959",
"pm_score": 1,
"selected": true,
"text": "<p>I solved the problem, the codes that work are as follows;</p>\n<pre><code>/* Custom Field for Categories */\nfunction dm_category_fields($term) {\n if (current_filter() == 'category_edit_form_fields') {\n $bottom_description = get_term_meta($term->term_id, 'bottom_description', true);\n $description_field = 'bottom-description';\n $description_args = array(\n 'wpautop' => false,\n 'media_buttons' => true,\n 'textarea_rows' => 10,\n 'textarea_name' => 'term_fields[bottom_description]'\n );\n ?>\n <tr class="bottom-form-field">\n <th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>\n <td>\n <?php wp_editor( $bottom_description, $description_field, $description_args ); ?>\n <span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>\n </td>\n </tr>\n <?php\n } elseif ( current_filter() == 'category_add_form_fields' ) {\n ?>\n <div class="bottom-form-field">\n <label><?php _e('Page Break Description'); ?></label>\n <textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>\n <p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>\n </div>\n <?php\n }\n}\nadd_action('category_edit_form_fields', 'dm_category_fields', 10, 2);\nadd_action('category_add_form_fields', 'dm_category_fields', 10, 2);\nfunction dm_save_category_fields($term_id) {\n if (!isset($_POST['term_fields'])) {\n return;\n }\n foreach ($_POST['term_fields'] as $key => $value) {\n update_term_meta($term_id, $key, $value);\n }\n}\nadd_action('edited_category', 'dm_save_category_fields', 10, 2);\nadd_action('create_category', 'dm_save_category_fields', 10, 2);\n</code></pre>\n"
}
] | 2022/08/31 | [
"https://wordpress.stackexchange.com/questions/409113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225378/"
] | On our website, we have a footer (built with WP-Bakery) that includes the typical information that is needed, plus there is a section that should show the different types of payment methods that we accept. But for an unknown reason, some of these SVG-Images (not even every time the same) are not visible. Looking at the page, e.g. with Chrome inspector, I can see the images are all there, but they don't show.
We tried different types of SVG-Images, for example the normal SVG or the optimized SVG. We tried to add a width and height to the pictures in the HTML text, and we exchanged the SVG to different SVG pictures to check if the files have any errors. It's still not working, and maybe you know what we should do? | I solved the problem, the codes that work are as follows;
```
/* Custom Field for Categories */
function dm_category_fields($term) {
if (current_filter() == 'category_edit_form_fields') {
$bottom_description = get_term_meta($term->term_id, 'bottom_description', true);
$description_field = 'bottom-description';
$description_args = array(
'wpautop' => false,
'media_buttons' => true,
'textarea_rows' => 10,
'textarea_name' => 'term_fields[bottom_description]'
);
?>
<tr class="bottom-form-field">
<th valign="top" scope="row"><label><?php _e('Page Break Description'); ?></label></th>
<td>
<?php wp_editor( $bottom_description, $description_field, $description_args ); ?>
<span class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></span>
</td>
</tr>
<?php
} elseif ( current_filter() == 'category_add_form_fields' ) {
?>
<div class="bottom-form-field">
<label><?php _e('Page Break Description'); ?></label>
<textarea rows="5" cols="72" id="term_fields[bottom_description]" name="term_fields[bottom_description]"></textarea>
<p class="description"><?php _e('To add something to the end of category content. Supports shortcode.'); ?></p>
</div>
<?php
}
}
add_action('category_edit_form_fields', 'dm_category_fields', 10, 2);
add_action('category_add_form_fields', 'dm_category_fields', 10, 2);
function dm_save_category_fields($term_id) {
if (!isset($_POST['term_fields'])) {
return;
}
foreach ($_POST['term_fields'] as $key => $value) {
update_term_meta($term_id, $key, $value);
}
}
add_action('edited_category', 'dm_save_category_fields', 10, 2);
add_action('create_category', 'dm_save_category_fields', 10, 2);
``` |
409,161 | <p>I added two menus</p>
<pre><code>register_nav_menus (
array(
'primary_menu' => esc_html__('Primary Menu', 'sre'),
'footer_menu' => esc_html__('Footer Menu', 'sre'),
)
);
</code></pre>
<p>But I'm unable to remove the two old ones, <code>Primary menu</code> and <code>Secondary menu</code>
<a href="https://i.stack.imgur.com/fDqnD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fDqnD.jpg" alt="enter image description here" /></a></p>
<p>When I use this code, it hides <code>Primary menu</code> but when I remove the code, it reappears in the list.</p>
<pre><code>add_action( 'after_setup_theme', 'remove_default_menu', 11 );
function remove_default_menu(){
unregister_nav_menu('primary');
}
</code></pre>
| [
{
"answer_id": 409122,
"author": "tiago calado",
"author_id": 198152,
"author_profile": "https://wordpress.stackexchange.com/users/198152",
"pm_score": 2,
"selected": true,
"text": "<p>in the server if you are using cpanel restore the database there, on Databases » phpmyadmin » choose the correct database » then to the tab import » choose file (enter your mysql backup) and press go</p>\n<p><a href=\"https://i.stack.imgur.com/rGpg5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rGpg5.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/c3peH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c3peH.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 409141,
"author": "Brian",
"author_id": 171383,
"author_profile": "https://wordpress.stackexchange.com/users/171383",
"pm_score": 0,
"selected": false,
"text": "<p>The guide here: <a href=\"https://www.wpbeginner.com/beginners-guide/beginners-guide-how-to-restore-wordpress-from-backup/\" rel=\"nofollow noreferrer\">https://www.wpbeginner.com/beginners-guide/beginners-guide-how-to-restore-wordpress-from-backup/</a> details how to import a database into a WordPress site. You might want to test it first on a MAMP install or at least back up your current DB before import. Then if things go awry you can roll back your original DB and try again.</p>\n"
}
] | 2022/09/01 | [
"https://wordpress.stackexchange.com/questions/409161",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171060/"
] | I added two menus
```
register_nav_menus (
array(
'primary_menu' => esc_html__('Primary Menu', 'sre'),
'footer_menu' => esc_html__('Footer Menu', 'sre'),
)
);
```
But I'm unable to remove the two old ones, `Primary menu` and `Secondary menu`
[](https://i.stack.imgur.com/fDqnD.jpg)
When I use this code, it hides `Primary menu` but when I remove the code, it reappears in the list.
```
add_action( 'after_setup_theme', 'remove_default_menu', 11 );
function remove_default_menu(){
unregister_nav_menu('primary');
}
``` | in the server if you are using cpanel restore the database there, on Databases » phpmyadmin » choose the correct database » then to the tab import » choose file (enter your mysql backup) and press go
[](https://i.stack.imgur.com/rGpg5.png)
[](https://i.stack.imgur.com/c3peH.png) |
409,209 | <p>I have a plugin that needs to do a "database update" sort of operation, going through all users and performing a particular database operation on each one. It's designed for sites with large numbers -- tens of thousands -- of users. I've worked out a good efficient way to do the operation in chunks of 1000 users. And I've worked out a way for each chunk (except the last one) to schedule the next chunk for a couple of seconds later with <a href="https://developer.wordpress.org/reference/functions/wp_schedule_single_event/" rel="nofollow noreferrer">wp_schedule_single_event()</a>. So the "database update" runs for a while as a polite background job.</p>
<p>All good.</p>
<p>Now I'm trying to make this work on sites that use system cron and have WP_DISABLE_CRON set to true. My question is this: Is there anything drastically wrong with doing this from an unload action? This code does what a system cronjob does to the site: it hits <code>https://example.com/wp-cron.php</code>. But it does so more often while my background job is in progress.</p>
<pre class="lang-php prettyprint-override"><code>if ( ! wp_doing_cron() ) {
$url = get_site_url( null, 'wp-cron.php' );
$req = new \WP_Http();
$req->get( $url );
}
</code></pre>
<p>I try to respect the disabled internal cron: the site owner disabled it for good reasons. I am taking care not to do this unless I know there's a chunk to process and I know it's been at least couple of seconds since the last time I did it.</p>
<p>This looks like it works. But are there configurations where it will cause big trouble?</p>
<p>(Note: wp-cron.php itself does <a href="https://www.php.net/manual/en/function.fastcgi-finish-request.php" rel="nofollow noreferrer">fastcgi_finish_request()</a> promptly when it is invoked, so my code won't hang for long waiting for wp-cron.php to finish.)</p>
| [
{
"answer_id": 409477,
"author": "AuRise",
"author_id": 110134,
"author_profile": "https://wordpress.stackexchange.com/users/110134",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>WP_DISABLE_CRON</code> constant only removes WP-Cron from loading on the page so it's no longer triggered by site traffic.</p>\n<p>You can absolutely hit the wp-cron.php file directly to trigger it. I use <a href=\"https://cron-job.org\" rel=\"nofollow noreferrer\">https://cron-job.org</a> to ping my private sites at <code>https://dev.example.com/wp-cron.php?doing_wp_cron</code> for example.</p>\n<p>This is actually recommended in the WordPress handbook: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/</a></p>\n<p>Editing to add: if you're concerned about triggering any other hooks associated with WP-Cron that maybe the site owner wants to avoid, you can also use cron-job.org (or a server CRON) to ping a page within your plugin to <em>only</em> run your update function without triggering WP-Cron at all.</p>\n"
},
{
"answer_id": 409542,
"author": "Prits",
"author_id": 140083,
"author_profile": "https://wordpress.stackexchange.com/users/140083",
"pm_score": 1,
"selected": false,
"text": "<p>When you add define('DISABLE_WP_CRON', true); in wp-config.php file the front end cron is disabled when website is triggered there will be no cron running at that time when you reload the page or visit the website.</p>\n<p>So, if you want to run cron using system then you can use ( cron_schedules , wp_next_scheduled ) to run the cron at specific time.</p>\n<p>Example :</p>\n<pre><code>add_filter( 'cron_schedules', 'check_every_time_cron' );\nfunction check_every_time_cron( $schedules ) {\n $schedules['every_minutes'] = array(\n 'interval' => 60,\n 'display' => __( 'Every 1 Minutes', 'cera-child' )\n );\n return $schedules;\n}\nif ( ! wp_next_scheduled( 'check_every_time_cron' ) ) {\n wp_schedule_event( time(), 'every_minutes', 'check_every_time_cron' );\n}\nadd_action( 'check_every_time_cron', 'check_every_time_cron_fun' );\nfunction check_every_time_cron_fun() {\n try {\n custom_logs('djdjdjdjdj');\n }catch (\\Exception $ex) {\n return apiResponse(200, true, $ex->getMessage());\n }\n}\n\nfunction custom_logs($message) {\n if(is_array($message)) {\n $message = json_encode($message);\n }\n $file = fopen("wp-content/themes/cera-child/custom_logs.log","a");\n echo fwrite($file, "\\n" . date('Y-m-d h:i:s') . " :: " . $message);\n fclose($file);\n}\n</code></pre>\n<p>It will check the cron and run at when you add ( wget -q -O - <a href=\"https://example.com/wp-cron.php?doing_wp_cron\" rel=\"nofollow noreferrer\">https://example.com/wp-cron.php?doing_wp_cron</a> ) at specific time in crontab -e.</p>\n<p>Example : 00 5 * * * wget -q -O - <a href=\"https://example.com/wp-cron.php?doing_wp_cron\" rel=\"nofollow noreferrer\">https://example.com/wp-cron.php?doing_wp_cron</a> it is running every day at morning 5 am.</p>\n<p>where i have caleed custom_logs() function you can add your function and do the work what you want.</p>\n<p>I have used that in my created plugin with the use of REST API.</p>\n"
}
] | 2022/09/03 | [
"https://wordpress.stackexchange.com/questions/409209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13596/"
] | I have a plugin that needs to do a "database update" sort of operation, going through all users and performing a particular database operation on each one. It's designed for sites with large numbers -- tens of thousands -- of users. I've worked out a good efficient way to do the operation in chunks of 1000 users. And I've worked out a way for each chunk (except the last one) to schedule the next chunk for a couple of seconds later with [wp\_schedule\_single\_event()](https://developer.wordpress.org/reference/functions/wp_schedule_single_event/). So the "database update" runs for a while as a polite background job.
All good.
Now I'm trying to make this work on sites that use system cron and have WP\_DISABLE\_CRON set to true. My question is this: Is there anything drastically wrong with doing this from an unload action? This code does what a system cronjob does to the site: it hits `https://example.com/wp-cron.php`. But it does so more often while my background job is in progress.
```php
if ( ! wp_doing_cron() ) {
$url = get_site_url( null, 'wp-cron.php' );
$req = new \WP_Http();
$req->get( $url );
}
```
I try to respect the disabled internal cron: the site owner disabled it for good reasons. I am taking care not to do this unless I know there's a chunk to process and I know it's been at least couple of seconds since the last time I did it.
This looks like it works. But are there configurations where it will cause big trouble?
(Note: wp-cron.php itself does [fastcgi\_finish\_request()](https://www.php.net/manual/en/function.fastcgi-finish-request.php) promptly when it is invoked, so my code won't hang for long waiting for wp-cron.php to finish.) | The `WP_DISABLE_CRON` constant only removes WP-Cron from loading on the page so it's no longer triggered by site traffic.
You can absolutely hit the wp-cron.php file directly to trigger it. I use <https://cron-job.org> to ping my private sites at `https://dev.example.com/wp-cron.php?doing_wp_cron` for example.
This is actually recommended in the WordPress handbook: <https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/>
Editing to add: if you're concerned about triggering any other hooks associated with WP-Cron that maybe the site owner wants to avoid, you can also use cron-job.org (or a server CRON) to ping a page within your plugin to *only* run your update function without triggering WP-Cron at all. |
409,243 | <p>I am not an expert. I have used a tutorial to write a custom query like this</p>
<pre><code>add_action( 'elementor/query/my_query_by_post_types', function( $query ) {
$query->set( 'post_type', [ 'libri', 'post'] );
} );
</code></pre>
<p>This has been deployes via snippets plugin. Works fine and filter 'libri' (which is a custom type) and posts. I need to enhance because i need only 'some' post, not all, so I need to filter by post category. Can anybody help to do that?
Thanks.</p>
| [
{
"answer_id": 409523,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>This just requires adding additional parameters to the <code>query->set()</code> array... ...it's standard <code>WP_Query()</code> stuff. So you'd essentially be taking this line:</p>\n<p><code>$query->set( 'post_type', [ 'libri', 'post'] );</code></p>\n<p>...and expanding it to include a tax query...</p>\n<pre><code>$tax_query = array(\n 'relation' => 'OR', //can also use 'AND' depends how you want it to work \n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 1 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 2 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 3 //put your term id here\n )\n);\n$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n"
},
{
"answer_id": 409964,
"author": "IMTanuki",
"author_id": 218388,
"author_profile": "https://wordpress.stackexchange.com/users/218388",
"pm_score": 0,
"selected": false,
"text": "<p>@Tony Djukic\nYour answer was incredibly helpful! But it seems that this structure is an OR:</p>\n<pre><code>$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n<p>Based on preliminary testing, it would return anything that is either libri, post, or satisfies the taxonomy filter.</p>\n<p>What if we want to AND the post_type and taxonomy - either (libri OR post) AND satisfies the taxonomy filter. How would that work? I think the following is an AND relationship (correct me if I'm wrong):</p>\n<pre><code> $query->set( \n 'post_type', [ 'libri', 'post'],\n ); \n $query->set( \n 'tax_query', $tax_query\n );\n</code></pre>\n<p>(sorry - not enough points to use comments)</p>\n"
}
] | 2022/09/05 | [
"https://wordpress.stackexchange.com/questions/409243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225521/"
] | I am not an expert. I have used a tutorial to write a custom query like this
```
add_action( 'elementor/query/my_query_by_post_types', function( $query ) {
$query->set( 'post_type', [ 'libri', 'post'] );
} );
```
This has been deployes via snippets plugin. Works fine and filter 'libri' (which is a custom type) and posts. I need to enhance because i need only 'some' post, not all, so I need to filter by post category. Can anybody help to do that?
Thanks. | This just requires adding additional parameters to the `query->set()` array... ...it's standard `WP_Query()` stuff. So you'd essentially be taking this line:
`$query->set( 'post_type', [ 'libri', 'post'] );`
...and expanding it to include a tax query...
```
$tax_query = array(
'relation' => 'OR', //can also use 'AND' depends how you want it to work
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 1 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 2 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 3 //put your term id here
)
);
$query->set(
'post_type', [ 'libri', 'post'],
'tax_query', $tax_query
);
``` |
409,255 | <p>I want to convert every PNG and JPEG to WebP on upload so that I can serve WebP and PNG/JPEG without requiring the user to upload a WebP version of every photo.<br />
I want to save the WebP in the same folder with the same name, for example:</p>
<pre><code>uploads/2022/09/image.png
uploads/2022/09/image.webp
</code></pre>
<p>How can I do this? Is there a hook I can use?
Is there a reason not to use <code>imagewebp</code> for this?</p>
| [
{
"answer_id": 409523,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>This just requires adding additional parameters to the <code>query->set()</code> array... ...it's standard <code>WP_Query()</code> stuff. So you'd essentially be taking this line:</p>\n<p><code>$query->set( 'post_type', [ 'libri', 'post'] );</code></p>\n<p>...and expanding it to include a tax query...</p>\n<pre><code>$tax_query = array(\n 'relation' => 'OR', //can also use 'AND' depends how you want it to work \n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 1 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 2 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 3 //put your term id here\n )\n);\n$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n"
},
{
"answer_id": 409964,
"author": "IMTanuki",
"author_id": 218388,
"author_profile": "https://wordpress.stackexchange.com/users/218388",
"pm_score": 0,
"selected": false,
"text": "<p>@Tony Djukic\nYour answer was incredibly helpful! But it seems that this structure is an OR:</p>\n<pre><code>$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n<p>Based on preliminary testing, it would return anything that is either libri, post, or satisfies the taxonomy filter.</p>\n<p>What if we want to AND the post_type and taxonomy - either (libri OR post) AND satisfies the taxonomy filter. How would that work? I think the following is an AND relationship (correct me if I'm wrong):</p>\n<pre><code> $query->set( \n 'post_type', [ 'libri', 'post'],\n ); \n $query->set( \n 'tax_query', $tax_query\n );\n</code></pre>\n<p>(sorry - not enough points to use comments)</p>\n"
}
] | 2022/09/05 | [
"https://wordpress.stackexchange.com/questions/409255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225526/"
] | I want to convert every PNG and JPEG to WebP on upload so that I can serve WebP and PNG/JPEG without requiring the user to upload a WebP version of every photo.
I want to save the WebP in the same folder with the same name, for example:
```
uploads/2022/09/image.png
uploads/2022/09/image.webp
```
How can I do this? Is there a hook I can use?
Is there a reason not to use `imagewebp` for this? | This just requires adding additional parameters to the `query->set()` array... ...it's standard `WP_Query()` stuff. So you'd essentially be taking this line:
`$query->set( 'post_type', [ 'libri', 'post'] );`
...and expanding it to include a tax query...
```
$tax_query = array(
'relation' => 'OR', //can also use 'AND' depends how you want it to work
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 1 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 2 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 3 //put your term id here
)
);
$query->set(
'post_type', [ 'libri', 'post'],
'tax_query', $tax_query
);
``` |
409,338 | <p>I have two files:</p>
<h1>abc.php</h1>
<pre><code><?php
/*
Template Name:ABC Template
*/
?>
<div id="div-image" class="div-child"> <img src="<?php echo get_template_directory_uri(); ?>/Images/Loading.gif" id="load" /> </div>
<script src="<?php echo get_template_directory_uri(); ?>/alphawords.js" type="text/javascript"></script>
</code></pre>
<h1>xyz.js</h1>
<pre><code>document.getElementById("load").src="<?php echo get_template_directory_uri(); ?>/Images/pic.png";
</code></pre>
<p><code>xyz.js</code> is included properly, but image is not being loaded through the JS. How can I get the image to load properly?</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 409523,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>This just requires adding additional parameters to the <code>query->set()</code> array... ...it's standard <code>WP_Query()</code> stuff. So you'd essentially be taking this line:</p>\n<p><code>$query->set( 'post_type', [ 'libri', 'post'] );</code></p>\n<p>...and expanding it to include a tax query...</p>\n<pre><code>$tax_query = array(\n 'relation' => 'OR', //can also use 'AND' depends how you want it to work \n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 1 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 2 //put your term id here\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'terms' => 3 //put your term id here\n )\n);\n$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n"
},
{
"answer_id": 409964,
"author": "IMTanuki",
"author_id": 218388,
"author_profile": "https://wordpress.stackexchange.com/users/218388",
"pm_score": 0,
"selected": false,
"text": "<p>@Tony Djukic\nYour answer was incredibly helpful! But it seems that this structure is an OR:</p>\n<pre><code>$query->set( \n 'post_type', [ 'libri', 'post'],\n 'tax_query', $tax_query\n);\n</code></pre>\n<p>Based on preliminary testing, it would return anything that is either libri, post, or satisfies the taxonomy filter.</p>\n<p>What if we want to AND the post_type and taxonomy - either (libri OR post) AND satisfies the taxonomy filter. How would that work? I think the following is an AND relationship (correct me if I'm wrong):</p>\n<pre><code> $query->set( \n 'post_type', [ 'libri', 'post'],\n ); \n $query->set( \n 'tax_query', $tax_query\n );\n</code></pre>\n<p>(sorry - not enough points to use comments)</p>\n"
}
] | 2022/09/08 | [
"https://wordpress.stackexchange.com/questions/409338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225610/"
] | I have two files:
abc.php
=======
```
<?php
/*
Template Name:ABC Template
*/
?>
<div id="div-image" class="div-child"> <img src="<?php echo get_template_directory_uri(); ?>/Images/Loading.gif" id="load" /> </div>
<script src="<?php echo get_template_directory_uri(); ?>/alphawords.js" type="text/javascript"></script>
```
xyz.js
======
```
document.getElementById("load").src="<?php echo get_template_directory_uri(); ?>/Images/pic.png";
```
`xyz.js` is included properly, but image is not being loaded through the JS. How can I get the image to load properly?
Thank you in advance. | This just requires adding additional parameters to the `query->set()` array... ...it's standard `WP_Query()` stuff. So you'd essentially be taking this line:
`$query->set( 'post_type', [ 'libri', 'post'] );`
...and expanding it to include a tax query...
```
$tax_query = array(
'relation' => 'OR', //can also use 'AND' depends how you want it to work
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 1 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 2 //put your term id here
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => 3 //put your term id here
)
);
$query->set(
'post_type', [ 'libri', 'post'],
'tax_query', $tax_query
);
``` |
409,354 | <p>I've implemented <a href="https://code.tutsplus.com/tutorials/create-a-license-controlled-update-system-doing-the-update--cms-22675" rel="nofollow noreferrer">this</a> update class in my plugin, but for some reason the update banner isn't diplayed.</p>
<p>Within the class <code>Wp_License_Manager_Client</code> I have this code:</p>
<pre><code>add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update'));
</code></pre>
<p>that fire the function <code>check_for_update</code>, in particular the following line is called:</p>
<pre><code>$plugin_slug = plugin_basename($this->plugin_file);
$transient->response[$plugin_slug] = (object) array(
'new_version' => $info->version,
'package' => $info->package_url,
'slug' => $plugin_slug,
'url' => $info->package_url
);
</code></pre>
<p>This is the <code>var_dump($transient->response[$plugin_slug])</code>:</p>
<pre><code>object(stdClass)#8891 (4) {
["new_version"]=> string(5) "1.0.1"
["package"]=> string(107) "https://example.com/api/license-manager/v1/get?p=my-plugin&[email protected]&l=123456789%24"
["slug"]=> string(47) "my-plugin/public/class-wp-api-client.php"
["url"]=> string(107) "https://example.com/api/license-manager/v1/get?p=my-plugin&[email protected]&l=123456789%24"
}
</code></pre>
<p>I replaced the values for privacy, but as you can see the object is correctly created.</p>
<p>The situation in the panel is the following:</p>
<p><a href="https://i.stack.imgur.com/lXFxD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lXFxD.jpg" alt="enter image description here" /></a></p>
<p>As you can see from the image Wordpress show me that there is one update, but when I click on "updates", it says that all the plugins are updated. Also, I get the update badge notification only when I clear the cache.</p>
<p>What is going on?</p>
<p>PS: I'm testing this in my localhost with XAMPP and wordpress version is 6.0.1.</p>
| [
{
"answer_id": 409545,
"author": "Prits",
"author_id": 140083,
"author_profile": "https://wordpress.stackexchange.com/users/140083",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this code to check if plugin updates is available :</p>\n<pre><code>add_action('admin_menu', array($this,'register_test_menu_page'));\n\npublic function register_test_menu_page(){\n add_menu_page('Test', 'Test Menu', 'manage_options', \n 'test_user_menu', array($this,'test_user_menu_fun'), null, 4);\n}\n\npublic function test_user_menu_fun(){\n $update_plugins = get_site_transient( 'update_plugins' );\n foreach ($update_plugins->response as $key => $value) {\n var_dump($value->slug);\n } \n}\n</code></pre>\n<p>it provides an array you can easily show that in the list in your setting page.</p>\n"
},
{
"answer_id": 409705,
"author": "Whispar Design",
"author_id": 225987,
"author_profile": "https://wordpress.stackexchange.com/users/225987",
"pm_score": 3,
"selected": true,
"text": "<p>I ran across this a few weeks ago with a client site - maybe this will help.</p>\n<pre><code> /**\n * Debug Pending Updates\n *\n * Crude debugging method that will spit out all pending plugin\n * and theme updates for admin level users when ?debug_updates is\n * added to a /wp-admin/ URL.\n */\nfunction debug_pending_updates() {\n\n // Rough safety nets\n if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) return;\n if ( ! isset( $_GET['debug_updates'] ) ) return;\n\n $output = "";\n\n // Check plugins\n $plugin_updates = get_site_transient( 'update_plugins' );\n if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {\n foreach ( $plugin_updates->response as $plugin => $details ) {\n $output .= "<p><strong>Plugin</strong> <u>$plugin</u> is reporting an available update.</p>";\n }\n }\n\n // Check themes\n wp_update_themes();\n $theme_updates = get_site_transient( 'update_themes' );\n if ( $theme_updates && ! empty( $theme_updates->response ) ) {\n foreach ( $theme_updates->response as $theme => $details ) {\n $output .= "<p><strong>Theme</strong> <u>$theme</u> is reporting an available update.</p>";\n }\n }\n\n if ( empty( $output ) ) $output = "No pending updates found in the database.";\n\n wp_die( $output );\n}\nadd_action( 'init', 'debug_pending_updates' );\n</code></pre>\n<p>Append your admin url as follows:</p>\n<pre><code>For example: https://yoursite.com/wp-admin/?debug_updates\n</code></pre>\n"
},
{
"answer_id": 409746,
"author": "ddur",
"author_id": 160028,
"author_profile": "https://wordpress.stackexchange.com/users/160028",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://code.tutsplus.com/tutorials/create-a-license-controlled-update-system-doing-the-update--cms-22675\" rel=\"nofollow noreferrer\">Tutorial</a> you are using is 7 years old, I wouldn't bother wit it as it is probably not fully compatible with latest WP-Core and auto-updates.</p>\n<p>I'm using free (MIT license) and regularly maintained <a href=\"https://github.com/YahnisElsts/plugin-update-checker\" rel=\"nofollow noreferrer\">Plugin Update Checker</a> & <a href=\"https://github.com/YahnisElsts/wp-update-server\" rel=\"nofollow noreferrer\">WP Update Server</a> WP libraries for my <a href=\"https://github.com/ddur/Warp-iMagick\" rel=\"nofollow noreferrer\">Warp iMagick plugin</a>.</p>\n<p>Check this <a href=\"http://open-tools.net/documentation/tutorial-automatic-updates.html#wordpress\" rel=\"nofollow noreferrer\">tutorial to add licencing</a>.</p>\n"
}
] | 2022/09/09 | [
"https://wordpress.stackexchange.com/questions/409354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160916/"
] | I've implemented [this](https://code.tutsplus.com/tutorials/create-a-license-controlled-update-system-doing-the-update--cms-22675) update class in my plugin, but for some reason the update banner isn't diplayed.
Within the class `Wp_License_Manager_Client` I have this code:
```
add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update'));
```
that fire the function `check_for_update`, in particular the following line is called:
```
$plugin_slug = plugin_basename($this->plugin_file);
$transient->response[$plugin_slug] = (object) array(
'new_version' => $info->version,
'package' => $info->package_url,
'slug' => $plugin_slug,
'url' => $info->package_url
);
```
This is the `var_dump($transient->response[$plugin_slug])`:
```
object(stdClass)#8891 (4) {
["new_version"]=> string(5) "1.0.1"
["package"]=> string(107) "https://example.com/api/license-manager/v1/get?p=my-plugin&[email protected]&l=123456789%24"
["slug"]=> string(47) "my-plugin/public/class-wp-api-client.php"
["url"]=> string(107) "https://example.com/api/license-manager/v1/get?p=my-plugin&[email protected]&l=123456789%24"
}
```
I replaced the values for privacy, but as you can see the object is correctly created.
The situation in the panel is the following:
[](https://i.stack.imgur.com/lXFxD.jpg)
As you can see from the image Wordpress show me that there is one update, but when I click on "updates", it says that all the plugins are updated. Also, I get the update badge notification only when I clear the cache.
What is going on?
PS: I'm testing this in my localhost with XAMPP and wordpress version is 6.0.1. | I ran across this a few weeks ago with a client site - maybe this will help.
```
/**
* Debug Pending Updates
*
* Crude debugging method that will spit out all pending plugin
* and theme updates for admin level users when ?debug_updates is
* added to a /wp-admin/ URL.
*/
function debug_pending_updates() {
// Rough safety nets
if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) return;
if ( ! isset( $_GET['debug_updates'] ) ) return;
$output = "";
// Check plugins
$plugin_updates = get_site_transient( 'update_plugins' );
if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {
foreach ( $plugin_updates->response as $plugin => $details ) {
$output .= "<p><strong>Plugin</strong> <u>$plugin</u> is reporting an available update.</p>";
}
}
// Check themes
wp_update_themes();
$theme_updates = get_site_transient( 'update_themes' );
if ( $theme_updates && ! empty( $theme_updates->response ) ) {
foreach ( $theme_updates->response as $theme => $details ) {
$output .= "<p><strong>Theme</strong> <u>$theme</u> is reporting an available update.</p>";
}
}
if ( empty( $output ) ) $output = "No pending updates found in the database.";
wp_die( $output );
}
add_action( 'init', 'debug_pending_updates' );
```
Append your admin url as follows:
```
For example: https://yoursite.com/wp-admin/?debug_updates
``` |
409,409 | <p>Brand new WP application on Cloudways hosting. Their tech support unable to resolve. Updating via backend or WP CLI results in error. Directory created but files not copied into it. Seems to be a PHP error.</p>
<pre><code>Installing Media Cleaner – Clean & Optimize Space (6.4.5)
Downloading installation package from https://downloads.wordpress.org/plugin/media-cleaner.6.4.5.zip...
Unpacking the package...
Installing the plugin...
PHP Fatal error: Uncaught Error: Call to undefined function fcp_copy_dir() in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/fi
le.php:1896
Stack trace:
#0 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(596): copy_dir()
#1 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(798): WP_Upgrader->install_package()
#2 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-plugin-upgrader.php(137): WP_Upgrader->run()
#3 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(552): Plugin_Upgrader->install()
#4 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/WP_CLI/CommandWithUpgrade.php(209): Plugin_Command->install_from_repo()
#5 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(809): WP_CLI\CommandWithUpgrade->install()
#6 [internal function]: Plugin_Command->install()
#7 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Di in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.php on lin
e 1896
Fatal error: Uncaught Error: Call to undefined function fcp_copy_dir() in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.ph
p:1896
Stack trace:
#0 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(596): copy_dir()
#1 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(798): WP_Upgrader->install_package()
#2 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-plugin-upgrader.php(137): WP_Upgrader->run()
#3 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(552): Plugin_Upgrader->install()
#4 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/WP_CLI/CommandWithUpgrade.php(209): Plugin_Command->install_from_repo()
#5 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(809): WP_CLI\CommandWithUpgrade->install()
#6 [internal function]: Plugin_Command->install()
#7 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Di in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.php on lin
e 1896
Error: There has been a critical error on this website.Learn more about troubleshooting WordPress. There has been a critical error on this website.
</code></pre>
<p>Tried with various plugins & themes; same result.</p>
<p>PHP version & SQL version on origin site matches destination.</p>
| [
{
"answer_id": 409410,
"author": "Chris J. Zähller",
"author_id": 119814,
"author_profile": "https://wordpress.stackexchange.com/users/119814",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like the Cloudways migration didn't complete properly. Reinstalling WordPress from the dashboard solved it.</p>\n"
},
{
"answer_id": 413952,
"author": "user11860704",
"author_id": 230079,
"author_profile": "https://wordpress.stackexchange.com/users/230079",
"pm_score": 2,
"selected": false,
"text": "<p>For the benefit of anyone else finding this off the back of a search query, I had the same issue with <code>fcp_copy_dir()</code> function not found.</p>\n<p>Cause: I'd migrated the site from a Flywheel instance. <code>fcp_copy_dir()</code> seems to be a custom Flywheel function they've added to WP core. Core WP runs into errors when run in non-Flywheel environments.</p>\n<p>Diagnosis: Use <code>wp core verify-checksums</code> to validate the integrity of WP core. In my case, this showed 3 files had been modified.</p>\n<p>Resolution: Revert to a clean WP core.</p>\n"
}
] | 2022/09/12 | [
"https://wordpress.stackexchange.com/questions/409409",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119814/"
] | Brand new WP application on Cloudways hosting. Their tech support unable to resolve. Updating via backend or WP CLI results in error. Directory created but files not copied into it. Seems to be a PHP error.
```
Installing Media Cleaner – Clean & Optimize Space (6.4.5)
Downloading installation package from https://downloads.wordpress.org/plugin/media-cleaner.6.4.5.zip...
Unpacking the package...
Installing the plugin...
PHP Fatal error: Uncaught Error: Call to undefined function fcp_copy_dir() in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/fi
le.php:1896
Stack trace:
#0 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(596): copy_dir()
#1 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(798): WP_Upgrader->install_package()
#2 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-plugin-upgrader.php(137): WP_Upgrader->run()
#3 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(552): Plugin_Upgrader->install()
#4 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/WP_CLI/CommandWithUpgrade.php(209): Plugin_Command->install_from_repo()
#5 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(809): WP_CLI\CommandWithUpgrade->install()
#6 [internal function]: Plugin_Command->install()
#7 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Di in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.php on lin
e 1896
Fatal error: Uncaught Error: Call to undefined function fcp_copy_dir() in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.ph
p:1896
Stack trace:
#0 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(596): copy_dir()
#1 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-wp-upgrader.php(798): WP_Upgrader->install_package()
#2 /home/path/to/my/wordpress/app/public_html/wp-admin/includes/class-plugin-upgrader.php(137): WP_Upgrader->run()
#3 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(552): Plugin_Upgrader->install()
#4 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/WP_CLI/CommandWithUpgrade.php(209): Plugin_Command->install_from_repo()
#5 phar:///usr/local/bin/wp/vendor/wp-cli/extension-command/src/Plugin_Command.php(809): WP_CLI\CommandWithUpgrade->install()
#6 [internal function]: Plugin_Command->install()
#7 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Di in /home/path/to/my/wordpress/app/public_html/wp-admin/includes/file.php on lin
e 1896
Error: There has been a critical error on this website.Learn more about troubleshooting WordPress. There has been a critical error on this website.
```
Tried with various plugins & themes; same result.
PHP version & SQL version on origin site matches destination. | For the benefit of anyone else finding this off the back of a search query, I had the same issue with `fcp_copy_dir()` function not found.
Cause: I'd migrated the site from a Flywheel instance. `fcp_copy_dir()` seems to be a custom Flywheel function they've added to WP core. Core WP runs into errors when run in non-Flywheel environments.
Diagnosis: Use `wp core verify-checksums` to validate the integrity of WP core. In my case, this showed 3 files had been modified.
Resolution: Revert to a clean WP core. |
409,446 | <p>I have two custom post type <strong>Author</strong> and <strong>Book</strong>. The book cpt have an <strong>ACF Object Field</strong> (<em>authors_object_field</em>) that is related to authors. On the author single page i want to display all <strong>books</strong> that have the <strong>author</strong> listed in their <strong>ACF Object Field</strong>. I'm using <strong>Elementor</strong> as page builder. I used this code but dont seems to work. Need your lights :)</p>
<pre><code>function my_books_by_author_query($query)
{
$myCurrentAuthorID = get_the_ID();
$meta_query = [
[
'key' => 'authors_object_field',
'value' => $myCurrentAuthorID,
'compare' => '==',
]
];
$query->set('meta_query', $meta_query);
$query->set('post_type', 'book');
}
add_action('elementor/query/booksByAuthor', 'my_books_by_author_query');
</code></pre>
| [
{
"answer_id": 409410,
"author": "Chris J. Zähller",
"author_id": 119814,
"author_profile": "https://wordpress.stackexchange.com/users/119814",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like the Cloudways migration didn't complete properly. Reinstalling WordPress from the dashboard solved it.</p>\n"
},
{
"answer_id": 413952,
"author": "user11860704",
"author_id": 230079,
"author_profile": "https://wordpress.stackexchange.com/users/230079",
"pm_score": 2,
"selected": false,
"text": "<p>For the benefit of anyone else finding this off the back of a search query, I had the same issue with <code>fcp_copy_dir()</code> function not found.</p>\n<p>Cause: I'd migrated the site from a Flywheel instance. <code>fcp_copy_dir()</code> seems to be a custom Flywheel function they've added to WP core. Core WP runs into errors when run in non-Flywheel environments.</p>\n<p>Diagnosis: Use <code>wp core verify-checksums</code> to validate the integrity of WP core. In my case, this showed 3 files had been modified.</p>\n<p>Resolution: Revert to a clean WP core.</p>\n"
}
] | 2022/09/13 | [
"https://wordpress.stackexchange.com/questions/409446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/175053/"
] | I have two custom post type **Author** and **Book**. The book cpt have an **ACF Object Field** (*authors\_object\_field*) that is related to authors. On the author single page i want to display all **books** that have the **author** listed in their **ACF Object Field**. I'm using **Elementor** as page builder. I used this code but dont seems to work. Need your lights :)
```
function my_books_by_author_query($query)
{
$myCurrentAuthorID = get_the_ID();
$meta_query = [
[
'key' => 'authors_object_field',
'value' => $myCurrentAuthorID,
'compare' => '==',
]
];
$query->set('meta_query', $meta_query);
$query->set('post_type', 'book');
}
add_action('elementor/query/booksByAuthor', 'my_books_by_author_query');
``` | For the benefit of anyone else finding this off the back of a search query, I had the same issue with `fcp_copy_dir()` function not found.
Cause: I'd migrated the site from a Flywheel instance. `fcp_copy_dir()` seems to be a custom Flywheel function they've added to WP core. Core WP runs into errors when run in non-Flywheel environments.
Diagnosis: Use `wp core verify-checksums` to validate the integrity of WP core. In my case, this showed 3 files had been modified.
Resolution: Revert to a clean WP core. |
409,489 | <p>I've originally hard-coded menu links into the mega menu of <a href="https://mandoemedia.com" rel="nofollow noreferrer">mandoemedia.com</a> in order to achieve the icon and description of each link.</p>
<p><a href="https://i.stack.imgur.com/ZQHjv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZQHjv.png" alt="enter image description here" /></a></p>
<p>I'm wondering if it is possible to convert these submenus into menus I can add through Appearance > Menus while still maintaining the icons and descriptions.</p>
<p>I see through Screen Options I can add a <code>Description</code> to each menu item and a <code>CSS Class</code> which I can use as in image filename.</p>
<p>From <a href="https://kriesi.at/archives/improve-your-wordpress-navigation-menu-output" rel="nofollow noreferrer">this page</a>, I've created a custom plugin:</p>
<pre><code><?php
/*
Plugin Name: Mandoe Mega Menu Helper
Description: Allows images and descriptions in mega menus
Author: Steve Doig
Version: 1.0.0
*/
class mandoe_menu_walker extends Walker {
function start_el(&$output, $item, $depth = 0, $args) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$prepend = '<strong>';
$append = '</strong>';
$description = ! empty( $item->description ) ? '<span class="mm-mm-subtext">'.esc_attr( $item->description ).'</span>' : '';
if($depth != 0) {
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><img src="' . get_stylesheet_directory_uri() . '/img/icon-' . $class_names .'" alt="' . $item->title . '" class="mm-mm-icon">';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
?>
</code></pre>
<p>but when activating this plugin I receive an error:</p>
<blockquote>
<p>Fatal error: Declaration of mandoe_menu_walker::start_el(&$output,
$item, $depth, $args) must be compatible with
Walker::start_el(&$output, $data_object, $depth = 0, $args = [],
$current_object_id = 0) in /wp-content/plugins/mm-mega-menu-helper/mm-mega-menu-helper.php
on line 10</p>
</blockquote>
<p>Help appreciated.</p>
| [
{
"answer_id": 409492,
"author": "Steve",
"author_id": 3206,
"author_profile": "https://wordpress.stackexchange.com/users/3206",
"pm_score": 0,
"selected": false,
"text": "<p>I changed the function definition to</p>\n<pre><code>function start_el(&$output, $item, $depth = 0, $args=[], current_object_id = 0) \n</code></pre>\n<p>and it activated okay.</p>\n"
},
{
"answer_id": 409494,
"author": "silver",
"author_id": 80499,
"author_profile": "https://wordpress.stackexchange.com/users/80499",
"pm_score": 1,
"selected": false,
"text": "<p>An entirely different approach.</p>\n<p>nav menu item are stored in posts table, so you can technically attach a post_meta into it, even other data like nav item class already stored in post mata table. However this wasn't easy to do before.</p>\n<p>but after 5.4.0 release, they have implemented hooks to easily do this.</p>\n<p>Here's the full step</p>\n<p><strong>Add Custom Meta box on Nav item</strong></p>\n<pre><code>add_action( 'wp_nav_menu_item_custom_fields', function( $id, $navItem) {\n\n wp_nonce_field( 'nav_menu_icon_nonce', '_nav_menu_icon_nonce_name' );\n $nav_menu_icon = get_post_meta( $id, '_nav_menu_icon', true );\n ?>\n <p class="field-nav-icon nav-icon description-wide">\n <label for="edit-menu-item-nav-icon-<?php echo $id ;?>">\n Nav Icon<br>\n <textarea id="edit-menu-item-nav-icon-<?php echo $id ;?>" class="widefat edit-menu-item-nav-icon" rows="3" cols="20" name="menu_item_nav_icon[<?php echo $id ;?>]"><?php echo esc_attr( $nav_menu_icon ); ?></textarea>\n <span class="description">Add icon on menu.</span>\n </label>\n </p>\n <?php\n}, 10, 2 );\n</code></pre>\n<p>There should be another box in nav item after adding the code above like this\n<a href=\"https://i.stack.imgur.com/QWcfX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QWcfX.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Then save the value of that field into post meta</strong></p>\n<pre><code>add_action( 'wp_update_nav_menu_item', function($menuId, $menuItemId) {\n\n // current_user_can( 'unfiltered_html' ) is a wordpress role which ensure the user can post unfiltered html\n if ( ! isset( $_POST['_nav_menu_icon_nonce_name'] ) || ! wp_verify_nonce( $_POST['_nav_menu_icon_nonce_name'], 'nav_menu_icon_nonce' ) || !current_user_can( 'unfiltered_html' ) ) \n return $menuId;\n \n if ( isset( $_POST['menu_item_nav_icon'][$menuItemId] ) ) {\n update_post_meta( $menuItemId, '_nav_menu_icon', $_POST['menu_item_nav_icon'][$menuItemId] );\n } else {\n delete_post_meta( $menuItemId, '_nav_menu_icon' );\n }\n}, 10, 2 );\n</code></pre>\n<p>and thats it, you now have additional data connected to each menu item for nav icon that supports text and html, you can add html tag like <code><img /></code> for adding image as menu icon, or <code>svg</code>,</p>\n<p>To display on the front-end, this depends on your set-up and where you want them to show</p>\n<p>an example below that modify the nav menu item title via <code>nav_menu_item_title</code> filter and include the icon using <code>get_post_meta</code> to pull the icon value</p>\n<pre><code>add_filter( 'nav_menu_item_title', function( $title, $item) {\n \n if( is_object( $item ) && isset( $item->ID ) ) {\n \n $navIcon = get_post_meta( $item->ID, '_nav_menu_icon', true );\n \n if ( ! empty( $navIcon ) ) {\n $title = '<span class="icon">'.$navIcon.'</span>' . $title;\n }\n \n }\n return $title;\n \n}, 10, 2 );\n</code></pre>\n<p>and the title would show the svg icon if there is</p>\n<p><a href=\"https://i.stack.imgur.com/42ziY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/42ziY.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2022/09/14 | [
"https://wordpress.stackexchange.com/questions/409489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | I've originally hard-coded menu links into the mega menu of [mandoemedia.com](https://mandoemedia.com) in order to achieve the icon and description of each link.
[](https://i.stack.imgur.com/ZQHjv.png)
I'm wondering if it is possible to convert these submenus into menus I can add through Appearance > Menus while still maintaining the icons and descriptions.
I see through Screen Options I can add a `Description` to each menu item and a `CSS Class` which I can use as in image filename.
From [this page](https://kriesi.at/archives/improve-your-wordpress-navigation-menu-output), I've created a custom plugin:
```
<?php
/*
Plugin Name: Mandoe Mega Menu Helper
Description: Allows images and descriptions in mega menus
Author: Steve Doig
Version: 1.0.0
*/
class mandoe_menu_walker extends Walker {
function start_el(&$output, $item, $depth = 0, $args) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$prepend = '<strong>';
$append = '</strong>';
$description = ! empty( $item->description ) ? '<span class="mm-mm-subtext">'.esc_attr( $item->description ).'</span>' : '';
if($depth != 0) {
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><img src="' . get_stylesheet_directory_uri() . '/img/icon-' . $class_names .'" alt="' . $item->title . '" class="mm-mm-icon">';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
?>
```
but when activating this plugin I receive an error:
>
> Fatal error: Declaration of mandoe\_menu\_walker::start\_el(&$output,
> $item, $depth, $args) must be compatible with
> Walker::start\_el(&$output, $data\_object, $depth = 0, $args = [],
> $current\_object\_id = 0) in /wp-content/plugins/mm-mega-menu-helper/mm-mega-menu-helper.php
> on line 10
>
>
>
Help appreciated. | An entirely different approach.
nav menu item are stored in posts table, so you can technically attach a post\_meta into it, even other data like nav item class already stored in post mata table. However this wasn't easy to do before.
but after 5.4.0 release, they have implemented hooks to easily do this.
Here's the full step
**Add Custom Meta box on Nav item**
```
add_action( 'wp_nav_menu_item_custom_fields', function( $id, $navItem) {
wp_nonce_field( 'nav_menu_icon_nonce', '_nav_menu_icon_nonce_name' );
$nav_menu_icon = get_post_meta( $id, '_nav_menu_icon', true );
?>
<p class="field-nav-icon nav-icon description-wide">
<label for="edit-menu-item-nav-icon-<?php echo $id ;?>">
Nav Icon<br>
<textarea id="edit-menu-item-nav-icon-<?php echo $id ;?>" class="widefat edit-menu-item-nav-icon" rows="3" cols="20" name="menu_item_nav_icon[<?php echo $id ;?>]"><?php echo esc_attr( $nav_menu_icon ); ?></textarea>
<span class="description">Add icon on menu.</span>
</label>
</p>
<?php
}, 10, 2 );
```
There should be another box in nav item after adding the code above like this
[](https://i.stack.imgur.com/QWcfX.png)
**Then save the value of that field into post meta**
```
add_action( 'wp_update_nav_menu_item', function($menuId, $menuItemId) {
// current_user_can( 'unfiltered_html' ) is a wordpress role which ensure the user can post unfiltered html
if ( ! isset( $_POST['_nav_menu_icon_nonce_name'] ) || ! wp_verify_nonce( $_POST['_nav_menu_icon_nonce_name'], 'nav_menu_icon_nonce' ) || !current_user_can( 'unfiltered_html' ) )
return $menuId;
if ( isset( $_POST['menu_item_nav_icon'][$menuItemId] ) ) {
update_post_meta( $menuItemId, '_nav_menu_icon', $_POST['menu_item_nav_icon'][$menuItemId] );
} else {
delete_post_meta( $menuItemId, '_nav_menu_icon' );
}
}, 10, 2 );
```
and thats it, you now have additional data connected to each menu item for nav icon that supports text and html, you can add html tag like `<img />` for adding image as menu icon, or `svg`,
To display on the front-end, this depends on your set-up and where you want them to show
an example below that modify the nav menu item title via `nav_menu_item_title` filter and include the icon using `get_post_meta` to pull the icon value
```
add_filter( 'nav_menu_item_title', function( $title, $item) {
if( is_object( $item ) && isset( $item->ID ) ) {
$navIcon = get_post_meta( $item->ID, '_nav_menu_icon', true );
if ( ! empty( $navIcon ) ) {
$title = '<span class="icon">'.$navIcon.'</span>' . $title;
}
}
return $title;
}, 10, 2 );
```
and the title would show the svg icon if there is
[](https://i.stack.imgur.com/42ziY.png) |
409,514 | <p>Did the Pullquote block styles disappear in the editor?</p>
<p>There used to be a <strong>Styles</strong> section in the sidebar panel with the "Default" and "Solid Color" options, as it is written in the <a href="https://wordpress.org/support/article/pullquote-block/" rel="nofollow noreferrer">documentation</a>:</p>
<p><a href="https://i.stack.imgur.com/U5reH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U5reH.png" alt="pullquote block styles" /></a></p>
<p>But in wordpress 6.0.2 it does not seem to show up anymore.</p>
| [
{
"answer_id": 409492,
"author": "Steve",
"author_id": 3206,
"author_profile": "https://wordpress.stackexchange.com/users/3206",
"pm_score": 0,
"selected": false,
"text": "<p>I changed the function definition to</p>\n<pre><code>function start_el(&$output, $item, $depth = 0, $args=[], current_object_id = 0) \n</code></pre>\n<p>and it activated okay.</p>\n"
},
{
"answer_id": 409494,
"author": "silver",
"author_id": 80499,
"author_profile": "https://wordpress.stackexchange.com/users/80499",
"pm_score": 1,
"selected": false,
"text": "<p>An entirely different approach.</p>\n<p>nav menu item are stored in posts table, so you can technically attach a post_meta into it, even other data like nav item class already stored in post mata table. However this wasn't easy to do before.</p>\n<p>but after 5.4.0 release, they have implemented hooks to easily do this.</p>\n<p>Here's the full step</p>\n<p><strong>Add Custom Meta box on Nav item</strong></p>\n<pre><code>add_action( 'wp_nav_menu_item_custom_fields', function( $id, $navItem) {\n\n wp_nonce_field( 'nav_menu_icon_nonce', '_nav_menu_icon_nonce_name' );\n $nav_menu_icon = get_post_meta( $id, '_nav_menu_icon', true );\n ?>\n <p class="field-nav-icon nav-icon description-wide">\n <label for="edit-menu-item-nav-icon-<?php echo $id ;?>">\n Nav Icon<br>\n <textarea id="edit-menu-item-nav-icon-<?php echo $id ;?>" class="widefat edit-menu-item-nav-icon" rows="3" cols="20" name="menu_item_nav_icon[<?php echo $id ;?>]"><?php echo esc_attr( $nav_menu_icon ); ?></textarea>\n <span class="description">Add icon on menu.</span>\n </label>\n </p>\n <?php\n}, 10, 2 );\n</code></pre>\n<p>There should be another box in nav item after adding the code above like this\n<a href=\"https://i.stack.imgur.com/QWcfX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QWcfX.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Then save the value of that field into post meta</strong></p>\n<pre><code>add_action( 'wp_update_nav_menu_item', function($menuId, $menuItemId) {\n\n // current_user_can( 'unfiltered_html' ) is a wordpress role which ensure the user can post unfiltered html\n if ( ! isset( $_POST['_nav_menu_icon_nonce_name'] ) || ! wp_verify_nonce( $_POST['_nav_menu_icon_nonce_name'], 'nav_menu_icon_nonce' ) || !current_user_can( 'unfiltered_html' ) ) \n return $menuId;\n \n if ( isset( $_POST['menu_item_nav_icon'][$menuItemId] ) ) {\n update_post_meta( $menuItemId, '_nav_menu_icon', $_POST['menu_item_nav_icon'][$menuItemId] );\n } else {\n delete_post_meta( $menuItemId, '_nav_menu_icon' );\n }\n}, 10, 2 );\n</code></pre>\n<p>and thats it, you now have additional data connected to each menu item for nav icon that supports text and html, you can add html tag like <code><img /></code> for adding image as menu icon, or <code>svg</code>,</p>\n<p>To display on the front-end, this depends on your set-up and where you want them to show</p>\n<p>an example below that modify the nav menu item title via <code>nav_menu_item_title</code> filter and include the icon using <code>get_post_meta</code> to pull the icon value</p>\n<pre><code>add_filter( 'nav_menu_item_title', function( $title, $item) {\n \n if( is_object( $item ) && isset( $item->ID ) ) {\n \n $navIcon = get_post_meta( $item->ID, '_nav_menu_icon', true );\n \n if ( ! empty( $navIcon ) ) {\n $title = '<span class="icon">'.$navIcon.'</span>' . $title;\n }\n \n }\n return $title;\n \n}, 10, 2 );\n</code></pre>\n<p>and the title would show the svg icon if there is</p>\n<p><a href=\"https://i.stack.imgur.com/42ziY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/42ziY.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2022/09/15 | [
"https://wordpress.stackexchange.com/questions/409514",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66405/"
] | Did the Pullquote block styles disappear in the editor?
There used to be a **Styles** section in the sidebar panel with the "Default" and "Solid Color" options, as it is written in the [documentation](https://wordpress.org/support/article/pullquote-block/):
[](https://i.stack.imgur.com/U5reH.png)
But in wordpress 6.0.2 it does not seem to show up anymore. | An entirely different approach.
nav menu item are stored in posts table, so you can technically attach a post\_meta into it, even other data like nav item class already stored in post mata table. However this wasn't easy to do before.
but after 5.4.0 release, they have implemented hooks to easily do this.
Here's the full step
**Add Custom Meta box on Nav item**
```
add_action( 'wp_nav_menu_item_custom_fields', function( $id, $navItem) {
wp_nonce_field( 'nav_menu_icon_nonce', '_nav_menu_icon_nonce_name' );
$nav_menu_icon = get_post_meta( $id, '_nav_menu_icon', true );
?>
<p class="field-nav-icon nav-icon description-wide">
<label for="edit-menu-item-nav-icon-<?php echo $id ;?>">
Nav Icon<br>
<textarea id="edit-menu-item-nav-icon-<?php echo $id ;?>" class="widefat edit-menu-item-nav-icon" rows="3" cols="20" name="menu_item_nav_icon[<?php echo $id ;?>]"><?php echo esc_attr( $nav_menu_icon ); ?></textarea>
<span class="description">Add icon on menu.</span>
</label>
</p>
<?php
}, 10, 2 );
```
There should be another box in nav item after adding the code above like this
[](https://i.stack.imgur.com/QWcfX.png)
**Then save the value of that field into post meta**
```
add_action( 'wp_update_nav_menu_item', function($menuId, $menuItemId) {
// current_user_can( 'unfiltered_html' ) is a wordpress role which ensure the user can post unfiltered html
if ( ! isset( $_POST['_nav_menu_icon_nonce_name'] ) || ! wp_verify_nonce( $_POST['_nav_menu_icon_nonce_name'], 'nav_menu_icon_nonce' ) || !current_user_can( 'unfiltered_html' ) )
return $menuId;
if ( isset( $_POST['menu_item_nav_icon'][$menuItemId] ) ) {
update_post_meta( $menuItemId, '_nav_menu_icon', $_POST['menu_item_nav_icon'][$menuItemId] );
} else {
delete_post_meta( $menuItemId, '_nav_menu_icon' );
}
}, 10, 2 );
```
and thats it, you now have additional data connected to each menu item for nav icon that supports text and html, you can add html tag like `<img />` for adding image as menu icon, or `svg`,
To display on the front-end, this depends on your set-up and where you want them to show
an example below that modify the nav menu item title via `nav_menu_item_title` filter and include the icon using `get_post_meta` to pull the icon value
```
add_filter( 'nav_menu_item_title', function( $title, $item) {
if( is_object( $item ) && isset( $item->ID ) ) {
$navIcon = get_post_meta( $item->ID, '_nav_menu_icon', true );
if ( ! empty( $navIcon ) ) {
$title = '<span class="icon">'.$navIcon.'</span>' . $title;
}
}
return $title;
}, 10, 2 );
```
and the title would show the svg icon if there is
[](https://i.stack.imgur.com/42ziY.png) |
409,543 | <p><a href="https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/" rel="nofollow noreferrer">FormTokenField</a> component has <a href="https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/#properties" rel="nofollow noreferrer">suggestions property</a> which provides a list of suggestions when user start typing.</p>
<p>But, FormTokenField also accepts any value, if separated by comma, even if it is not defined in the suggestions property. Just like you can add anything to Post Categories and Post Tags field.</p>
<p>Is there a way to prevent this? I would like to limit users to be able to only add items from suggestions.</p>
<p>Or, if this is not possible with the FormTokenField, is there any other component that could do this - allow users to select multiple items from predefined lists of options?</p>
| [
{
"answer_id": 409549,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 1,
"selected": false,
"text": "<p>The validation feature is currently flagged as "experimental," which means that it may change at any point without warning and may require the Gutenberg plugin to use. If you do choose to use it, you'll want to keep an eye out for updates on the status of the interface.</p>\n<p>It's exposed through the <code>__experimentalValidateInput</code> prop which is passed a callback. The callback receives a newly input value as an argument, and may return a truthy value to accept the input or a falsey value to deny it. You might use it as such:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { FormTokenField } from '@wordpress/components'\nimport { useSelect } from '@wordpress/data';\n\n// A multiple Post-Type selection control implemented on top of FormTokenField.\nconst PostTypesControl = ( props ) => {\n const { value = [], onChange } = props;\n\n const types = useSelect(\n ( select ) => ( select( 'core' ).getPostTypes() ?? [] ).map( ( { slug, name } ) => ( { value: slug, title: name } ) ),\n []\n );\n\n const tokenIsValid = ( title ) => types.some( type => type.title === title );\n const titleToValue = ( title ) => title ? types.find( type => type.title === title )?.value || '' : '';\n\n return (\n <FormTokenField\n value={ value }\n onChange={ onChange }\n suggestions={ types.map( type => type.title ) }\n saveTransform={ titleToValue }\n __experimentalValidateInput={ tokenIsValid }\n />\n );\n};\n</code></pre>\n<blockquote>\n<p>is there any other component that could do this - allow users to select multiple items from predefined lists of options?</p>\n</blockquote>\n<p><a href=\"https://wordpress.github.io/gutenberg/?path=/story/components-selectcontrol--default\" rel=\"nofollow noreferrer\"><code><SelectControl></code></a> with <code>multiple</code> enabled comes to mind, but there may be others.</p>\n"
},
{
"answer_id": 409550,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>On a recent project I handled this by just filtering out invalid values in the <code>onChange</code> callback:</p>\n<pre><code>export default () => {\n const [value, setValue] = useState([]);\n const suggestions = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];\n\n const onChange = (tokens) => {\n const value = tokens.filter((t) => suggestions.includes(t));\n\n setValue(value);\n };\n\n return <FormTokenField onChange={onChange} suggestions={suggestions} value={value} />;\n};\n</code></pre>\n"
}
] | 2022/09/16 | [
"https://wordpress.stackexchange.com/questions/409543",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148666/"
] | [FormTokenField](https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/) component has [suggestions property](https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/#properties) which provides a list of suggestions when user start typing.
But, FormTokenField also accepts any value, if separated by comma, even if it is not defined in the suggestions property. Just like you can add anything to Post Categories and Post Tags field.
Is there a way to prevent this? I would like to limit users to be able to only add items from suggestions.
Or, if this is not possible with the FormTokenField, is there any other component that could do this - allow users to select multiple items from predefined lists of options? | On a recent project I handled this by just filtering out invalid values in the `onChange` callback:
```
export default () => {
const [value, setValue] = useState([]);
const suggestions = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];
const onChange = (tokens) => {
const value = tokens.filter((t) => suggestions.includes(t));
setValue(value);
};
return <FormTokenField onChange={onChange} suggestions={suggestions} value={value} />;
};
``` |
409,624 | <p>It seems not possible to write :</p>
<pre><code>register_taxonomy('category',array('events'), array(
'hierarchical' => true,
'labels' => $labels_category_events,
'show_ui' => true,
'show_in_rest' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => "evenements/category" ),
'has_archive' => true,
));
</code></pre>
<p>without having conflict with "real" categories ?
Thank to confirm ... or not .</p>
| [
{
"answer_id": 409629,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>No, as WordPress by default register a taxonomy called category (which is linked with blog posts). However, you can assign this taxonomy(category) to your custom post type too.<br />\nusing the following code snippet.</p>\n<pre><code>add_action( 'init', 'pixel_add_category_cpt' );\nfunction pixel_add_category_cpt() {\n register_taxonomy_for_object_type( 'events', 'course' );\n\n}\n</code></pre>\n"
},
{
"answer_id": 409638,
"author": "Sébastien Serre",
"author_id": 62892,
"author_profile": "https://wordpress.stackexchange.com/users/62892",
"pm_score": 1,
"selected": false,
"text": "<p>As said, you can't and here's the list of reserved terms: <a href=\"https://codex.wordpress.org/Reserved_Terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Reserved_Terms</a></p>\n"
}
] | 2022/09/19 | [
"https://wordpress.stackexchange.com/questions/409624",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201582/"
] | It seems not possible to write :
```
register_taxonomy('category',array('events'), array(
'hierarchical' => true,
'labels' => $labels_category_events,
'show_ui' => true,
'show_in_rest' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => "evenements/category" ),
'has_archive' => true,
));
```
without having conflict with "real" categories ?
Thank to confirm ... or not . | As said, you can't and here's the list of reserved terms: <https://codex.wordpress.org/Reserved_Terms> |
409,639 | <p>I'm trying to write a function that checks if a specific role exists. I found the following code on the web but it doesn't work for me:</p>
<pre><code>function role_exists( $role ) {
if ( ! empty( $role ) ) {
return $GLOBALS['wp_roles']->is_role( $role );
}
return false;
}
</code></pre>
<p>I get the following error message: Fatal error: Uncaught Error: Call to a member function is_role() on null in C:\xampp...</p>
<p>I tried to output <code>$GLOBALS['wp_roles']</code> with a <code>print_r</code> but it's empty.</p>
<p>What am I missing? Thanks</p>
| [
{
"answer_id": 409629,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>No, as WordPress by default register a taxonomy called category (which is linked with blog posts). However, you can assign this taxonomy(category) to your custom post type too.<br />\nusing the following code snippet.</p>\n<pre><code>add_action( 'init', 'pixel_add_category_cpt' );\nfunction pixel_add_category_cpt() {\n register_taxonomy_for_object_type( 'events', 'course' );\n\n}\n</code></pre>\n"
},
{
"answer_id": 409638,
"author": "Sébastien Serre",
"author_id": 62892,
"author_profile": "https://wordpress.stackexchange.com/users/62892",
"pm_score": 1,
"selected": false,
"text": "<p>As said, you can't and here's the list of reserved terms: <a href=\"https://codex.wordpress.org/Reserved_Terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Reserved_Terms</a></p>\n"
}
] | 2022/09/19 | [
"https://wordpress.stackexchange.com/questions/409639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225929/"
] | I'm trying to write a function that checks if a specific role exists. I found the following code on the web but it doesn't work for me:
```
function role_exists( $role ) {
if ( ! empty( $role ) ) {
return $GLOBALS['wp_roles']->is_role( $role );
}
return false;
}
```
I get the following error message: Fatal error: Uncaught Error: Call to a member function is\_role() on null in C:\xampp...
I tried to output `$GLOBALS['wp_roles']` with a `print_r` but it's empty.
What am I missing? Thanks | As said, you can't and here's the list of reserved terms: <https://codex.wordpress.org/Reserved_Terms> |
409,659 | <p>I have some problem with the <a href="https://github.com/deliciousbrains/wp-background-processing" rel="nofollow noreferrer">wp-background-processing</a> that's when I change the <code>$url</code> in another file using <code>$this->process_single->url('https://anotherexample.com');</code> the url won't update in handle function :/ but when I echo it in dispatch, it shows the updated url</p>
<p>here is my <code>class-example-request.php</code> file:</p>
<pre class="lang-php prettyprint-override"><code><?php
class WP_Example_Request extends WP_Async_Request {
/**
* @var string
*/
protected $action = 'example_request';
protected $url = "https://example.com";
public function url($url){
$this->url = $url;
return $this;
}
public function get_url(){
return $this->url;
}
public function handle() {
$response = wp_remote_get( esc_url_raw( $this->get_url() ) );//here, the url won't update!
}
public function dispatch() {
$url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
$args = $this->get_post_args();
echo $this->get_url(); // this echos the updated url
return wp_remote_post( esc_url_raw( $url ), $args );
}
}
</code></pre>
<p>any ideas?</p>
<p>update:</p>
<p>This is my main plugin file</p>
<pre class="lang-php prettyprint-override"><code><?php
/*
Plugin info...
*/
class Example_Background_Processing {
protected $process_single;
public function __construct() {
add_action( 'plugins_loaded', array( $this, 'init' ) );
add_action( 'woocommerce_add_to_cart', array($this, 'add_to_cart_callback'), 10, 2);
}
public function init() {
require_once plugin_dir_path( __FILE__ ) . 'async-requests/class-example-request.php';
$this->process_single = new WP_Example_Request();
}
public function add_to_cart_callback($cart_item_data, $productId){
$this->process_single->url('https://httpbin.org/anything');
$this->process_single->data( array() );
$this->process_single->dispatch();
}
}
new Example_Background_Processing();
</code></pre>
| [
{
"answer_id": 409660,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": -1,
"selected": false,
"text": "<p>You need to change the method use for the variable $url</p>\n<ul>\n<li><p>public - the property or method can be accessed from everywhere. This\nis default</p>\n</li>\n<li><p>protected - the property or method can be accessed within the class\nand by classes derived from that class</p>\n</li>\n<li><p>private - the property or method can ONLY be accessed within the\nclass</p>\n</li>\n</ul>\n<p>In your case your script is not allowed to modify a protected variable.\nChange it to public.</p>\n"
},
{
"answer_id": 409671,
"author": "Erfan Paslar",
"author_id": 214004,
"author_profile": "https://wordpress.stackexchange.com/users/214004",
"pm_score": 2,
"selected": true,
"text": "<p>A huge thanks to @JacobPeattie</p>\n<p>We should pass the url to <code>data</code> function and retrieve it using <code>_POST</code></p>\n<p>so the main file will be:</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n/* \nPlugin info...\n*/\nclass Example_Background_Processing {\n protected $process_single;\n public function __construct() {\n add_action( 'plugins_loaded', array( $this, 'init' ) );\n add_action( 'woocommerce_add_to_cart', array($this, 'add_to_cart_callback'), 10, 2);\n \n }\n\n\n public function init() {\n \n require_once plugin_dir_path( __FILE__ ) . 'async-requests/class-example-request.php';\n \n $this->process_single = new WP_Example_Request();\n }\n \n public function add_to_cart_callback($cart_item_data, $productId){\n\n $this->process_single->data( array('url'=>'https://httpbin.org/anything') )->dispatch();\n }\n\n}\nnew Example_Background_Processing();\n</code></pre>\n<p>and the <code>class-example-request.php</code> file will be:</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nclass WP_Example_Request extends WP_Async_Request {\n\n /**\n * @var string\n */\n protected $action = 'example_request';\n\n public function handle() {\n $url = $_POST['url'];\n $response = wp_remote_get( esc_url_raw( $url );\n }\n\n}\n</code></pre>\n<p>if the request has payloads, we could pass it like the url.</p>\n<p>@JacobPeattie feel free to edit the answer.</p>\n"
}
] | 2022/09/20 | [
"https://wordpress.stackexchange.com/questions/409659",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/214004/"
] | I have some problem with the [wp-background-processing](https://github.com/deliciousbrains/wp-background-processing) that's when I change the `$url` in another file using `$this->process_single->url('https://anotherexample.com');` the url won't update in handle function :/ but when I echo it in dispatch, it shows the updated url
here is my `class-example-request.php` file:
```php
<?php
class WP_Example_Request extends WP_Async_Request {
/**
* @var string
*/
protected $action = 'example_request';
protected $url = "https://example.com";
public function url($url){
$this->url = $url;
return $this;
}
public function get_url(){
return $this->url;
}
public function handle() {
$response = wp_remote_get( esc_url_raw( $this->get_url() ) );//here, the url won't update!
}
public function dispatch() {
$url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
$args = $this->get_post_args();
echo $this->get_url(); // this echos the updated url
return wp_remote_post( esc_url_raw( $url ), $args );
}
}
```
any ideas?
update:
This is my main plugin file
```php
<?php
/*
Plugin info...
*/
class Example_Background_Processing {
protected $process_single;
public function __construct() {
add_action( 'plugins_loaded', array( $this, 'init' ) );
add_action( 'woocommerce_add_to_cart', array($this, 'add_to_cart_callback'), 10, 2);
}
public function init() {
require_once plugin_dir_path( __FILE__ ) . 'async-requests/class-example-request.php';
$this->process_single = new WP_Example_Request();
}
public function add_to_cart_callback($cart_item_data, $productId){
$this->process_single->url('https://httpbin.org/anything');
$this->process_single->data( array() );
$this->process_single->dispatch();
}
}
new Example_Background_Processing();
``` | A huge thanks to @JacobPeattie
We should pass the url to `data` function and retrieve it using `_POST`
so the main file will be:
```php
<?php
/*
Plugin info...
*/
class Example_Background_Processing {
protected $process_single;
public function __construct() {
add_action( 'plugins_loaded', array( $this, 'init' ) );
add_action( 'woocommerce_add_to_cart', array($this, 'add_to_cart_callback'), 10, 2);
}
public function init() {
require_once plugin_dir_path( __FILE__ ) . 'async-requests/class-example-request.php';
$this->process_single = new WP_Example_Request();
}
public function add_to_cart_callback($cart_item_data, $productId){
$this->process_single->data( array('url'=>'https://httpbin.org/anything') )->dispatch();
}
}
new Example_Background_Processing();
```
and the `class-example-request.php` file will be:
```php
<?php
class WP_Example_Request extends WP_Async_Request {
/**
* @var string
*/
protected $action = 'example_request';
public function handle() {
$url = $_POST['url'];
$response = wp_remote_get( esc_url_raw( $url );
}
}
```
if the request has payloads, we could pass it like the url.
@JacobPeattie feel free to edit the answer. |
409,720 | <p>I'm trying to add a new role to my website that is based on administrator's role. I want my new role to have all the capabilities admin has. Problem is, when I log in with my new user, I can't access the admin dashboard. I can only change my profile. Here's my code:</p>
<pre><code>function quick_remove_role() {
remove_role( 'manager' );
}
add_action( 'init', 'quick_remove_role' );
if ( ! ( role_exists( 'manager' ) ) ) {
function new_role_manager() {
global $wp_roles;
if ( ! isset( $wp_roles ) ) {
$wp_roles = new WP_Roles();
}
$adm = $wp_roles->get_role( 'administrator' );
$wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );
}
add_action( 'init', 'new_role_manager' );
}
</code></pre>
<p>What I am doing wrong?</p>
| [
{
"answer_id": 409749,
"author": "ddur",
"author_id": 160028,
"author_profile": "https://wordpress.stackexchange.com/users/160028",
"pm_score": 0,
"selected": false,
"text": "<p>How about <a href=\"https://wpmudev.com/blog/change-wordpress-role-names/\" rel=\"nofollow noreferrer\">renaming</a> 'administrator' role to 'manager' or use <a href=\"https://wordpress.org/plugins/search/roles/\" rel=\"nofollow noreferrer\">role editor plugin</a>?</p>\n"
},
{
"answer_id": 409762,
"author": "Francis Bégin",
"author_id": 225929,
"author_profile": "https://wordpress.stackexchange.com/users/225929",
"pm_score": 1,
"selected": false,
"text": "<p>I found the solution to my problem. It had to do with my function that removes the manager role. I commented it out, and it works. My bad. Here's the working code:</p>\n<pre><code>if ( ! ( role_exists( 'manager' ) ) ) {\n function new_role_manager() {\n global $wp_roles;\n\n if ( ! isset( $wp_roles ) ) {\n $wp_roles = new WP_Roles();\n }\n\n $adm = $wp_roles->get_role( 'administrator' );\n\n $wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );\n }\n\n add_action( 'init', 'new_role_manager' );\n}\n</code></pre>\n<p>Thanks</p>\n"
}
] | 2022/09/21 | [
"https://wordpress.stackexchange.com/questions/409720",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225929/"
] | I'm trying to add a new role to my website that is based on administrator's role. I want my new role to have all the capabilities admin has. Problem is, when I log in with my new user, I can't access the admin dashboard. I can only change my profile. Here's my code:
```
function quick_remove_role() {
remove_role( 'manager' );
}
add_action( 'init', 'quick_remove_role' );
if ( ! ( role_exists( 'manager' ) ) ) {
function new_role_manager() {
global $wp_roles;
if ( ! isset( $wp_roles ) ) {
$wp_roles = new WP_Roles();
}
$adm = $wp_roles->get_role( 'administrator' );
$wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );
}
add_action( 'init', 'new_role_manager' );
}
```
What I am doing wrong? | I found the solution to my problem. It had to do with my function that removes the manager role. I commented it out, and it works. My bad. Here's the working code:
```
if ( ! ( role_exists( 'manager' ) ) ) {
function new_role_manager() {
global $wp_roles;
if ( ! isset( $wp_roles ) ) {
$wp_roles = new WP_Roles();
}
$adm = $wp_roles->get_role( 'administrator' );
$wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );
}
add_action( 'init', 'new_role_manager' );
}
```
Thanks |
409,721 | <p>Each time I attempt to import my test server db into my production server, I get the error below:</p>
<blockquote>
<p>WordPress database error Table 'adminjsds_wordpress.wp_actionscheduler_actions' doesn't exist for query SELECT a.action_id FROM wp_actionscheduler_actions a WHERE 1=1 AND a.hook='action_scheduler/migration_hook' AND a.status IN ('in-progress') ORDER BY a.scheduled_date_gmt ASC LIMIT 0, 1 made by include('phar:///usr/local/bin/wp/php/boot-phar.php'), include('phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/wp-cli.php'), WP_CLI\bootstrap, WP_CLI\Bootstrap\LaunchRunner->process, WP_CLI\Runner->start, WP_CLI\Runner->load_wordpress, require('wp-settings.php'), do_action('wp_loaded'), WP_Hook->do_action, WP_Hook->apply_filters, Action_Scheduler\Migration\Controller->schedule_migration, Action_Scheduler\Migration\Scheduler->is_migration_scheduled, as_next_scheduled_action, ActionScheduler_Store->query_action, ActionScheduler_HybridStore->query_actions, ActionScheduler_DBStore->query_actions
WordPress database error Table 'adminjsds_wordpress.wp_actionscheduler_actions' doesn't exist for query SELECT a.action_id FROM wp_actionscheduler_actions a WHERE 1=1 AND a.hook='action_scheduler/migration_hook' AND a.status IN ('pending') ORDER BY a.scheduled_date_gmt ASC LIMIT 0, 1 made by include('phar:///usr/local/bin/wp/php/boot-phar.php'), include('phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/wp-cli.php'), WP_CLI\bootstrap, WP_CLI\Bootstrap\LaunchRunner->process, WP_CLI\Runner->start, WP_CLI\Runner->load_wordpress, require('wp-settings.php'), do_action('wp_loaded'), WP_Hook->do_action, WP_Hook->apply_filters, Action_Scheduler\Migration\Controller->schedule_migration, Action_Scheduler\Migration\Scheduler->is_migration_scheduled, as_next_scheduled_action, ActionScheduler_Store->query_action, ActionScheduler_HybridStore->query_actions, ActionScheduler_DBStore->query_actions</p>
</blockquote>
<p>My question is not specific to the above error. As I get bunches of table related errors when importing / exporting dbs. My question is conceptual.</p>
<p><strong>Question</strong><br />
Is there a reliable way to determine which table was created by which plugin? I can't troubleshoot the error without knowing which plugin is causing it.</p>
<p>Is there any type of "Registry of Tables For Plugins" that can easily determine which table belong to which plugins?</p>
| [
{
"answer_id": 409749,
"author": "ddur",
"author_id": 160028,
"author_profile": "https://wordpress.stackexchange.com/users/160028",
"pm_score": 0,
"selected": false,
"text": "<p>How about <a href=\"https://wpmudev.com/blog/change-wordpress-role-names/\" rel=\"nofollow noreferrer\">renaming</a> 'administrator' role to 'manager' or use <a href=\"https://wordpress.org/plugins/search/roles/\" rel=\"nofollow noreferrer\">role editor plugin</a>?</p>\n"
},
{
"answer_id": 409762,
"author": "Francis Bégin",
"author_id": 225929,
"author_profile": "https://wordpress.stackexchange.com/users/225929",
"pm_score": 1,
"selected": false,
"text": "<p>I found the solution to my problem. It had to do with my function that removes the manager role. I commented it out, and it works. My bad. Here's the working code:</p>\n<pre><code>if ( ! ( role_exists( 'manager' ) ) ) {\n function new_role_manager() {\n global $wp_roles;\n\n if ( ! isset( $wp_roles ) ) {\n $wp_roles = new WP_Roles();\n }\n\n $adm = $wp_roles->get_role( 'administrator' );\n\n $wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );\n }\n\n add_action( 'init', 'new_role_manager' );\n}\n</code></pre>\n<p>Thanks</p>\n"
}
] | 2022/09/21 | [
"https://wordpress.stackexchange.com/questions/409721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190801/"
] | Each time I attempt to import my test server db into my production server, I get the error below:
>
> WordPress database error Table 'adminjsds\_wordpress.wp\_actionscheduler\_actions' doesn't exist for query SELECT a.action\_id FROM wp\_actionscheduler\_actions a WHERE 1=1 AND a.hook='action\_scheduler/migration\_hook' AND a.status IN ('in-progress') ORDER BY a.scheduled\_date\_gmt ASC LIMIT 0, 1 made by include('phar:///usr/local/bin/wp/php/boot-phar.php'), include('phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/wp-cli.php'), WP\_CLI\bootstrap, WP\_CLI\Bootstrap\LaunchRunner->process, WP\_CLI\Runner->start, WP\_CLI\Runner->load\_wordpress, require('wp-settings.php'), do\_action('wp\_loaded'), WP\_Hook->do\_action, WP\_Hook->apply\_filters, Action\_Scheduler\Migration\Controller->schedule\_migration, Action\_Scheduler\Migration\Scheduler->is\_migration\_scheduled, as\_next\_scheduled\_action, ActionScheduler\_Store->query\_action, ActionScheduler\_HybridStore->query\_actions, ActionScheduler\_DBStore->query\_actions
> WordPress database error Table 'adminjsds\_wordpress.wp\_actionscheduler\_actions' doesn't exist for query SELECT a.action\_id FROM wp\_actionscheduler\_actions a WHERE 1=1 AND a.hook='action\_scheduler/migration\_hook' AND a.status IN ('pending') ORDER BY a.scheduled\_date\_gmt ASC LIMIT 0, 1 made by include('phar:///usr/local/bin/wp/php/boot-phar.php'), include('phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/wp-cli.php'), WP\_CLI\bootstrap, WP\_CLI\Bootstrap\LaunchRunner->process, WP\_CLI\Runner->start, WP\_CLI\Runner->load\_wordpress, require('wp-settings.php'), do\_action('wp\_loaded'), WP\_Hook->do\_action, WP\_Hook->apply\_filters, Action\_Scheduler\Migration\Controller->schedule\_migration, Action\_Scheduler\Migration\Scheduler->is\_migration\_scheduled, as\_next\_scheduled\_action, ActionScheduler\_Store->query\_action, ActionScheduler\_HybridStore->query\_actions, ActionScheduler\_DBStore->query\_actions
>
>
>
My question is not specific to the above error. As I get bunches of table related errors when importing / exporting dbs. My question is conceptual.
**Question**
Is there a reliable way to determine which table was created by which plugin? I can't troubleshoot the error without knowing which plugin is causing it.
Is there any type of "Registry of Tables For Plugins" that can easily determine which table belong to which plugins? | I found the solution to my problem. It had to do with my function that removes the manager role. I commented it out, and it works. My bad. Here's the working code:
```
if ( ! ( role_exists( 'manager' ) ) ) {
function new_role_manager() {
global $wp_roles;
if ( ! isset( $wp_roles ) ) {
$wp_roles = new WP_Roles();
}
$adm = $wp_roles->get_role( 'administrator' );
$wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );
}
add_action( 'init', 'new_role_manager' );
}
```
Thanks |
409,777 | <p>I have a user base of hundreds of users, and trying to create a custom API endpoint to get users in a specific membership group.</p>
<p>The database structure is as follows (<strong>using Ultimate Member plugin</strong>):</p>
<ul>
<li>User is stored in <code>wpma_users</code> table</li>
<li>User metadata in table <code>wpma_usermeta</code> contains user meta named <code>mygroups</code>, containing a value <code>a:1:{i:0;s:3:"155";}</code></li>
<li>The <code>155</code> value is the ID of a term</li>
</ul>
<p>I already tried this, with <code>$groupid=155</code>:</p>
<pre><code>$args = array(
'fields' => 'all_with_meta',
'tax_query' => array(
array(
'taxonomy' => 'mygroups',
'field' => 'term_id',
'terms' => $groupid,
),
),
);
$user_query = new WP_User_Query($args);
</code></pre>
<p>When I var_dump <code>get_terms(array('include' => $groupid))</code>, an actual term is printed:</p>
<pre><code>array(1){
[
0
]=>object(WP_Term)#27633(10){
[
"term_id"
]=>int(155)[
"name"
]=>string(8)"Example Group"[
"slug"
]=>string(8)"example_group"[
"term_group"
]=>int(0)[
"term_taxonomy_id"
]=>int(155)[
"taxonomy"
]=>string(11)"um_user_tag"[
"description"
]=>string(0)""[
"parent"
]=>int(149)[
"count"
]=>int(1)[
"filter"
]=>string(3)"raw"
}
}
</code></pre>
<p>Another way I tried, is using the <code>meta_query</code> instead of the tax_query:</p>
<pre><code>'meta_query' => array(
array(
'key' => 'mygroups',
'value' => $groupid,
'compare' => 'LIKE',
)
),
</code></pre>
<p>This actually filters the query, but when I use <code>$groupid=1</code>, it filters where <code>groupid</code> contains <code>1</code>, so also <code>10</code>, <code>11</code>, <code>100</code> etc.</p>
<p>Who can point me in the right direction to filter the user on <code>mygroups</code> the right way?</p>
| [
{
"answer_id": 409779,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't possible, you can't safely/reliably query the internals of meta value strings that way, and you can't use it as a form of indirection:</p>\n<ul>\n<li>You can query for substrings or for whole values, but you can't query the internals of serialised PHP values without major performance reliability and consistency issues</li>\n<li>but if you could, or if it was just the plain number, there's no way to then take that and plug it into a term query</li>\n<li>You can only use <code>tax_query</code> to find users in a given taxonomy, but your users don't have terms, and they aren't in a taxonomy.</li>\n</ul>\n<p>User taxonomies are a thing, so be careful about what you're asking. Instead, you need to rephrase your question like this:</p>\n<blockquote>\n<p>How do I find users with a specific value that's listed in the <code>mygroups</code> user meta field using <code>WP_User_Query</code>?</p>\n</blockquote>\n<p>And the answer is, you can't. This is because <code>mygroups</code> is stored as a serialised PHP array, and you can't query sub-values of serialised values. E.g. you could use a LIKE style parameter to search for group 1 but it will also give you 10, 100, 41, etc It may even give you users who have a group number that is 1 digit long, and users that have 1 group even if that groups number is 9999.</p>\n<p>It may be that there is a solution that uses features of the Ultimate Member plugin, but questions about that plugin and other 3rd party plugins are off-topic here and not in this stacks scope</p>\n"
},
{
"answer_id": 409841,
"author": "harmjanr",
"author_id": 226048,
"author_profile": "https://wordpress.stackexchange.com/users/226048",
"pm_score": 1,
"selected": true,
"text": "<p>I found a solution, since the serialized array is always structured like this: <code>':"%s";'</code>, it is possible to write a meta_query like:</p>\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'mygroups',\n 'value' => sprintf(':"%s";', $groupid),\n 'compare' => 'LIKE'\n )\n)\n</code></pre>\n<p>Works like a charm!</p>\n"
}
] | 2022/09/23 | [
"https://wordpress.stackexchange.com/questions/409777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226048/"
] | I have a user base of hundreds of users, and trying to create a custom API endpoint to get users in a specific membership group.
The database structure is as follows (**using Ultimate Member plugin**):
* User is stored in `wpma_users` table
* User metadata in table `wpma_usermeta` contains user meta named `mygroups`, containing a value `a:1:{i:0;s:3:"155";}`
* The `155` value is the ID of a term
I already tried this, with `$groupid=155`:
```
$args = array(
'fields' => 'all_with_meta',
'tax_query' => array(
array(
'taxonomy' => 'mygroups',
'field' => 'term_id',
'terms' => $groupid,
),
),
);
$user_query = new WP_User_Query($args);
```
When I var\_dump `get_terms(array('include' => $groupid))`, an actual term is printed:
```
array(1){
[
0
]=>object(WP_Term)#27633(10){
[
"term_id"
]=>int(155)[
"name"
]=>string(8)"Example Group"[
"slug"
]=>string(8)"example_group"[
"term_group"
]=>int(0)[
"term_taxonomy_id"
]=>int(155)[
"taxonomy"
]=>string(11)"um_user_tag"[
"description"
]=>string(0)""[
"parent"
]=>int(149)[
"count"
]=>int(1)[
"filter"
]=>string(3)"raw"
}
}
```
Another way I tried, is using the `meta_query` instead of the tax\_query:
```
'meta_query' => array(
array(
'key' => 'mygroups',
'value' => $groupid,
'compare' => 'LIKE',
)
),
```
This actually filters the query, but when I use `$groupid=1`, it filters where `groupid` contains `1`, so also `10`, `11`, `100` etc.
Who can point me in the right direction to filter the user on `mygroups` the right way? | I found a solution, since the serialized array is always structured like this: `':"%s";'`, it is possible to write a meta\_query like:
```
'meta_query' => array(
array(
'key' => 'mygroups',
'value' => sprintf(':"%s";', $groupid),
'compare' => 'LIKE'
)
)
```
Works like a charm! |
409,818 | <p>I'm fairly new at this, so please excuse my ignorance.</p>
<p>I'm trying to order my posts in the site's categories with a button, 'ascending' / 'descending'.</p>
<p>I'm trying to use 'sortit' function because that's the only source I could find online; been working on this all the past week.</p>
<p>So what I did here is;</p>
<pre><code> <li class="dropdown">
<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Sırala</a>
<ul class="dropdown-menu">
<li class="nav-item"><a href="?sortby=asc" class="nav-link dropdown-item" type="button" role="tab">Yeniden Eskiye</a></li>
<li class="nav-item"><a href="?sortby=desc" class="nav-link dropdown-item" type="button" role="tab">Eskiden Yeniye</a></li>
</ul>
</li>
</code></pre>
<p>Add a code to the menu, so the URL will be '?sortby=asc' or '?sortby=desc'</p>
<p>(Web site is in Turkish so ignore the texts)</p>
<p>The next step was adding a function.</p>
<pre><code> function sortIt($sortType)
{
global $wp_query;
$cat_ID = get_query_var('cat');
if (strcmp($sortType, 'ASC') )
{
$newQuery = new WP_Query( array(
'orderby' => 'date' ,
'order' => 'ASC',
'cat' => $cat_ID,
'posts_per_page' => '10') );
}
if (strcmp($sortType, 'DESC') )
{
$newQuery = new WP_Query( array(
'orderby' => 'date' ,
'order' => 'DESC',
'cat' => $cat_ID,
'posts_per_page' => '10') );
}
return $newQuery;
}
</code></pre>
<p>Next step is displaying them when the button is clicked, but it will crash into each other with the current order so and if-else must be created here. What I did is</p>
<pre><code><?php if (is_page('echo esc_url( wp_get_current_url()/?sortby=asc')) {
if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post();
} else { if (is_page('echo esc_url( wp_get_current_url()/?sortby=desc')) {
if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post();
} } else { if (have_posts()) : while (have_posts()) : the_post();
} ?>
</code></pre>
<p>But now I'm getting an error, "Parse error: syntax error, unexpected '}' in"</p>
<p>Any ideas? Any help?</p>
<p>Thank you.</p>
| [
{
"answer_id": 409779,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't possible, you can't safely/reliably query the internals of meta value strings that way, and you can't use it as a form of indirection:</p>\n<ul>\n<li>You can query for substrings or for whole values, but you can't query the internals of serialised PHP values without major performance reliability and consistency issues</li>\n<li>but if you could, or if it was just the plain number, there's no way to then take that and plug it into a term query</li>\n<li>You can only use <code>tax_query</code> to find users in a given taxonomy, but your users don't have terms, and they aren't in a taxonomy.</li>\n</ul>\n<p>User taxonomies are a thing, so be careful about what you're asking. Instead, you need to rephrase your question like this:</p>\n<blockquote>\n<p>How do I find users with a specific value that's listed in the <code>mygroups</code> user meta field using <code>WP_User_Query</code>?</p>\n</blockquote>\n<p>And the answer is, you can't. This is because <code>mygroups</code> is stored as a serialised PHP array, and you can't query sub-values of serialised values. E.g. you could use a LIKE style parameter to search for group 1 but it will also give you 10, 100, 41, etc It may even give you users who have a group number that is 1 digit long, and users that have 1 group even if that groups number is 9999.</p>\n<p>It may be that there is a solution that uses features of the Ultimate Member plugin, but questions about that plugin and other 3rd party plugins are off-topic here and not in this stacks scope</p>\n"
},
{
"answer_id": 409841,
"author": "harmjanr",
"author_id": 226048,
"author_profile": "https://wordpress.stackexchange.com/users/226048",
"pm_score": 1,
"selected": true,
"text": "<p>I found a solution, since the serialized array is always structured like this: <code>':"%s";'</code>, it is possible to write a meta_query like:</p>\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'mygroups',\n 'value' => sprintf(':"%s";', $groupid),\n 'compare' => 'LIKE'\n )\n)\n</code></pre>\n<p>Works like a charm!</p>\n"
}
] | 2022/09/24 | [
"https://wordpress.stackexchange.com/questions/409818",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226073/"
] | I'm fairly new at this, so please excuse my ignorance.
I'm trying to order my posts in the site's categories with a button, 'ascending' / 'descending'.
I'm trying to use 'sortit' function because that's the only source I could find online; been working on this all the past week.
So what I did here is;
```
<li class="dropdown">
<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Sırala</a>
<ul class="dropdown-menu">
<li class="nav-item"><a href="?sortby=asc" class="nav-link dropdown-item" type="button" role="tab">Yeniden Eskiye</a></li>
<li class="nav-item"><a href="?sortby=desc" class="nav-link dropdown-item" type="button" role="tab">Eskiden Yeniye</a></li>
</ul>
</li>
```
Add a code to the menu, so the URL will be '?sortby=asc' or '?sortby=desc'
(Web site is in Turkish so ignore the texts)
The next step was adding a function.
```
function sortIt($sortType)
{
global $wp_query;
$cat_ID = get_query_var('cat');
if (strcmp($sortType, 'ASC') )
{
$newQuery = new WP_Query( array(
'orderby' => 'date' ,
'order' => 'ASC',
'cat' => $cat_ID,
'posts_per_page' => '10') );
}
if (strcmp($sortType, 'DESC') )
{
$newQuery = new WP_Query( array(
'orderby' => 'date' ,
'order' => 'DESC',
'cat' => $cat_ID,
'posts_per_page' => '10') );
}
return $newQuery;
}
```
Next step is displaying them when the button is clicked, but it will crash into each other with the current order so and if-else must be created here. What I did is
```
<?php if (is_page('echo esc_url( wp_get_current_url()/?sortby=asc')) {
if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post();
} else { if (is_page('echo esc_url( wp_get_current_url()/?sortby=desc')) {
if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post();
} } else { if (have_posts()) : while (have_posts()) : the_post();
} ?>
```
But now I'm getting an error, "Parse error: syntax error, unexpected '}' in"
Any ideas? Any help?
Thank you. | I found a solution, since the serialized array is always structured like this: `':"%s";'`, it is possible to write a meta\_query like:
```
'meta_query' => array(
array(
'key' => 'mygroups',
'value' => sprintf(':"%s";', $groupid),
'compare' => 'LIKE'
)
)
```
Works like a charm! |
409,926 | <p>I created a custom taxonomies to work like category called projects to be used for the attachments.</p>
<p>I want to be able to create the archive page without having to use the CMS.</p>
<p>Currently the only thing I can figure out is to manually create the projects CMS page and attach the custom template there.</p>
<p>Here is my code for the projects taxonomy ( I edited out labels array to keep it simple):</p>
<pre><code>register_taxonomy(
'projects',
'attachment',
array(
'labels' => array(
'name' => 'Projects',
),
'public' => true,
'hierarchical' => true,
'sort' => true,
'show_admin_column' => true,
'rewrite' => array('slug' => 'projects', 'with_front' => false)
)
);
</code></pre>
<p>To be clear all of the custom taxonomy seems to be working fine, I wanted to share that code mainly to show the rewrite line.</p>
<p>I thought at this point using <a href="https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/" rel="nofollow noreferrer">the template hierarchy</a> I would just need to create a file like
<code>taxonomy-{taxonomy}.php</code></p>
<p>So I created my file taxonomy-projects.php but if I go to mysite.com/projects it is 404.</p>
<p>I have flushed permalinks multiple times and the way those are set are as custom structure:</p>
<p><code>/%category%/%postname%/</code></p>
| [
{
"answer_id": 409928,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>Did you set public to true? As I can remember without it you can't use your taxonomy in your theme.</p>\n<pre><code>public bool\nWhether a taxonomy is intended for use publicly either via the admin interface or by front-end users. The default settings of $publicly_queryable, $show_ui, and $show_in_nav_menus are inherited from $public.\npublicly_queryable bool\nWhether the taxonomy is publicly queryable.\nIf not set, the default is inherited from $public\n</code></pre>\n"
},
{
"answer_id": 409938,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>If you register a taxonomy named <code>projects</code>, and create <code>taxonomy-projects.php</code>, the URL <code>mysite.com/projects</code> will not exist. There is no such page in WordPress.</p>\n<p>If you create a term inside inside that taxonomy, "My Project", that term will be accessible at <code>mysite.com/projects/my-project</code> and that URL will use <code>taxonomy-projects.php</code> to list all posts that belong to that project. <code>mysite.com/projects</code> on its own does not exist.</p>\n"
}
] | 2022/09/27 | [
"https://wordpress.stackexchange.com/questions/409926",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2661/"
] | I created a custom taxonomies to work like category called projects to be used for the attachments.
I want to be able to create the archive page without having to use the CMS.
Currently the only thing I can figure out is to manually create the projects CMS page and attach the custom template there.
Here is my code for the projects taxonomy ( I edited out labels array to keep it simple):
```
register_taxonomy(
'projects',
'attachment',
array(
'labels' => array(
'name' => 'Projects',
),
'public' => true,
'hierarchical' => true,
'sort' => true,
'show_admin_column' => true,
'rewrite' => array('slug' => 'projects', 'with_front' => false)
)
);
```
To be clear all of the custom taxonomy seems to be working fine, I wanted to share that code mainly to show the rewrite line.
I thought at this point using [the template hierarchy](https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/) I would just need to create a file like
`taxonomy-{taxonomy}.php`
So I created my file taxonomy-projects.php but if I go to mysite.com/projects it is 404.
I have flushed permalinks multiple times and the way those are set are as custom structure:
`/%category%/%postname%/` | If you register a taxonomy named `projects`, and create `taxonomy-projects.php`, the URL `mysite.com/projects` will not exist. There is no such page in WordPress.
If you create a term inside inside that taxonomy, "My Project", that term will be accessible at `mysite.com/projects/my-project` and that URL will use `taxonomy-projects.php` to list all posts that belong to that project. `mysite.com/projects` on its own does not exist. |
409,945 | <p>I use a conditional statement to display a shortcode depending on which category archive is being displayed. The issue I have is that if I use get_queried_object_id, the archive page for the parent term shows the shortcode for the parent term and the first child term.</p>
<p>Here's the code which returns the parent <strong>and</strong> the first child term shortcodes.</p>
<pre class="lang-php prettyprint-override"><code>$emk_current_term_id = get_queried_object_id();
// Parent Term
if ( ($emk_current_term_id==141293) || in_category(array(141293)) )
{
echo do_shortcode('[emk_shortcode_01]');
}
// Child Term
if ( ($emk_current_term_id==305) || in_category(array(305)) )
{
echo do_shortcode('[emk_shortcode_02]');
}
</code></pre>
<p>The way I've got around this is to stipulate which result from the returned array to base the conditional statement on by using square brackets, like this.</p>
<pre class="lang-php prettyprint-override"><code>$emk_current_term_id = get_queried_object_id();
// Parent Term
if ( ($emk_current_term_id[0]==141293) || in_category(array(141293)) )
{
echo do_shortcode('[emk_shortcode_01]');
}
// Child Term
if ( ($emk_current_term_id[0]==305) || in_category(array(305)) )
{
echo do_shortcode('[emk_shortcode_02]');
}
</code></pre>
<p>So each conditional statement only takes into account the first returned value in the array.</p>
<p>Is this the best way to return the current term id <strong>only</strong>, i.e., is there any way to exclude child terms from the results array for <code>get_queried_object_id()</code>.</p>
<p>Thanks</p>
| [
{
"answer_id": 409947,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>The issue I have is that if I use get_queried_object_id, the archive\npage for the parent term shows the shortcode for the parent term and\nthe first child term.</p>\n</blockquote>\n<p>That's not what's happening. <code>get_queried_object_id()</code> will only return the ID of the current category. When you add <code>[0]</code> you're just breaking the condition check meaning that only <code>in_category()</code> is being checked. The problem is how you're using <code>in_category()</code>.</p>\n<p><code>in_category()</code> is supposed to be used inside the loop, and is checking the current post. When used on an archive page this is going to check the first post on the page. The reason your shortcode is being output twice is because the <code>get_queried_object_id()</code> check is <code>true</code> for the parent category, and the <code>in_category()</code> check for the child category is (apparently) true for the first post.</p>\n<p>If you want to check which archive is being displayed get rid of <code>in_category()</code> entirely, and make sure to check <code>is_category()</code> to ensure that the queried object is a category.</p>\n<pre><code>if ( is_category() && $emk_current_term_id === 141293 ) {\n echo do_shortcode( '[emk_shortcode_02]' );\n}\n\nif ( is_category() && $emk_current_term_id === 305 ) {\n echo do_shortcode( '[emk_shortcode_02]' );\n}\n</code></pre>\n<p>Just note that checking <code>is_category()</code> is redundant if this code is in category.php.</p>\n"
},
{
"answer_id": 409955,
"author": "MattK1984",
"author_id": 226190,
"author_profile": "https://wordpress.stackexchange.com/users/226190",
"pm_score": 0,
"selected": false,
"text": "<p>the code sits inside my sidebars.php file so it's loaded on archive.php and single.php to display banners relevant to the category archive being displayed, or the category to which a single post belongs.</p>\n<p>So if it's the Category A archive or it's a single post that belongs to Category A, show the Category A banners (which is what the shortcode does).</p>\n<p>It's probably easier to use the following.</p>\n<pre>\nif ( is_category(141293) || ( is_single() && in_category(array(141293)) ) )\n{\necho do_shortcode('[emk_shortcode_01]');\n}\n</pre>\n<p>I was just trying to use the get_queried_object_id() to make sure it was definitely using the category term id for the current archive, but I guess it depends on which template the statement is loaded inside which was causing my original issue. i.e. by having in_category as part of the conditional statement without the is_single preceding it, that's what was pulling in the multiple shortcodes.</p>\n<p>The above certainly seems to do what I need it to do.</p>\n"
}
] | 2022/09/28 | [
"https://wordpress.stackexchange.com/questions/409945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226190/"
] | I use a conditional statement to display a shortcode depending on which category archive is being displayed. The issue I have is that if I use get\_queried\_object\_id, the archive page for the parent term shows the shortcode for the parent term and the first child term.
Here's the code which returns the parent **and** the first child term shortcodes.
```php
$emk_current_term_id = get_queried_object_id();
// Parent Term
if ( ($emk_current_term_id==141293) || in_category(array(141293)) )
{
echo do_shortcode('[emk_shortcode_01]');
}
// Child Term
if ( ($emk_current_term_id==305) || in_category(array(305)) )
{
echo do_shortcode('[emk_shortcode_02]');
}
```
The way I've got around this is to stipulate which result from the returned array to base the conditional statement on by using square brackets, like this.
```php
$emk_current_term_id = get_queried_object_id();
// Parent Term
if ( ($emk_current_term_id[0]==141293) || in_category(array(141293)) )
{
echo do_shortcode('[emk_shortcode_01]');
}
// Child Term
if ( ($emk_current_term_id[0]==305) || in_category(array(305)) )
{
echo do_shortcode('[emk_shortcode_02]');
}
```
So each conditional statement only takes into account the first returned value in the array.
Is this the best way to return the current term id **only**, i.e., is there any way to exclude child terms from the results array for `get_queried_object_id()`.
Thanks | >
> The issue I have is that if I use get\_queried\_object\_id, the archive
> page for the parent term shows the shortcode for the parent term and
> the first child term.
>
>
>
That's not what's happening. `get_queried_object_id()` will only return the ID of the current category. When you add `[0]` you're just breaking the condition check meaning that only `in_category()` is being checked. The problem is how you're using `in_category()`.
`in_category()` is supposed to be used inside the loop, and is checking the current post. When used on an archive page this is going to check the first post on the page. The reason your shortcode is being output twice is because the `get_queried_object_id()` check is `true` for the parent category, and the `in_category()` check for the child category is (apparently) true for the first post.
If you want to check which archive is being displayed get rid of `in_category()` entirely, and make sure to check `is_category()` to ensure that the queried object is a category.
```
if ( is_category() && $emk_current_term_id === 141293 ) {
echo do_shortcode( '[emk_shortcode_02]' );
}
if ( is_category() && $emk_current_term_id === 305 ) {
echo do_shortcode( '[emk_shortcode_02]' );
}
```
Just note that checking `is_category()` is redundant if this code is in category.php. |
409,985 | <p>Regarding to the <strong>performances</strong>, and the performances only (and not from the point of view of the readability of the code), is it a best practice to check if the post has a thumbnail <strong>before</strong> to check if we are on the front-page, the home page, a single page, etc. or to do the opposite ?</p>
<p>Will my website load faster if I write :</p>
<pre><code><?php
if ( has_post_thumbnail() ) {
if ( is_front_page() ) {
// Do something…
} elseif ( is_archive() ) {
// Do something…
} elseif ( is_page() ) {
// Do something…
} elseif ( is_single() ) {
// Do someting…
// And so on
}
} else {
// Do something…
}
?>
</code></pre>
<p>OR if I write :</p>
<pre><code>
if ( is_front_page() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_archive() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_page() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_single() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
?>```
</code></pre>
| [
{
"answer_id": 409987,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Neither, they are just as fast as each other, both are using information that has already been fetched in advance. <em>This is micro-optimising.</em></strong></p>\n<p>Functions such as <code>is_front_page</code> or <code>is_singular</code> etc etc are just looking up variables already set in the main query object.</p>\n<p>Likewise functions such as <code>has_post_thumbnail</code> etc are looking up data that has already been fetched. WordPress will try to fetch things in advance, and most functions you call are already cached, or rely on pre-fetched data. For example when WordPress fetches a post, it also fetches its post meta and terms in bulk to save time and improve performance. This is why <code>get_post_meta</code> calls don't add database queries on most pages (because the data is already fetched and stored in <code>WP_Cache</code>).</p>\n<p>If you want to make your site faster, you should not be looking at things like this, and you should be measuring performance timings. If you took measurements you would see no measurable difference. Unless you have proof this is slowing down your site, performance isn't a consideration for this code.</p>\n<p>Normally the differences for code like this are so tiny when contributing to performance that they'll be drowned out by mundane things such as the temperature of the RAM and other minute things that aren't worth thinking about.</p>\n"
},
{
"answer_id": 409988,
"author": "Nabha Cosley",
"author_id": 335,
"author_profile": "https://wordpress.stackexchange.com/users/335",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Tom's answer is better and more true, but I'm leaving this here because the logic might be helpful to see.</strong></p>\n<p>In theory, all else being equal, you'd want to minimize the number of checks. The first approach is more performant because if the post doesn't have a post thumbnail, it only does one check.</p>\n<p>Then after that it minimized the number of checks because as soon as there's a match (<code>is_front_page()</code>) it stops checking the rest of them.</p>\n<p>The second approach does a minimum of four checks, and a maximum of five. The first approach does a minimum of one check, and a maximum of five.</p>\n<p>That said, not all checks are equal. All of the <code>is_</code> functions here just check a value stored in the global <code>wp_query</code> object, so I believe there's no call to the database, and effectively no difference for each of these checks. You'd have to run them thousands of times to make a difference.</p>\n<p><code>has_post_thumbnail()</code> uses <code>get_post()</code> and <code>get_post_meta()</code>, so there might be one or two database calls depending on what caching is going on. So this would be the function to limit use of, which means that your second approach could actually be more performant in cases where none of the <code>is_</code> functions are true.</p>\n<p>You can actually test this yourself using the <code>microtime()</code> function, which measures how long the server is taking to process a request. Run it before and after the code, then take the difference between the two. (Run it several times to get an average.)</p>\n"
}
] | 2022/09/29 | [
"https://wordpress.stackexchange.com/questions/409985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/175093/"
] | Regarding to the **performances**, and the performances only (and not from the point of view of the readability of the code), is it a best practice to check if the post has a thumbnail **before** to check if we are on the front-page, the home page, a single page, etc. or to do the opposite ?
Will my website load faster if I write :
```
<?php
if ( has_post_thumbnail() ) {
if ( is_front_page() ) {
// Do something…
} elseif ( is_archive() ) {
// Do something…
} elseif ( is_page() ) {
// Do something…
} elseif ( is_single() ) {
// Do someting…
// And so on
}
} else {
// Do something…
}
?>
```
OR if I write :
```
if ( is_front_page() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_archive() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_page() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
if ( is_single() ) {
if ( has_post_thumbnail() ) {
// Do something…
} else {
// Do something…
}
}
?>```
``` | **Neither, they are just as fast as each other, both are using information that has already been fetched in advance. *This is micro-optimising.***
Functions such as `is_front_page` or `is_singular` etc etc are just looking up variables already set in the main query object.
Likewise functions such as `has_post_thumbnail` etc are looking up data that has already been fetched. WordPress will try to fetch things in advance, and most functions you call are already cached, or rely on pre-fetched data. For example when WordPress fetches a post, it also fetches its post meta and terms in bulk to save time and improve performance. This is why `get_post_meta` calls don't add database queries on most pages (because the data is already fetched and stored in `WP_Cache`).
If you want to make your site faster, you should not be looking at things like this, and you should be measuring performance timings. If you took measurements you would see no measurable difference. Unless you have proof this is slowing down your site, performance isn't a consideration for this code.
Normally the differences for code like this are so tiny when contributing to performance that they'll be drowned out by mundane things such as the temperature of the RAM and other minute things that aren't worth thinking about. |
410,083 | <p>I have authors posting posts with a custom post type and have users with Editor roles publishing them. How can I get the editors who published them?</p>
| [
{
"answer_id": 410085,
"author": "Patryk Gielo",
"author_id": 226310,
"author_profile": "https://wordpress.stackexchange.com/users/226310",
"pm_score": 0,
"selected": false,
"text": "<p>wordpress don't have native functionality to handle changes around post/page from users. You need to write / or use plugin to get them and control your authors.</p>\n"
},
{
"answer_id": 410087,
"author": "Kristián Filo",
"author_id": 138610,
"author_profile": "https://wordpress.stackexchange.com/users/138610",
"pm_score": 3,
"selected": true,
"text": "<p>As far as I know, WordPress only stores original authors of the posts. If you want to also save the publisher's ID, you need to do a bit of custom coding, or use some 3rd party plugin.</p>\n<p>Essentially what you need to do is to store the user ID whenever the post status is being changed to <code>publish</code>. For that you can use the <code>publish_{your_post_type}</code> action (replace {your_post_type} with your custom post type slug). If your CPT slug is <code>project</code> for example, your action should look like this:</p>\n<pre><code>function save_project_publisher_meta( $post_id, $post ) {\n\n // Set current user ID as a post meta\n update_post_meta( $post_id, 'publisher_id', get_current_user_id() );\n}\nadd_action( 'publish_project', 'save_project_publisher_meta', 10, 3 );\n</code></pre>\n<p>Now the publisher ID should be stored as a post meta for each post, and you can access the user data whenever you need by retrieving the publisher ID using <code>get_post_meta</code>:</p>\n<pre><code>// Get WP_User object from ID\n$publisher_id = get_post_meta( $post_id, 'publisher_id' );\n$publisher = get_user_by( 'id', $publisher_id );\n\n// Get whatever user data you need\n$publisher_email = $publisher->user_email;\n</code></pre>\n<p>Note this will only affect newly published posts. Posts that were published in the past won't have publisher IDs stored, until you re-publish them.</p>\n"
}
] | 2022/10/03 | [
"https://wordpress.stackexchange.com/questions/410083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/217284/"
] | I have authors posting posts with a custom post type and have users with Editor roles publishing them. How can I get the editors who published them? | As far as I know, WordPress only stores original authors of the posts. If you want to also save the publisher's ID, you need to do a bit of custom coding, or use some 3rd party plugin.
Essentially what you need to do is to store the user ID whenever the post status is being changed to `publish`. For that you can use the `publish_{your_post_type}` action (replace {your\_post\_type} with your custom post type slug). If your CPT slug is `project` for example, your action should look like this:
```
function save_project_publisher_meta( $post_id, $post ) {
// Set current user ID as a post meta
update_post_meta( $post_id, 'publisher_id', get_current_user_id() );
}
add_action( 'publish_project', 'save_project_publisher_meta', 10, 3 );
```
Now the publisher ID should be stored as a post meta for each post, and you can access the user data whenever you need by retrieving the publisher ID using `get_post_meta`:
```
// Get WP_User object from ID
$publisher_id = get_post_meta( $post_id, 'publisher_id' );
$publisher = get_user_by( 'id', $publisher_id );
// Get whatever user data you need
$publisher_email = $publisher->user_email;
```
Note this will only affect newly published posts. Posts that were published in the past won't have publisher IDs stored, until you re-publish them. |
410,101 | <p>I have a question and couldn't find a solution for it.</p>
<p>We have a Wordpress page where the client wants multiple error pages.</p>
<p>1 error page is in the usual normal 404.php for the custom theme which we created. Now I want to add multiple error pages with different styling and html structure.</p>
<p>example:</p>
<pre><code>localhost/blog/{post-name} -> if post-name is not found load me the post-404-error.php
localhost/service/{service-name} -> if service-name was not found load the service-404-error.php
</code></pre>
<p>I couldn't think of a good solution how to get it done the right and save way.</p>
<p>I thought about changing the .htaccess like described here: <a href="https://stackoverflow.com/questions/24198493/404-redirection-to-multiple-error-page-htaccess">https://stackoverflow.com/questions/24198493/404-redirection-to-multiple-error-page-htaccess</a></p>
<p>But if permalinks are saved the .htaccess is rewritten and my changes will be gone there. Also I didn't know how to put the correct error documents inside (my rewriting htaccess knowledge is not the best.) I thought there could be a coded way with php/js something?</p>
<p>I also thought about some complicated check if this url is called and then check if <code>is_404()</code> but I guess its too complicated.</p>
<p>Thanks in advance for any help and tips :)</p>
| [
{
"answer_id": 410113,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>If your client wants only visual differences may be should consider using the get_template_part() function.</p>\n"
},
{
"answer_id": 410133,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for the help and the tips.\n@Dexter0015 Tip helped me in the end to get it done.</p>\n<p>This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.</p>\n<p>Thanks everyone again</p>\n<p><em><strong>edit</strong></em>:</p>\n<p>i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me</p>\n<pre><code>$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";\n\nget_header();\n\n\n\nif (strpos($postUrl,'/services/') !== false) {\n get_template_part("error-pages/services-error-page");\n} elseif(strpos($postUrl,'/blog/') !== false) {\n\n get_template_part("error-pages/blog-post-error");\n\n}else{\n get_template_part("error-pages/general-404-error");\n}\n\n\n\n\nget_footer();\n</code></pre>\n"
}
] | 2022/10/03 | [
"https://wordpress.stackexchange.com/questions/410101",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223996/"
] | I have a question and couldn't find a solution for it.
We have a Wordpress page where the client wants multiple error pages.
1 error page is in the usual normal 404.php for the custom theme which we created. Now I want to add multiple error pages with different styling and html structure.
example:
```
localhost/blog/{post-name} -> if post-name is not found load me the post-404-error.php
localhost/service/{service-name} -> if service-name was not found load the service-404-error.php
```
I couldn't think of a good solution how to get it done the right and save way.
I thought about changing the .htaccess like described here: <https://stackoverflow.com/questions/24198493/404-redirection-to-multiple-error-page-htaccess>
But if permalinks are saved the .htaccess is rewritten and my changes will be gone there. Also I didn't know how to put the correct error documents inside (my rewriting htaccess knowledge is not the best.) I thought there could be a coded way with php/js something?
I also thought about some complicated check if this url is called and then check if `is_404()` but I guess its too complicated.
Thanks in advance for any help and tips :) | Thank you guys for the help and the tips.
@Dexter0015 Tip helped me in the end to get it done.
This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.
Thanks everyone again
***edit***:
i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me
```
$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
get_header();
if (strpos($postUrl,'/services/') !== false) {
get_template_part("error-pages/services-error-page");
} elseif(strpos($postUrl,'/blog/') !== false) {
get_template_part("error-pages/blog-post-error");
}else{
get_template_part("error-pages/general-404-error");
}
get_footer();
``` |
410,150 | <p>I have been told here that having my data saved as metadata is creating slow queries.</p>
<p>I'm starting to convert all data used to sort my posts to taxonomy data. I've converted all the data stored in 'wpcf-release-year' to a taxonomy called 'release-year' and have created terms for every year.</p>
<p>Now I'd like to sort posts by <code>release-year</code>. I can't seem to find a way to get this to work with my new taxonomy. Here's my old code</p>
<pre><code>$my_query_args = array(
'posts_per_page' => -1,
'post_type' => 'release',
'meta_key' => 'wpcf-release-year', //I want this to be my taxonomy instead of the meta data
'orderby' => array(
'meta_value_num' => 'ASC',
'title' => 'ASC',
),
'tax_query' => $release_type_query,
);
</code></pre>
<p>How can I refer to the taxonomy term instead of the <code>meta-key</code> in this code? I've tried using the name <code>meta_key => 'release-year'</code> but that made all the posts dissapear. Do I need to add a new tax query? I'm not sure what to do. Thanks!</p>
| [
{
"answer_id": 410113,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>If your client wants only visual differences may be should consider using the get_template_part() function.</p>\n"
},
{
"answer_id": 410133,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for the help and the tips.\n@Dexter0015 Tip helped me in the end to get it done.</p>\n<p>This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.</p>\n<p>Thanks everyone again</p>\n<p><em><strong>edit</strong></em>:</p>\n<p>i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me</p>\n<pre><code>$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";\n\nget_header();\n\n\n\nif (strpos($postUrl,'/services/') !== false) {\n get_template_part("error-pages/services-error-page");\n} elseif(strpos($postUrl,'/blog/') !== false) {\n\n get_template_part("error-pages/blog-post-error");\n\n}else{\n get_template_part("error-pages/general-404-error");\n}\n\n\n\n\nget_footer();\n</code></pre>\n"
}
] | 2022/10/04 | [
"https://wordpress.stackexchange.com/questions/410150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/222023/"
] | I have been told here that having my data saved as metadata is creating slow queries.
I'm starting to convert all data used to sort my posts to taxonomy data. I've converted all the data stored in 'wpcf-release-year' to a taxonomy called 'release-year' and have created terms for every year.
Now I'd like to sort posts by `release-year`. I can't seem to find a way to get this to work with my new taxonomy. Here's my old code
```
$my_query_args = array(
'posts_per_page' => -1,
'post_type' => 'release',
'meta_key' => 'wpcf-release-year', //I want this to be my taxonomy instead of the meta data
'orderby' => array(
'meta_value_num' => 'ASC',
'title' => 'ASC',
),
'tax_query' => $release_type_query,
);
```
How can I refer to the taxonomy term instead of the `meta-key` in this code? I've tried using the name `meta_key => 'release-year'` but that made all the posts dissapear. Do I need to add a new tax query? I'm not sure what to do. Thanks! | Thank you guys for the help and the tips.
@Dexter0015 Tip helped me in the end to get it done.
This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.
Thanks everyone again
***edit***:
i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me
```
$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
get_header();
if (strpos($postUrl,'/services/') !== false) {
get_template_part("error-pages/services-error-page");
} elseif(strpos($postUrl,'/blog/') !== false) {
get_template_part("error-pages/blog-post-error");
}else{
get_template_part("error-pages/general-404-error");
}
get_footer();
``` |
410,161 | <p>I am trying to create a pdf using fpdf, which opens in a browser window. Ultimately, the data will be passed from a form submit to a non-existent WP page called pdf.</p>
<p>I am checking for this in template_redirect hook, so if it is pdf being requested, it will generate the pdf, and exit, otherwise will continue for normal WP processes.</p>
<p>This works in Firefox, but in Chrome, an alert : Failed to open PDF document. If I call a page with just this code in, it also works in Chrome.</p>
<pre><code>add_action("template_redirect", "checkRedirect");
function checkRedirect() {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$slug = strtolower(basename($url));
if ($slug == "pdf") {
require_once(getPath() . "fpdf.php");
$pdf = new \FPDF;
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
die(); // to stop WP processing
}
}
</code></pre>
<p>Using the template_redirect hook, I believe WP has not output any data, so not sure what the problem is, and it works in Firefox.</p>
| [
{
"answer_id": 410113,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>If your client wants only visual differences may be should consider using the get_template_part() function.</p>\n"
},
{
"answer_id": 410133,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for the help and the tips.\n@Dexter0015 Tip helped me in the end to get it done.</p>\n<p>This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.</p>\n<p>Thanks everyone again</p>\n<p><em><strong>edit</strong></em>:</p>\n<p>i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me</p>\n<pre><code>$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";\n\nget_header();\n\n\n\nif (strpos($postUrl,'/services/') !== false) {\n get_template_part("error-pages/services-error-page");\n} elseif(strpos($postUrl,'/blog/') !== false) {\n\n get_template_part("error-pages/blog-post-error");\n\n}else{\n get_template_part("error-pages/general-404-error");\n}\n\n\n\n\nget_footer();\n</code></pre>\n"
}
] | 2022/10/05 | [
"https://wordpress.stackexchange.com/questions/410161",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153752/"
] | I am trying to create a pdf using fpdf, which opens in a browser window. Ultimately, the data will be passed from a form submit to a non-existent WP page called pdf.
I am checking for this in template\_redirect hook, so if it is pdf being requested, it will generate the pdf, and exit, otherwise will continue for normal WP processes.
This works in Firefox, but in Chrome, an alert : Failed to open PDF document. If I call a page with just this code in, it also works in Chrome.
```
add_action("template_redirect", "checkRedirect");
function checkRedirect() {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$slug = strtolower(basename($url));
if ($slug == "pdf") {
require_once(getPath() . "fpdf.php");
$pdf = new \FPDF;
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
die(); // to stop WP processing
}
}
```
Using the template\_redirect hook, I believe WP has not output any data, so not sure what the problem is, and it works in Firefox. | Thank you guys for the help and the tips.
@Dexter0015 Tip helped me in the end to get it done.
This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.
Thanks everyone again
***edit***:
i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me
```
$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
get_header();
if (strpos($postUrl,'/services/') !== false) {
get_template_part("error-pages/services-error-page");
} elseif(strpos($postUrl,'/blog/') !== false) {
get_template_part("error-pages/blog-post-error");
}else{
get_template_part("error-pages/general-404-error");
}
get_footer();
``` |
410,164 | <p>I use plugin for submitting posts from frontend. It's a field builder.
Maybe it uses <code>wp_insert_post()</code> function, I really don't know.</p>
<p>Here I use my custom shortcode, please check here for the code:</p>
<pre><code>function my_custom_shortcode() {
global $wpdb;
$results = $wpdb->get_results( "SELECT city FROM slovak_cities" );
$select = '<select name="city_field">';
$select .= '<option value="-1">- select your city -</option>';
foreach ( $results as $result ) {
$select .= '<option value="' . str_replace( ' ', '_', strtolower( remove_accents( $result->city ) ) ) . '">' . $result->city . '</option>';
}
$select .= '</select>';
return $select;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' );
</code></pre>
<p>This shortcode creates a dropdown field in post form with many many options. All options inside are generated from database.
This everything is OK and works good.</p>
<p>But I need help with saving this field as custom field to post when post form is submitted. The element has a name attribute named "city_field". This value should be a META KEY of custom field and META VALUE should be one selected option from element.</p>
<p>Can someone help me please? I know that this is related to add_post_meta() or update_post_meta() functions, but how to use them? Are there any action or filter hooks available?</p>
| [
{
"answer_id": 410113,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>If your client wants only visual differences may be should consider using the get_template_part() function.</p>\n"
},
{
"answer_id": 410133,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for the help and the tips.\n@Dexter0015 Tip helped me in the end to get it done.</p>\n<p>This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.</p>\n<p>Thanks everyone again</p>\n<p><em><strong>edit</strong></em>:</p>\n<p>i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me</p>\n<pre><code>$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";\n\nget_header();\n\n\n\nif (strpos($postUrl,'/services/') !== false) {\n get_template_part("error-pages/services-error-page");\n} elseif(strpos($postUrl,'/blog/') !== false) {\n\n get_template_part("error-pages/blog-post-error");\n\n}else{\n get_template_part("error-pages/general-404-error");\n}\n\n\n\n\nget_footer();\n</code></pre>\n"
}
] | 2022/10/05 | [
"https://wordpress.stackexchange.com/questions/410164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/196508/"
] | I use plugin for submitting posts from frontend. It's a field builder.
Maybe it uses `wp_insert_post()` function, I really don't know.
Here I use my custom shortcode, please check here for the code:
```
function my_custom_shortcode() {
global $wpdb;
$results = $wpdb->get_results( "SELECT city FROM slovak_cities" );
$select = '<select name="city_field">';
$select .= '<option value="-1">- select your city -</option>';
foreach ( $results as $result ) {
$select .= '<option value="' . str_replace( ' ', '_', strtolower( remove_accents( $result->city ) ) ) . '">' . $result->city . '</option>';
}
$select .= '</select>';
return $select;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' );
```
This shortcode creates a dropdown field in post form with many many options. All options inside are generated from database.
This everything is OK and works good.
But I need help with saving this field as custom field to post when post form is submitted. The element has a name attribute named "city\_field". This value should be a META KEY of custom field and META VALUE should be one selected option from element.
Can someone help me please? I know that this is related to add\_post\_meta() or update\_post\_meta() functions, but how to use them? Are there any action or filter hooks available? | Thank you guys for the help and the tips.
@Dexter0015 Tip helped me in the end to get it done.
This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.
Thanks everyone again
***edit***:
i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me
```
$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
get_header();
if (strpos($postUrl,'/services/') !== false) {
get_template_part("error-pages/services-error-page");
} elseif(strpos($postUrl,'/blog/') !== false) {
get_template_part("error-pages/blog-post-error");
}else{
get_template_part("error-pages/general-404-error");
}
get_footer();
``` |
410,178 | <p><a href="https://i.stack.imgur.com/Lmi7B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lmi7B.png" alt="enter image description here" /></a></p>
<p>I got page information. but now I can't print specific data from this array.</p>
<pre><code>$page_details = get_pages( array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'hierarchical' => 0,
'meta_value' => 'template-parts/about.php'
));
echo '<pre>';
var_dump($page_details);// check the array value
echo '</pre>';
var_dump($page_details["post_title"]);// it's return null value. this way I am trying catch the specific value. but it is wrong
</code></pre>
<p>I was known but recently I forget it. so please help</p>
| [
{
"answer_id": 410113,
"author": "Bob",
"author_id": 225603,
"author_profile": "https://wordpress.stackexchange.com/users/225603",
"pm_score": 0,
"selected": false,
"text": "<p>If your client wants only visual differences may be should consider using the get_template_part() function.</p>\n"
},
{
"answer_id": 410133,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for the help and the tips.\n@Dexter0015 Tip helped me in the end to get it done.</p>\n<p>This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.</p>\n<p>Thanks everyone again</p>\n<p><em><strong>edit</strong></em>:</p>\n<p>i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me</p>\n<pre><code>$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";\n\nget_header();\n\n\n\nif (strpos($postUrl,'/services/') !== false) {\n get_template_part("error-pages/services-error-page");\n} elseif(strpos($postUrl,'/blog/') !== false) {\n\n get_template_part("error-pages/blog-post-error");\n\n}else{\n get_template_part("error-pages/general-404-error");\n}\n\n\n\n\nget_footer();\n</code></pre>\n"
}
] | 2022/10/05 | [
"https://wordpress.stackexchange.com/questions/410178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/220933/"
] | [](https://i.stack.imgur.com/Lmi7B.png)
I got page information. but now I can't print specific data from this array.
```
$page_details = get_pages( array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'hierarchical' => 0,
'meta_value' => 'template-parts/about.php'
));
echo '<pre>';
var_dump($page_details);// check the array value
echo '</pre>';
var_dump($page_details["post_title"]);// it's return null value. this way I am trying catch the specific value. but it is wrong
```
I was known but recently I forget it. so please help | Thank you guys for the help and the tips.
@Dexter0015 Tip helped me in the end to get it done.
This is how my 404.php looks like now im only checking if in the url the string is present and show the template for it.
Thanks everyone again
***edit***:
i changed the search values to /services/ and /blog/ so it was a bit better when the url has services inside or something it got messed up now it works perfectly for me
```
$postUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
get_header();
if (strpos($postUrl,'/services/') !== false) {
get_template_part("error-pages/services-error-page");
} elseif(strpos($postUrl,'/blog/') !== false) {
get_template_part("error-pages/blog-post-error");
}else{
get_template_part("error-pages/general-404-error");
}
get_footer();
``` |
410,298 | <p>I am using this code to center a custom ajax spinner for gravity forms submission.</p>
<ol>
<li><p>The spinner is centered based on the location of the gravity forms. I would like the spinner to be always centered horizontally and vertically, irrespective of the scroll position of the user.</p>
</li>
<li><p>In addition, the semi-transparent background overlay <code>background-color: rgba(255,255,255,0.5)</code> does not work. I have tried different variations, but I couldn't get a semi-transparent full page background overlay for the spinner.</p>
<pre><code> /* Absolute Center Spinner */
.gform_wrapper .gform_ajax_spinner {
position: fixed;
z-index: 999;
overflow: show;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 120px;
height: 120px;
}
/* Transparent Overlay */
.gform_wrapper .gform_ajax_spinner:before {
content: '';
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255,255,255,0.5) !important;
}
</code></pre>
</li>
</ol>
| [
{
"answer_id": 410282,
"author": "NBgr",
"author_id": 226498,
"author_profile": "https://wordpress.stackexchange.com/users/226498",
"pm_score": 1,
"selected": false,
"text": "<p>Got it - <strong>update_post_meta</strong> has to be used for <strong>_wp_attachment_image_alt</strong></p>\n"
},
{
"answer_id": 410667,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>You have a global <code>alt</code> (meta) value associated with an attachment(viewable when managed via "media" in the admin) that's stored in the post meta table, but on a post by post basis, the alt value you set when you use that piece of media into a post is stored more literally as a portion post content HTML.</p>\n<p>The issue i think is that WordPress doesn't respect the global(main) attachment alt value and will update the attachment meta when you insert it into a post and set the alt text, whilst the specific post alt text (post content html) for that attachment will be whatever you set it to at the time it was inserted.</p>\n<p>By calling <code>update_post_meta</code> on <code>_wp_attachment_image_alt</code> all you'll likely to achieve is a short term fix for setting what the current alt value is, it will likely change the next time you insert it and set a differing alt value.</p>\n"
}
] | 2022/10/10 | [
"https://wordpress.stackexchange.com/questions/410298",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this code to center a custom ajax spinner for gravity forms submission.
1. The spinner is centered based on the location of the gravity forms. I would like the spinner to be always centered horizontally and vertically, irrespective of the scroll position of the user.
2. In addition, the semi-transparent background overlay `background-color: rgba(255,255,255,0.5)` does not work. I have tried different variations, but I couldn't get a semi-transparent full page background overlay for the spinner.
```
/* Absolute Center Spinner */
.gform_wrapper .gform_ajax_spinner {
position: fixed;
z-index: 999;
overflow: show;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 120px;
height: 120px;
}
/* Transparent Overlay */
.gform_wrapper .gform_ajax_spinner:before {
content: '';
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255,255,255,0.5) !important;
}
``` | Got it - **update\_post\_meta** has to be used for **\_wp\_attachment\_image\_alt** |
410,449 | <p>I hope you have a good day.<br/>
I get a query from the database,<br/>
If the query is empty, the message "Register" will be displayed
Otherwise, the message "Register" will be displayed<br/>
See the code below and please guide me.<br/>
<em>Nothing is displayed when the query is empty</em></p>
<pre><code>function book_user(){
global $wpdb;
$rows = $wpdb->get_results("SELECT `quy` FROM wp_course_management WHERE user.current_user = '$booked_username' AND `quy` > 0");
foreach($rows as $row){
if (empty($row->quy)){
echo "register.";
}
else{
echo "You have alredy registered.";
};}?>
</code></pre>
| [
{
"answer_id": 410282,
"author": "NBgr",
"author_id": 226498,
"author_profile": "https://wordpress.stackexchange.com/users/226498",
"pm_score": 1,
"selected": false,
"text": "<p>Got it - <strong>update_post_meta</strong> has to be used for <strong>_wp_attachment_image_alt</strong></p>\n"
},
{
"answer_id": 410667,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>You have a global <code>alt</code> (meta) value associated with an attachment(viewable when managed via "media" in the admin) that's stored in the post meta table, but on a post by post basis, the alt value you set when you use that piece of media into a post is stored more literally as a portion post content HTML.</p>\n<p>The issue i think is that WordPress doesn't respect the global(main) attachment alt value and will update the attachment meta when you insert it into a post and set the alt text, whilst the specific post alt text (post content html) for that attachment will be whatever you set it to at the time it was inserted.</p>\n<p>By calling <code>update_post_meta</code> on <code>_wp_attachment_image_alt</code> all you'll likely to achieve is a short term fix for setting what the current alt value is, it will likely change the next time you insert it and set a differing alt value.</p>\n"
}
] | 2022/10/16 | [
"https://wordpress.stackexchange.com/questions/410449",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135260/"
] | I hope you have a good day.
I get a query from the database,
If the query is empty, the message "Register" will be displayed
Otherwise, the message "Register" will be displayed
See the code below and please guide me.
*Nothing is displayed when the query is empty*
```
function book_user(){
global $wpdb;
$rows = $wpdb->get_results("SELECT `quy` FROM wp_course_management WHERE user.current_user = '$booked_username' AND `quy` > 0");
foreach($rows as $row){
if (empty($row->quy)){
echo "register.";
}
else{
echo "You have alredy registered.";
};}?>
``` | Got it - **update\_post\_meta** has to be used for **\_wp\_attachment\_image\_alt** |
410,585 | <p>I need to add some shotrcodes for many taxonomies and I would like to display the value terms on a product page of woocommerce.
I tried with this but doesn't work, in this case the taxonomy name is "pagamento"</p>
<pre><code>$terms = get_terms( 'pagamento' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ($terms as $term) {
// $taxonomy name pagamento
$pagamento = get_field('pagamento', $term->taxonomy.'_'.$term->term_id);
}
echo '</ul>';
}
add_shortcode( 'pagamento', 'na_display_pagamento' );
</code></pre>
| [
{
"answer_id": 410282,
"author": "NBgr",
"author_id": 226498,
"author_profile": "https://wordpress.stackexchange.com/users/226498",
"pm_score": 1,
"selected": false,
"text": "<p>Got it - <strong>update_post_meta</strong> has to be used for <strong>_wp_attachment_image_alt</strong></p>\n"
},
{
"answer_id": 410667,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>You have a global <code>alt</code> (meta) value associated with an attachment(viewable when managed via "media" in the admin) that's stored in the post meta table, but on a post by post basis, the alt value you set when you use that piece of media into a post is stored more literally as a portion post content HTML.</p>\n<p>The issue i think is that WordPress doesn't respect the global(main) attachment alt value and will update the attachment meta when you insert it into a post and set the alt text, whilst the specific post alt text (post content html) for that attachment will be whatever you set it to at the time it was inserted.</p>\n<p>By calling <code>update_post_meta</code> on <code>_wp_attachment_image_alt</code> all you'll likely to achieve is a short term fix for setting what the current alt value is, it will likely change the next time you insert it and set a differing alt value.</p>\n"
}
] | 2022/10/20 | [
"https://wordpress.stackexchange.com/questions/410585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226777/"
] | I need to add some shotrcodes for many taxonomies and I would like to display the value terms on a product page of woocommerce.
I tried with this but doesn't work, in this case the taxonomy name is "pagamento"
```
$terms = get_terms( 'pagamento' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ($terms as $term) {
// $taxonomy name pagamento
$pagamento = get_field('pagamento', $term->taxonomy.'_'.$term->term_id);
}
echo '</ul>';
}
add_shortcode( 'pagamento', 'na_display_pagamento' );
``` | Got it - **update\_post\_meta** has to be used for **\_wp\_attachment\_image\_alt** |
410,614 | <p>I've been able to successfully empty the meta_value for a specific meta_key. The problem is that a new meta_key will be created for all users in the database. I do not want all users to have the meta_key created in the database unless it already exist.</p>
<p>I think perhaps if I set 'guest_list_venue_names' as a variable and check if it exist I can use an IF statement? I'm new to PHP so any insight would be helpful.</p>
<pre><code>$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));
$users = $wp_user_query->get_results();
if (!empty($users)) {
foreach ($users as $user)
{
update_user_meta( $user->id, 'guest_list_venue', '');
update_user_meta( $user->id, 'guest_list_venue_names', '');
}
}
</code></pre>
| [
{
"answer_id": 410282,
"author": "NBgr",
"author_id": 226498,
"author_profile": "https://wordpress.stackexchange.com/users/226498",
"pm_score": 1,
"selected": false,
"text": "<p>Got it - <strong>update_post_meta</strong> has to be used for <strong>_wp_attachment_image_alt</strong></p>\n"
},
{
"answer_id": 410667,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>You have a global <code>alt</code> (meta) value associated with an attachment(viewable when managed via "media" in the admin) that's stored in the post meta table, but on a post by post basis, the alt value you set when you use that piece of media into a post is stored more literally as a portion post content HTML.</p>\n<p>The issue i think is that WordPress doesn't respect the global(main) attachment alt value and will update the attachment meta when you insert it into a post and set the alt text, whilst the specific post alt text (post content html) for that attachment will be whatever you set it to at the time it was inserted.</p>\n<p>By calling <code>update_post_meta</code> on <code>_wp_attachment_image_alt</code> all you'll likely to achieve is a short term fix for setting what the current alt value is, it will likely change the next time you insert it and set a differing alt value.</p>\n"
}
] | 2022/10/21 | [
"https://wordpress.stackexchange.com/questions/410614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226812/"
] | I've been able to successfully empty the meta\_value for a specific meta\_key. The problem is that a new meta\_key will be created for all users in the database. I do not want all users to have the meta\_key created in the database unless it already exist.
I think perhaps if I set 'guest\_list\_venue\_names' as a variable and check if it exist I can use an IF statement? I'm new to PHP so any insight would be helpful.
```
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));
$users = $wp_user_query->get_results();
if (!empty($users)) {
foreach ($users as $user)
{
update_user_meta( $user->id, 'guest_list_venue', '');
update_user_meta( $user->id, 'guest_list_venue_names', '');
}
}
``` | Got it - **update\_post\_meta** has to be used for **\_wp\_attachment\_image\_alt** |
410,623 | <p>I have created a new custom post type in wordpress using <strong><code>register_post_type()</code></strong> function But when I click on <strong>add new</strong> in right side the editor not showing <strong>template</strong> choose option as you can see in <strong>Screenshot_01.png</strong>. In <strong>Screenshot_2</strong> you can see the default add post option has the <strong>template</strong> choose option. How can I get that option without using plugin.
Here is my exiting code for creating custom post type.</p>
<pre><code>function short_story_type(){
$labels = array(
'name' => _x( 'storys', 'Post Type General Name', 'textdomain' ),
'singular_name' => _x( 'story', 'Post Type Singular Name', 'textdomain' ),
'menu_name' => _x( 'storys', 'Admin Menu text', 'textdomain' ),
'name_admin_bar' => _x( 'story', 'Add New on Toolbar', 'textdomain' ),
'archives' => __( 'story Archives', 'textdomain' ),
'attributes' => __( 'story Attributes', 'textdomain' ),
'parent_item_colon' => __( 'Parent story:', 'textdomain' ),
'all_items' => __( 'All storys', 'textdomain' ),
'add_new_item' => __( 'Add New story', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'new_item' => __( 'New story', 'textdomain' ),
'edit_item' => __( 'Edit story', 'textdomain' ),
'update_item' => __( 'Update story', 'textdomain' ),
'view_item' => __( 'View story', 'textdomain' ),
'view_items' => __( 'View storys', 'textdomain' ),
'search_items' => __( 'Search story', 'textdomain' ),
'not_found' => __( 'Not found', 'textdomain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
'featured_image' => __( 'Featured Image', 'textdomain' ),
'set_featured_image' => __( 'Set featured image', 'textdomain' ),
'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
'use_featured_image' => __( 'Use as featured image', 'textdomain' ),
'insert_into_item' => __( 'Insert into story', 'textdomain' ),
'uploaded_to_this_item' => __( 'Uploaded to this story', 'textdomain' ),
'items_list' => __( 'storys list', 'textdomain' ),
'items_list_navigation' => __( 'storys list navigation', 'textdomain' ),
'filter_items_list' => __( 'Filter storys list', 'textdomain' ),
);
$args = array(
'label' => __( 'story', 'textdomain' ),
'description' => __( '', 'textdomain' ),
'labels' => $labels,
'menu_icon' => 'dashicons-album',
'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'author', 'comments', 'trackbacks', 'page-attributes', 'post-formats', 'custom-fields'),
'taxonomies' => array(),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'hierarchical' => false,
'exclude_from_search' => true,
'show_in_rest' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'story', $args );
}
add_action('init', 'short_story_type');
</code></pre>
| [
{
"answer_id": 410625,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure where these screenshots you're talking about have gone, no matter, i think i know the problem.</p>\n<p>You simply need to add support for the post type in the templates you want to be able to attach by adjusting the <code>Template Post Type:</code> line for the appropriate template files in your theme.</p>\n<p><strong>Example</strong></p>\n<pre><code>Template Post Type: post, books, movies\n</code></pre>\n<p>The dropdown should then appear in the editor like it does for posts.</p>\n"
},
{
"answer_id": 410632,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>Try to change</p>\n<pre><code>'`capability_type' => 'post',`\n</code></pre>\n<p>to</p>\n<pre><code>'capability_type' => 'page',\n</code></pre>\n"
}
] | 2022/10/21 | [
"https://wordpress.stackexchange.com/questions/410623",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/225779/"
] | I have created a new custom post type in wordpress using **`register_post_type()`** function But when I click on **add new** in right side the editor not showing **template** choose option as you can see in **Screenshot\_01.png**. In **Screenshot\_2** you can see the default add post option has the **template** choose option. How can I get that option without using plugin.
Here is my exiting code for creating custom post type.
```
function short_story_type(){
$labels = array(
'name' => _x( 'storys', 'Post Type General Name', 'textdomain' ),
'singular_name' => _x( 'story', 'Post Type Singular Name', 'textdomain' ),
'menu_name' => _x( 'storys', 'Admin Menu text', 'textdomain' ),
'name_admin_bar' => _x( 'story', 'Add New on Toolbar', 'textdomain' ),
'archives' => __( 'story Archives', 'textdomain' ),
'attributes' => __( 'story Attributes', 'textdomain' ),
'parent_item_colon' => __( 'Parent story:', 'textdomain' ),
'all_items' => __( 'All storys', 'textdomain' ),
'add_new_item' => __( 'Add New story', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'new_item' => __( 'New story', 'textdomain' ),
'edit_item' => __( 'Edit story', 'textdomain' ),
'update_item' => __( 'Update story', 'textdomain' ),
'view_item' => __( 'View story', 'textdomain' ),
'view_items' => __( 'View storys', 'textdomain' ),
'search_items' => __( 'Search story', 'textdomain' ),
'not_found' => __( 'Not found', 'textdomain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
'featured_image' => __( 'Featured Image', 'textdomain' ),
'set_featured_image' => __( 'Set featured image', 'textdomain' ),
'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
'use_featured_image' => __( 'Use as featured image', 'textdomain' ),
'insert_into_item' => __( 'Insert into story', 'textdomain' ),
'uploaded_to_this_item' => __( 'Uploaded to this story', 'textdomain' ),
'items_list' => __( 'storys list', 'textdomain' ),
'items_list_navigation' => __( 'storys list navigation', 'textdomain' ),
'filter_items_list' => __( 'Filter storys list', 'textdomain' ),
);
$args = array(
'label' => __( 'story', 'textdomain' ),
'description' => __( '', 'textdomain' ),
'labels' => $labels,
'menu_icon' => 'dashicons-album',
'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'author', 'comments', 'trackbacks', 'page-attributes', 'post-formats', 'custom-fields'),
'taxonomies' => array(),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'hierarchical' => false,
'exclude_from_search' => true,
'show_in_rest' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'story', $args );
}
add_action('init', 'short_story_type');
``` | Not sure where these screenshots you're talking about have gone, no matter, i think i know the problem.
You simply need to add support for the post type in the templates you want to be able to attach by adjusting the `Template Post Type:` line for the appropriate template files in your theme.
**Example**
```
Template Post Type: post, books, movies
```
The dropdown should then appear in the editor like it does for posts. |
410,658 | <p>Hello im really stuck and messing around now so i thought i give a try and ask the community.</p>
<p>Im working on a Blog Post page where im showing some posts. The user have the selection to search for posts via a search form or clicking on some categories and filtering the category. This works fine for now. But i couldn't find a way to adjust the pagination to this new filtered posts. Also the posts are not sorted after the filtering.</p>
<p>I created a new Array where i loop through without any success. The posts are still on the same position.</p>
<p>ex. User is filtering for Outsourcing so all posts with category outsourcing are showing but they are splited this means some of the posts are on page 1 some of them are on page 2 and so on the array is not sorted new after the filtering and they stick to they page positions:</p>
<p>here is my code which i loop through then later and showing the html with title, image etc... and some screenshots:</p>
<pre><code>$searchBlog = '';
$searchCategory = '';
if(!empty($_GET['searchBlog']))
{
$searchBlog = $_GET['searchBlog'];
}
if(!empty($_GET['search_category']))
{
$searchCategory = $_GET['search_category'];
}
global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$categories = get_categories();
$args = array(
'posts_per_page' => 5,
'paged' => $paged,
'post_type' => 'post',
'order' => 'DESC',
);
$big = 999999999; // need an unlikely integer
$query = new WP_Query( $args );
$postsList = [];
foreach ($query->posts AS $post)
{
$custom = get_post_custom($post->ID);
$post_category = wp_get_post_categories($post->ID);
foreach ($post_category AS $cat)
{
$postsList[] = [
'post' => $post,
'category' => $cat,
];
}
}
$filteredPostList = [];
foreach ($postsList AS $posts) {
if (!empty($searchCategory) && $posts['category'] == $searchCategory) {
$filteredPostList[] = $posts;
var_dump('category');
} elseif (!empty($searchBlog) && str_contains(strtolower($posts['post']->post_title), strtolower($searchBlog))) {
$filteredPostList[] = $posts;
var_dump('search');
} elseif (empty($searchCategory) && $posts['category'] != $searchCategory && empty($searchBlog)) {
$filteredPostList[] = $posts;
var_dump('all');
}
}
$pagination = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '/page/%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $query->max_num_pages,
'prev_text' => __('<i class="ico_arrow_left_black"></i>'),
'next_text' => __('<i class="ico_arrow_right_black"></i>'),
'type' => 'list',
) );
</code></pre>
<p><a href="https://i.stack.imgur.com/svemP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/svemP.png" alt="first page with only one post but posts per page is 5 and there are definitely more posts" /></a></p>
<p><a href="https://i.stack.imgur.com/fhEsE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhEsE.jpg" alt="here is the second page with more posts of the same category" /></a></p>
| [
{
"answer_id": 410670,
"author": "Matheus Alves",
"author_id": 226852,
"author_profile": "https://wordpress.stackexchange.com/users/226852",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how many categories you will have, I would create result pages for each category.\nI would do the filtering with the GET method as you already did. And it would use a switch case to select each result page.</p>\n"
},
{
"answer_id": 410823,
"author": "Jaba",
"author_id": 223996,
"author_profile": "https://wordpress.stackexchange.com/users/223996",
"pm_score": 3,
"selected": true,
"text": "<p>I found my own Answer:</p>\n<p>due to my second array which i created to add some categories the filter only searched for each page separately. with 'cat' i could search for the category and with 's' i could search for a specific value like the title. so i put everything i needed in $args to make it work :</p>\n<pre><code>$searchBlog = '';\n$searchCategory = '';\nif(!empty($_GET['searchBlog']))\n{\n $searchBlog = $_GET['searchBlog'];\n\n}\nif(!empty($_GET['search_category']))\n{\n $searchCategory = $_GET['search_category'];\n}\n\nglobal $wp_query;\n$categories = get_categories();\n\n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n\n$args = array(\n 'posts_per_page' => 12,\n 'paged' => $paged,\n 'post_type' => 'post',\n 'order' => 'DESC',\n 'cat' => $searchCategory,\n 's' => $searchBlog,\n\n);\n\n\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] | 2022/10/22 | [
"https://wordpress.stackexchange.com/questions/410658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/223996/"
] | Hello im really stuck and messing around now so i thought i give a try and ask the community.
Im working on a Blog Post page where im showing some posts. The user have the selection to search for posts via a search form or clicking on some categories and filtering the category. This works fine for now. But i couldn't find a way to adjust the pagination to this new filtered posts. Also the posts are not sorted after the filtering.
I created a new Array where i loop through without any success. The posts are still on the same position.
ex. User is filtering for Outsourcing so all posts with category outsourcing are showing but they are splited this means some of the posts are on page 1 some of them are on page 2 and so on the array is not sorted new after the filtering and they stick to they page positions:
here is my code which i loop through then later and showing the html with title, image etc... and some screenshots:
```
$searchBlog = '';
$searchCategory = '';
if(!empty($_GET['searchBlog']))
{
$searchBlog = $_GET['searchBlog'];
}
if(!empty($_GET['search_category']))
{
$searchCategory = $_GET['search_category'];
}
global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$categories = get_categories();
$args = array(
'posts_per_page' => 5,
'paged' => $paged,
'post_type' => 'post',
'order' => 'DESC',
);
$big = 999999999; // need an unlikely integer
$query = new WP_Query( $args );
$postsList = [];
foreach ($query->posts AS $post)
{
$custom = get_post_custom($post->ID);
$post_category = wp_get_post_categories($post->ID);
foreach ($post_category AS $cat)
{
$postsList[] = [
'post' => $post,
'category' => $cat,
];
}
}
$filteredPostList = [];
foreach ($postsList AS $posts) {
if (!empty($searchCategory) && $posts['category'] == $searchCategory) {
$filteredPostList[] = $posts;
var_dump('category');
} elseif (!empty($searchBlog) && str_contains(strtolower($posts['post']->post_title), strtolower($searchBlog))) {
$filteredPostList[] = $posts;
var_dump('search');
} elseif (empty($searchCategory) && $posts['category'] != $searchCategory && empty($searchBlog)) {
$filteredPostList[] = $posts;
var_dump('all');
}
}
$pagination = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '/page/%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $query->max_num_pages,
'prev_text' => __('<i class="ico_arrow_left_black"></i>'),
'next_text' => __('<i class="ico_arrow_right_black"></i>'),
'type' => 'list',
) );
```
[](https://i.stack.imgur.com/svemP.png)
[](https://i.stack.imgur.com/fhEsE.jpg) | I found my own Answer:
due to my second array which i created to add some categories the filter only searched for each page separately. with 'cat' i could search for the category and with 's' i could search for a specific value like the title. so i put everything i needed in $args to make it work :
```
$searchBlog = '';
$searchCategory = '';
if(!empty($_GET['searchBlog']))
{
$searchBlog = $_GET['searchBlog'];
}
if(!empty($_GET['search_category']))
{
$searchCategory = $_GET['search_category'];
}
global $wp_query;
$categories = get_categories();
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 12,
'paged' => $paged,
'post_type' => 'post',
'order' => 'DESC',
'cat' => $searchCategory,
's' => $searchBlog,
);
$query = new WP_Query( $args );
``` |
410,659 | <p>How to upgrade WordPress automatically?</p>
<p>What is the standard way to upgrade an entire WordPress installation --- core <strong>or</strong> core and plugins, automatically?</p>
| [
{
"answer_id": 410660,
"author": "WebDeveloper.IM",
"author_id": 114235,
"author_profile": "https://wordpress.stackexchange.com/users/114235",
"pm_score": 0,
"selected": false,
"text": "<p>One of the advantages of WordPress is that it can be easily upgraded. New versions of WordPress are released regularly, and you can upgrade your WordPress site with just a few clicks.</p>\n<p>To upgrade WordPress core automatically, long your wp-config.php file add this line:</p>\n<pre><code>define( 'WP_AUTO_UPDATE_CORE', true );\n</code></pre>\n<p>To enable automatic updates for WordPress plugins, simply go to the Plugins page and beside each plugin click on the "Enable auto-updates" text. Once you've done that, WordPress will automatically update your plugins whenever a new version is released.</p>\n<p>Also, you can use a plugin called: <a href=\"https://wordpress.org/plugins/stops-core-theme-and-plugin-updates/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/stops-core-theme-and-plugin-updates/</a> to manage all updated related settings.</p>\n"
},
{
"answer_id": 410675,
"author": "Buttered_Toast",
"author_id": 192133,
"author_profile": "https://wordpress.stackexchange.com/users/192133",
"pm_score": 2,
"selected": true,
"text": "<p>By default WordPress automatically updates itself, plugins, and themes.<br />\nIf your WordPress install doesn't do that then you probably have something that disables this.</p>\n<p>You can check your theme for something like this</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('auto_update_plugin', '__return_false');\nadd_filter('auto_update_theme', '__return_false');\n</code></pre>\n<p>And/Or in your wp-config.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('AUTOMATIC_UPDATER_DISABLED', true);\ndefine('WP_AUTO_UPDATE_CORE', false);\n</code></pre>\n<p>If your WordPress is not on a local machine and is on a hosting env, and you can't find anything like the code above, you can try contacting your hosting about this, they might provide additional help.</p>\n"
}
] | 2022/10/22 | [
"https://wordpress.stackexchange.com/questions/410659",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226837/"
] | How to upgrade WordPress automatically?
What is the standard way to upgrade an entire WordPress installation --- core **or** core and plugins, automatically? | By default WordPress automatically updates itself, plugins, and themes.
If your WordPress install doesn't do that then you probably have something that disables this.
You can check your theme for something like this
```php
add_filter('auto_update_plugin', '__return_false');
add_filter('auto_update_theme', '__return_false');
```
And/Or in your wp-config.php
```php
define('AUTOMATIC_UPDATER_DISABLED', true);
define('WP_AUTO_UPDATE_CORE', false);
```
If your WordPress is not on a local machine and is on a hosting env, and you can't find anything like the code above, you can try contacting your hosting about this, they might provide additional help. |
410,733 | <p>I want to create a custom plugin to add a login with url functionality to my wordpress sites.</p>
<p>For example, I want to create a link as follows:</p>
<blockquote>
<p><a href="http://www.mysite.com/wp-admin?username=xxxx&pass=xxxxx" rel="nofollow noreferrer">www.mysite.com/wp-admin?username=xxxx&pass=xxxxx</a></p>
</blockquote>
<p>For implementing this i found a code which is to be added to funtions.php file of any theme or plugin. The code is:</p>
<pre><code><?php
if( isset($_GET['username']) and $_GET['pass'] ) {
$user = get_user_by('login', $_GET['username']);
if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
wp_redirect( admin_url() );
exit;
}
wp_redirect( home_url() );
exit;
}
?>
</code></pre>
<p>But instead of hampering the files of any theme or plugin i want to create a custom plugin to add this functionality.</p>
<p>Also by doing this i will be able to just simply install that plugin to all of my sites to add that functionality without hampering the code of any other plugin or theme.</p>
<p>I tried to create a plugin named TechyParas to add this. But sadly it hasn't worked. The code i added to my plugin was:</p>
<pre><code><?php
/*
* Plugin Name: TechyParas
* Description: This plugin will display a fixed link on the footer of your website.
* Version: 1.0.0
* Author: TechyParas
* Author URI: https://techyparas.com
* License: GPL2
*/
function techyparas_log(){
if( isset($_GET['username']) and $_GET['pass'] ) {
$user = get_user_by('login', $_GET['username']);
if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
wp_redirect( admin_url() );
exit;
}
wp_redirect( home_url() );
exit;
}}
add_filter('loginout', 'techyparas_log');
?>
</code></pre>
<p>Please help me with this.</p>
| [
{
"answer_id": 410660,
"author": "WebDeveloper.IM",
"author_id": 114235,
"author_profile": "https://wordpress.stackexchange.com/users/114235",
"pm_score": 0,
"selected": false,
"text": "<p>One of the advantages of WordPress is that it can be easily upgraded. New versions of WordPress are released regularly, and you can upgrade your WordPress site with just a few clicks.</p>\n<p>To upgrade WordPress core automatically, long your wp-config.php file add this line:</p>\n<pre><code>define( 'WP_AUTO_UPDATE_CORE', true );\n</code></pre>\n<p>To enable automatic updates for WordPress plugins, simply go to the Plugins page and beside each plugin click on the "Enable auto-updates" text. Once you've done that, WordPress will automatically update your plugins whenever a new version is released.</p>\n<p>Also, you can use a plugin called: <a href=\"https://wordpress.org/plugins/stops-core-theme-and-plugin-updates/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/stops-core-theme-and-plugin-updates/</a> to manage all updated related settings.</p>\n"
},
{
"answer_id": 410675,
"author": "Buttered_Toast",
"author_id": 192133,
"author_profile": "https://wordpress.stackexchange.com/users/192133",
"pm_score": 2,
"selected": true,
"text": "<p>By default WordPress automatically updates itself, plugins, and themes.<br />\nIf your WordPress install doesn't do that then you probably have something that disables this.</p>\n<p>You can check your theme for something like this</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('auto_update_plugin', '__return_false');\nadd_filter('auto_update_theme', '__return_false');\n</code></pre>\n<p>And/Or in your wp-config.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('AUTOMATIC_UPDATER_DISABLED', true);\ndefine('WP_AUTO_UPDATE_CORE', false);\n</code></pre>\n<p>If your WordPress is not on a local machine and is on a hosting env, and you can't find anything like the code above, you can try contacting your hosting about this, they might provide additional help.</p>\n"
}
] | 2022/10/25 | [
"https://wordpress.stackexchange.com/questions/410733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/226938/"
] | I want to create a custom plugin to add a login with url functionality to my wordpress sites.
For example, I want to create a link as follows:
>
> [www.mysite.com/wp-admin?username=xxxx&pass=xxxxx](http://www.mysite.com/wp-admin?username=xxxx&pass=xxxxx)
>
>
>
For implementing this i found a code which is to be added to funtions.php file of any theme or plugin. The code is:
```
<?php
if( isset($_GET['username']) and $_GET['pass'] ) {
$user = get_user_by('login', $_GET['username']);
if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
wp_redirect( admin_url() );
exit;
}
wp_redirect( home_url() );
exit;
}
?>
```
But instead of hampering the files of any theme or plugin i want to create a custom plugin to add this functionality.
Also by doing this i will be able to just simply install that plugin to all of my sites to add that functionality without hampering the code of any other plugin or theme.
I tried to create a plugin named TechyParas to add this. But sadly it hasn't worked. The code i added to my plugin was:
```
<?php
/*
* Plugin Name: TechyParas
* Description: This plugin will display a fixed link on the footer of your website.
* Version: 1.0.0
* Author: TechyParas
* Author URI: https://techyparas.com
* License: GPL2
*/
function techyparas_log(){
if( isset($_GET['username']) and $_GET['pass'] ) {
$user = get_user_by('login', $_GET['username']);
if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
wp_redirect( admin_url() );
exit;
}
wp_redirect( home_url() );
exit;
}}
add_filter('loginout', 'techyparas_log');
?>
```
Please help me with this. | By default WordPress automatically updates itself, plugins, and themes.
If your WordPress install doesn't do that then you probably have something that disables this.
You can check your theme for something like this
```php
add_filter('auto_update_plugin', '__return_false');
add_filter('auto_update_theme', '__return_false');
```
And/Or in your wp-config.php
```php
define('AUTOMATIC_UPDATER_DISABLED', true);
define('WP_AUTO_UPDATE_CORE', false);
```
If your WordPress is not on a local machine and is on a hosting env, and you can't find anything like the code above, you can try contacting your hosting about this, they might provide additional help. |
410,789 | <p>I'm using a third-party theme with a custom child theme on a website and want to remove the Google Fonts from the parent theme within the child theme's functions.php. This is not working - nothing happens.</p>
<pre><code>/**
* Remove parent theme Google fonts
*/
function remove_parent_theme_google_fonts() {
wp_dequeue_style( 'themename_googlefonts-css' );
wp_deregister_style( 'themename_googlefonts-css' );
}
add_action( 'after_setup_theme', 'remove_parent_theme_google_fonts', 1);
</code></pre>
<p>where <code>themename_googlefonts-css</code> is the parent theme's id from the stylesheet link.</p>
<p>Thanks for your help.</p>
<p>EDIT: Removed direct references to specific third-party theme to make this more relevant for other users.</p>
| [
{
"answer_id": 410791,
"author": "Gui",
"author_id": 182960,
"author_profile": "https://wordpress.stackexchange.com/users/182960",
"pm_score": 1,
"selected": false,
"text": "<p>As Buttered_Toast mentioned, I think the hook you want to use is <code>wp_enqueue_scripts</code> rather than <code>after_setup_theme</code>. Changing the priority is also a good idea to make sure your function trigger after the initial call from the parent theme.</p>\n<p>So your function would be:</p>\n<pre><code>/**\n * Remove Accelerate Google fonts\n */\nfunction remove_accelerate_google_fonts() {\n wp_dequeue_style( 'accelerate_googlefonts-css' );\n wp_deregister_style( 'accelerate_googlefonts-css' );\n}\nadd_action( 'wp_enqueue_scripts', 'remove_accelerate_google_fonts', 50);\n</code></pre>\n"
},
{
"answer_id": 410821,
"author": "winnewoerp",
"author_id": 40934,
"author_profile": "https://wordpress.stackexchange.com/users/40934",
"pm_score": 0,
"selected": false,
"text": "<p>It works with <code>wp_enqueue_scripts</code> and the correct handle without the <code>-css</code> suffix. Here is my fully working solution:</p>\n<pre><code>/**\n * Remove parent theme Google fonts\n */\nfunction remove_parent_theme_google_fonts() {\n wp_dequeue_style( 'themename_googlefonts' );\n wp_deregister_style( 'themename_googlefonts' );\n}\nadd_action( 'wp_enqueue_scripts', 'remove_parent_theme_google_fonts', 50);\n</code></pre>\n"
}
] | 2022/10/27 | [
"https://wordpress.stackexchange.com/questions/410789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40934/"
] | I'm using a third-party theme with a custom child theme on a website and want to remove the Google Fonts from the parent theme within the child theme's functions.php. This is not working - nothing happens.
```
/**
* Remove parent theme Google fonts
*/
function remove_parent_theme_google_fonts() {
wp_dequeue_style( 'themename_googlefonts-css' );
wp_deregister_style( 'themename_googlefonts-css' );
}
add_action( 'after_setup_theme', 'remove_parent_theme_google_fonts', 1);
```
where `themename_googlefonts-css` is the parent theme's id from the stylesheet link.
Thanks for your help.
EDIT: Removed direct references to specific third-party theme to make this more relevant for other users. | As Buttered\_Toast mentioned, I think the hook you want to use is `wp_enqueue_scripts` rather than `after_setup_theme`. Changing the priority is also a good idea to make sure your function trigger after the initial call from the parent theme.
So your function would be:
```
/**
* Remove Accelerate Google fonts
*/
function remove_accelerate_google_fonts() {
wp_dequeue_style( 'accelerate_googlefonts-css' );
wp_deregister_style( 'accelerate_googlefonts-css' );
}
add_action( 'wp_enqueue_scripts', 'remove_accelerate_google_fonts', 50);
``` |
410,855 | <p>The following applies to all attchment images on my site:</p>
<p>There is a PNG image attachment, its ID is 519271.</p>
<p><code>wp_get_attachment_image(519271, 'thumbnail', false, array( 'id' => 'esjb-preview-image' ))</code> returns "".</p>
<p><code>wp_get_attachment_image_src(519271)</code> returns <code>false</code>.</p>
<p><code>wp_attachment_is_image(519271)</code> returns <code>true</code></p>
<p>The file is there in the uploads folder. Folder permissions are 755. File permissions are 644.</p>
<p>The attachment is in the wp_posts table and the data seems to be OK.</p>
<p>The file has a proper thumbnail in the media library, but when I click on it and it opens the attachment details (/wp-admin/upload.php?item=519271), there's no image there, just the default empty image icon. The details are correct though, <em>including the actual file URL</em>.</p>
<p>I tried deactivating all plugins (except the Really Simple SSL) to no effect.</p>
<p>I re-generated thumbnails using the Regenerate Thumbnails plugin, but the problem still exists.</p>
<p>The site has been hacked recently (WPCoreSys (Dolly) Hack), after which I deleted all files, changed my host password, then uploaded a clean WP, checked my database for any entries that do not belong there, so I presume WP core files are unchanged. The only folders I took from the hacked install were the uploads folder and my theme folder, but I made sure there are no corrupted files there. Anyway, I deactivated my current theme for a time and nothing changed.</p>
<p>Any ideas on what could have caused the problem?</p>
<p><strong>Edit.</strong></p>
<p>This is my code that can't get data:</p>
<pre><code>static function get_image() {
if(isset($_GET['id']) ){
$img_id = (int) $_GET['id'];
$data = array(
'image' => wp_get_attachment_image($img_id, 'thumbnail', false, array( 'id' => 'esjb-preview-image' ))
);
wp_send_json_success( $data );
} else {
wp_send_json_error();
}
}
</code></pre>
<p>The PHP class itself, as well as AJAX request, they both work just fine.</p>
<p><strong>Edit 2.</strong></p>
<p>I cloned my site to a sub-domain, created an empty database and imported images from the main site. I.e. the files are just the same. On the cloned site, the code works just fine and retrieves image data. So it looks like the issue in my database, but the wp_posts tables in both databases look identical to me, their structure is the same, the indices are the same, and there's nothing strange in the data...</p>
| [
{
"answer_id": 410864,
"author": "Lisa",
"author_id": 75600,
"author_profile": "https://wordpress.stackexchange.com/users/75600",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure how you're using it, but <code>wp_get_attachment_image_src()</code> returns an array. This should work:</p>\n<pre><code><?php\n $attachmentID = 519271;\n $imageSizeName = "thumbnail";\n $img = wp_get_attachment_image_src($attachmentID, $imageSizeName);\n?>\n\n<img src="<?php echo $img[0]; ?>" alt="image">\n</code></pre>\n<p>An alternative to try if it isn't working:</p>\n<pre><code><img src="<?php echo wp_get_attachment_url(519271); ?>" alt="image">\n</code></pre>\n<p>This thread discusses your issue further: <a href=\"https://wordpress.stackexchange.com/questions/162616/wp-get-attachment-image-src-always-returns-false\">wp_get_attachment_image_src always returns false</a></p>\n<hr />\n<p>EDIT:</p>\n<p>After reading your edit and seeing the site works elsewhere, if it is indeed a corrupted database, try adding this into your wp-config.php file:</p>\n<pre><code>define( 'WP_ALLOW_REPAIR', true );\n</code></pre>\n<p>After you have added the line, visit the database repair page: <a href=\"http://your-site.com/wp-admin/maint/repair.php\" rel=\"nofollow noreferrer\">http://your-site.com/wp-admin/maint/repair.php</a> or if you have an SSL certificate, visit <a href=\"https://your-site.com/wp-admin/maint/repair.php\" rel=\"nofollow noreferrer\">https://your-site.com/wp-admin/maint/repair.php</a>.</p>\n<p>More information on things that could help found here: <a href=\"https://wpmudev.com/blog/repairing-corrupted-broken-missing-files-databases-wordpress/\" rel=\"nofollow noreferrer\">https://wpmudev.com/blog/repairing-corrupted-broken-missing-files-databases-wordpress/</a></p>\n"
},
{
"answer_id": 410902,
"author": "Artem",
"author_id": 190417,
"author_profile": "https://wordpress.stackexchange.com/users/190417",
"pm_score": 2,
"selected": true,
"text": "<p>Culprit found!</p>\n<p>The <code>wp_postmeta</code> table's <code>meta_id</code> field didn't have an <code>auto_increment</code> attribute.</p>\n<p>I have no idea why the malware would remove the attribute.</p>\n<p>How I found the solution:</p>\n<p>I was checking if <code>wp_attachment_is('image')</code> would return true or false for a particular image. It returned false, while <code>get_post_mime_type()</code> returned "image\\png". Strange.</p>\n<p>I turned to the functions' source code and found out that wp_attachment_is() uses get_attached_file(), which, in turn, retrieves post meta for the attachment, namely the '_wp_attached_file' meta. I then saw that the images that got 'false' from wp_attachment_is('image') had no such meta.</p>\n<p>Then I tried to insert a row into the table via PHPMyAdmin. It failed because of the duplicate meta_id of 0. That indicated that meta_id field had no auto_increment attribute.</p>\n<p>The rest is simple. I added the attribute and now everything works as a charm.</p>\n<p>So, the answer to my question is:</p>\n<p>wp_get_attachment_image() returned empty string and wp_get_attachment_image_src() returned false because, while the attachment post was valid, it had no '_wp_attachment_file' meta, therefore WordPress had no data on the file to return. In turn, no meta was added to the attachment post because the 'meta_id' field had no auto_increment attribute, resulting in duplicate entry error every time WordPress tried to add meta to posts. The problem was probably caused by a recent hack.</p>\n"
}
] | 2022/10/29 | [
"https://wordpress.stackexchange.com/questions/410855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190417/"
] | The following applies to all attchment images on my site:
There is a PNG image attachment, its ID is 519271.
`wp_get_attachment_image(519271, 'thumbnail', false, array( 'id' => 'esjb-preview-image' ))` returns "".
`wp_get_attachment_image_src(519271)` returns `false`.
`wp_attachment_is_image(519271)` returns `true`
The file is there in the uploads folder. Folder permissions are 755. File permissions are 644.
The attachment is in the wp\_posts table and the data seems to be OK.
The file has a proper thumbnail in the media library, but when I click on it and it opens the attachment details (/wp-admin/upload.php?item=519271), there's no image there, just the default empty image icon. The details are correct though, *including the actual file URL*.
I tried deactivating all plugins (except the Really Simple SSL) to no effect.
I re-generated thumbnails using the Regenerate Thumbnails plugin, but the problem still exists.
The site has been hacked recently (WPCoreSys (Dolly) Hack), after which I deleted all files, changed my host password, then uploaded a clean WP, checked my database for any entries that do not belong there, so I presume WP core files are unchanged. The only folders I took from the hacked install were the uploads folder and my theme folder, but I made sure there are no corrupted files there. Anyway, I deactivated my current theme for a time and nothing changed.
Any ideas on what could have caused the problem?
**Edit.**
This is my code that can't get data:
```
static function get_image() {
if(isset($_GET['id']) ){
$img_id = (int) $_GET['id'];
$data = array(
'image' => wp_get_attachment_image($img_id, 'thumbnail', false, array( 'id' => 'esjb-preview-image' ))
);
wp_send_json_success( $data );
} else {
wp_send_json_error();
}
}
```
The PHP class itself, as well as AJAX request, they both work just fine.
**Edit 2.**
I cloned my site to a sub-domain, created an empty database and imported images from the main site. I.e. the files are just the same. On the cloned site, the code works just fine and retrieves image data. So it looks like the issue in my database, but the wp\_posts tables in both databases look identical to me, their structure is the same, the indices are the same, and there's nothing strange in the data... | Culprit found!
The `wp_postmeta` table's `meta_id` field didn't have an `auto_increment` attribute.
I have no idea why the malware would remove the attribute.
How I found the solution:
I was checking if `wp_attachment_is('image')` would return true or false for a particular image. It returned false, while `get_post_mime_type()` returned "image\png". Strange.
I turned to the functions' source code and found out that wp\_attachment\_is() uses get\_attached\_file(), which, in turn, retrieves post meta for the attachment, namely the '\_wp\_attached\_file' meta. I then saw that the images that got 'false' from wp\_attachment\_is('image') had no such meta.
Then I tried to insert a row into the table via PHPMyAdmin. It failed because of the duplicate meta\_id of 0. That indicated that meta\_id field had no auto\_increment attribute.
The rest is simple. I added the attribute and now everything works as a charm.
So, the answer to my question is:
wp\_get\_attachment\_image() returned empty string and wp\_get\_attachment\_image\_src() returned false because, while the attachment post was valid, it had no '\_wp\_attachment\_file' meta, therefore WordPress had no data on the file to return. In turn, no meta was added to the attachment post because the 'meta\_id' field had no auto\_increment attribute, resulting in duplicate entry error every time WordPress tried to add meta to posts. The problem was probably caused by a recent hack. |
410,860 | <p>I have a function that has a few and/or operators in it. I'm sure there is a better way to write this but can't seem to figure it out. I thought I could use arrays but ran into an issue with having more than one search value I need to check for.</p>
<p>My function: If the user (level 3) has clicked a button, user_meta is updated with what the current quarter is. This user meta is going to be used to track if and in which quarter the button has been clicked for said user:</p>
<pre><code>// When book now button is clicked, update the user meta with current month.
$month = date('n');
$curtQuarter = 'cc_events_Q' . ceil($month / 3);
if (!empty($_REQUEST['add_qrtly_user_meta_cc']) && $level_id == 3) {
update_user_meta($member_id, $curtQuarter, true);
}
</code></pre>
<p>Level 3 users that have clicked the button will no long have access to the content for the rest of the quarter unless they pay or until the next quarter. In the function below, if the current quarter and user_meta quarter <strong>does not</strong> match they are able to access the content. If the current quarter and user_meta quarter <strong>does</strong> match they are not able to access the content.
I then added code to remove old user_meta for quarters that aren't the current one to ensure that the following year I would get the same results:</p>
<pre><code>function all_access_levels($levels)
{
global $current_user;
$member_id = $current_user->ID;
$month = date('n');
$curtQuarter = 'cc_events_Q' . ceil($month / 3);
$key = get_user_meta($member_id, 'cc_events_Q1', true);
$key2 = get_user_meta($member_id, 'cc_events_Q2', true);
$key3 = get_user_meta($member_id, 'cc_events_Q3', true);
$key4 = get_user_meta($member_id, 'cc_events_Q4', true);
if (
$curtQuarter == 'cc_events_Q1' && empty($key) ||
$curtQuarter == 'cc_events_Q2' && empty($key2) ||
$curtQuarter == 'cc_events_Q3' && empty($key3) ||
$curtQuarter == 'cc_events_Q4' && empty($key4)
) { // Change post ID and user ID value. Adjust this accordingly.
$levels = array('3');
return $levels;
} else {
if (
$curtQuarter == 'cc_events_Q1' && !empty($key2) ||
$curtQuarter == 'cc_events_Q1' && !empty($key3) ||
$curtQuarter == 'cc_events_Q1' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q3');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q2' && !empty($key) ||
$curtQuarter == 'cc_events_Q2' && !empty($key3) ||
$curtQuarter == 'cc_events_Q2' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q3');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q3' && !empty($key) ||
$curtQuarter == 'cc_events_Q3' && !empty($key2) ||
$curtQuarter == 'cc_events_Q3' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q4' && !empty($key) ||
$curtQuarter == 'cc_events_Q4' && !empty($key2) ||
$curtQuarter == 'cc_events_Q4' && !empty($key3)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q3');
}
return false;
}
}
add_filter('cc_all_access_levels', 'all_access_levels', 10, 3);
</code></pre>
<p>I would really like to clean up my code to make it more efficient. Thank you in advance for your insight.</p>
<p><strong>UPDATE:</strong></p>
<p>The quarter is a calendar quarter e.g. Jan, Feb, Mar = Q1, Apr, May, Jun = Q2 etc. This is for a membership site. I have a member level (3) that will be able to access content for free once a quarter. If they want more access that quarter they will have to pay for additional access until the next quarter.</p>
<p>The code works as is but I know it's sub-par and I'm not sure of the proper way to clean it up.</p>
| [
{
"answer_id": 410879,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>I don't completely follow what you're trying to do, but:</p>\n<ol>\n<li><p>If the user isn't logged in you probably don't want to run the rest of the function. At the moment it looks like you will with $member_id unset.</p>\n</li>\n<li><p>Your first check is essentially <code>if (empty(get_user_meta($member_id, $curtQuarter, true)))</code> so you might as well just call that rather than loading the four other keys?</p>\n</li>\n<li><p>To delete the other keys, you could just use a loop. Something like</p>\n<pre><code>$curtQuarterNumber = ceil($month / 3);\nfor ( $quarter = 1; $quarter <= 4; $quarter++ ) {\n if ( $quarter === $curtQuarterNumber ) continue;\n\n $quarterKey = 'cc_events_Q' . $quarter;\n if ( ! empty( get_user_meta( $member_id, $quarterKey, true ) ) ) {\n delete_user_meta( $member_id, $quarterKey );\n }\n}\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 410941,
"author": "protagonist",
"author_id": 210760,
"author_profile": "https://wordpress.stackexchange.com/users/210760",
"pm_score": 1,
"selected": false,
"text": "<p>This answer is completely based on the code and help from -KIKO Software. I did have to add in the global '$current_user' for it to work correctly. Also, per @kikosoftware foresight, I added a means to track by year, just in case a user did not visit the site until the same quarter the following year.</p>\n<pre><code>function all_access_levels($current_user)\n{\n global $current_user;\n\n $user_id = $current_user->ID;\n $current_quarter = 'Q' . ceil(date('n') / 3) . '_' . date('Y');\n $past_meta_year = get_user_meta($user_id,'cc_event_date_clicked');\n $get_meta_date = $past_meta_year[0];\n $last_four_of_past_year = substr($get_meta_date,-4);\n\n // unset meta data for all other quarters\n for ($quarter = 1; $quarter <= 4; $quarter++) {\n if ('Q' . $quarter . '_' . $last_four_of_past_year != $current_quarter) {\n delete_user_meta($user_id, 'cc_event_date_clicked', 'Q' . $quarter . '_' . $last_four_of_past_year);\n }\n }\n\n // level 3 users can access when they haven't any meta data\n if (empty(get_user_meta($user_id, 'cc_event_date_clicked'))) {\n return ['3'];\n }\n return false;\n}\n\n\nadd_filter('cc_all_access_levels', 'all_access_levels', 10, 3);\n</code></pre>\n"
}
] | 2022/10/29 | [
"https://wordpress.stackexchange.com/questions/410860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/210760/"
] | I have a function that has a few and/or operators in it. I'm sure there is a better way to write this but can't seem to figure it out. I thought I could use arrays but ran into an issue with having more than one search value I need to check for.
My function: If the user (level 3) has clicked a button, user\_meta is updated with what the current quarter is. This user meta is going to be used to track if and in which quarter the button has been clicked for said user:
```
// When book now button is clicked, update the user meta with current month.
$month = date('n');
$curtQuarter = 'cc_events_Q' . ceil($month / 3);
if (!empty($_REQUEST['add_qrtly_user_meta_cc']) && $level_id == 3) {
update_user_meta($member_id, $curtQuarter, true);
}
```
Level 3 users that have clicked the button will no long have access to the content for the rest of the quarter unless they pay or until the next quarter. In the function below, if the current quarter and user\_meta quarter **does not** match they are able to access the content. If the current quarter and user\_meta quarter **does** match they are not able to access the content.
I then added code to remove old user\_meta for quarters that aren't the current one to ensure that the following year I would get the same results:
```
function all_access_levels($levels)
{
global $current_user;
$member_id = $current_user->ID;
$month = date('n');
$curtQuarter = 'cc_events_Q' . ceil($month / 3);
$key = get_user_meta($member_id, 'cc_events_Q1', true);
$key2 = get_user_meta($member_id, 'cc_events_Q2', true);
$key3 = get_user_meta($member_id, 'cc_events_Q3', true);
$key4 = get_user_meta($member_id, 'cc_events_Q4', true);
if (
$curtQuarter == 'cc_events_Q1' && empty($key) ||
$curtQuarter == 'cc_events_Q2' && empty($key2) ||
$curtQuarter == 'cc_events_Q3' && empty($key3) ||
$curtQuarter == 'cc_events_Q4' && empty($key4)
) { // Change post ID and user ID value. Adjust this accordingly.
$levels = array('3');
return $levels;
} else {
if (
$curtQuarter == 'cc_events_Q1' && !empty($key2) ||
$curtQuarter == 'cc_events_Q1' && !empty($key3) ||
$curtQuarter == 'cc_events_Q1' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q3');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q2' && !empty($key) ||
$curtQuarter == 'cc_events_Q2' && !empty($key3) ||
$curtQuarter == 'cc_events_Q2' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q3');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q3' && !empty($key) ||
$curtQuarter == 'cc_events_Q3' && !empty($key2) ||
$curtQuarter == 'cc_events_Q3' && !empty($key4)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q4');
}
if (
$curtQuarter == 'cc_events_Q4' && !empty($key) ||
$curtQuarter == 'cc_events_Q4' && !empty($key2) ||
$curtQuarter == 'cc_events_Q4' && !empty($key3)
) {
delete_user_meta($member_id, 'cc_events_Q1');
delete_user_meta($member_id, 'cc_events_Q2');
delete_user_meta($member_id, 'cc_events_Q3');
}
return false;
}
}
add_filter('cc_all_access_levels', 'all_access_levels', 10, 3);
```
I would really like to clean up my code to make it more efficient. Thank you in advance for your insight.
**UPDATE:**
The quarter is a calendar quarter e.g. Jan, Feb, Mar = Q1, Apr, May, Jun = Q2 etc. This is for a membership site. I have a member level (3) that will be able to access content for free once a quarter. If they want more access that quarter they will have to pay for additional access until the next quarter.
The code works as is but I know it's sub-par and I'm not sure of the proper way to clean it up. | This answer is completely based on the code and help from -KIKO Software. I did have to add in the global '$current\_user' for it to work correctly. Also, per @kikosoftware foresight, I added a means to track by year, just in case a user did not visit the site until the same quarter the following year.
```
function all_access_levels($current_user)
{
global $current_user;
$user_id = $current_user->ID;
$current_quarter = 'Q' . ceil(date('n') / 3) . '_' . date('Y');
$past_meta_year = get_user_meta($user_id,'cc_event_date_clicked');
$get_meta_date = $past_meta_year[0];
$last_four_of_past_year = substr($get_meta_date,-4);
// unset meta data for all other quarters
for ($quarter = 1; $quarter <= 4; $quarter++) {
if ('Q' . $quarter . '_' . $last_four_of_past_year != $current_quarter) {
delete_user_meta($user_id, 'cc_event_date_clicked', 'Q' . $quarter . '_' . $last_four_of_past_year);
}
}
// level 3 users can access when they haven't any meta data
if (empty(get_user_meta($user_id, 'cc_event_date_clicked'))) {
return ['3'];
}
return false;
}
add_filter('cc_all_access_levels', 'all_access_levels', 10, 3);
``` |
410,983 | <p>since version 6.1, wordpress loads classic-themes.min.css on our websites and crashes all of my buttons styles.</p>
<p>I only want to see my own styles in the frontend, so i'm dequeueing WP Styles like this:</p>
<pre><code>function disable_gutenberg_wp_enqueue_scripts() {
wp_dequeue_style('wp-block-library');
wp_dequeue_style('wp-block-library-theme');
}
add_filter('wp_enqueue_scripts', 'disable_gutenberg_wp_enqueue_scripts', 100);
function prefix_remove_core_block_styles() {
global $wp_styles;
foreach ( $wp_styles->queue as $key => $handle ) {
if ( strpos( $handle, 'wp-block-' ) === 0 ) {
wp_dequeue_style( $handle );
}
}
}
add_action( 'wp_enqueue_scripts', 'prefix_remove_core_block_styles' );
function prefix_remove_global_styles() {
wp_dequeue_style( 'global-styles' );
}
add_action( 'wp_enqueue_scripts', 'prefix_remove_global_styles', 100 );
remove_filter( 'render_block', 'wp_render_layout_support_flag', 10, 2 );
remove_filter( 'render_block', 'wp_render_elements_support', 10, 2 );
remove_filter( 'render_block', 'gutenberg_render_elements_support', 10, 2 );
</code></pre>
<p>Do i miss something thats loading the classic-themes.min.css?</p>
<p>Thanks for the help!</p>
| [
{
"answer_id": 410985,
"author": "emot1onz",
"author_id": 227178,
"author_profile": "https://wordpress.stackexchange.com/users/227178",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to @t31os</p>\n<p>I achieved dequeuing the stylesheet with this code:</p>\n<pre><code>function disable_classic_theme_styles() {\n wp_deregister_style('classic-theme-styles');\n wp_dequeue_style('classic-theme-styles');\n}\nadd_filter('wp_enqueue_scripts', 'disable_classic_theme_styles', 100);\n</code></pre>\n"
},
{
"answer_id": 412590,
"author": "Matt Keys",
"author_id": 32799,
"author_profile": "https://wordpress.stackexchange.com/users/32799",
"pm_score": 1,
"selected": false,
"text": "<p>I am removing it with the following code in my functions.php</p>\n<pre><code>remove_action( 'wp_enqueue_scripts', 'wp_enqueue_classic_theme_styles' );\n</code></pre>\n"
}
] | 2022/11/03 | [
"https://wordpress.stackexchange.com/questions/410983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/227178/"
] | since version 6.1, wordpress loads classic-themes.min.css on our websites and crashes all of my buttons styles.
I only want to see my own styles in the frontend, so i'm dequeueing WP Styles like this:
```
function disable_gutenberg_wp_enqueue_scripts() {
wp_dequeue_style('wp-block-library');
wp_dequeue_style('wp-block-library-theme');
}
add_filter('wp_enqueue_scripts', 'disable_gutenberg_wp_enqueue_scripts', 100);
function prefix_remove_core_block_styles() {
global $wp_styles;
foreach ( $wp_styles->queue as $key => $handle ) {
if ( strpos( $handle, 'wp-block-' ) === 0 ) {
wp_dequeue_style( $handle );
}
}
}
add_action( 'wp_enqueue_scripts', 'prefix_remove_core_block_styles' );
function prefix_remove_global_styles() {
wp_dequeue_style( 'global-styles' );
}
add_action( 'wp_enqueue_scripts', 'prefix_remove_global_styles', 100 );
remove_filter( 'render_block', 'wp_render_layout_support_flag', 10, 2 );
remove_filter( 'render_block', 'wp_render_elements_support', 10, 2 );
remove_filter( 'render_block', 'gutenberg_render_elements_support', 10, 2 );
```
Do i miss something thats loading the classic-themes.min.css?
Thanks for the help! | Thanks to @t31os
I achieved dequeuing the stylesheet with this code:
```
function disable_classic_theme_styles() {
wp_deregister_style('classic-theme-styles');
wp_dequeue_style('classic-theme-styles');
}
add_filter('wp_enqueue_scripts', 'disable_classic_theme_styles', 100);
``` |
411,113 | <p>I am using the following code to create a shortcode that generates the url of my website:</p>
<pre><code>add_shortcode( 'base_url', 'baseurl_shortcode' );
function baseurl_shortcode( $atts ) {
return site_url();
}
</code></pre>
<p>However, when the url is generated it has <code>https://</code> at the beginning of it. Is there a way to remove this please?</p>
| [
{
"answer_id": 411115,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>That would be: <code>return parse_url( get_site_url(), PHP_URL_HOST ) );</code></p>\n<p>Explanation:</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_site_url/\" rel=\"nofollow noreferrer\">get_site_url</a> is the WP function that returns the full url (it is the function that <code>site_url</code> relies on). <a href=\"https://www.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\">parse_url</a> is a PHP function that splits the url into several components and returns one or more of them. In this case it returns the hostname, which you seem to be looking for.</p>\n"
},
{
"answer_id": 411201,
"author": "Donna Hall",
"author_id": 179566,
"author_profile": "https://wordpress.stackexchange.com/users/179566",
"pm_score": 1,
"selected": false,
"text": "<p>That's great, thanks very much!</p>\n<p>This is the code I ended up using:</p>\n<pre><code>// Add site url shortcode\nfunction baseurl_shortcode($atts) {\n\n return parse_url(site_url(), PHP_URL_HOST);\n\n}\nadd_shortcode( 'base_url', 'baseurl_shortcode' );\n</code></pre>\n"
}
] | 2022/11/08 | [
"https://wordpress.stackexchange.com/questions/411113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179566/"
] | I am using the following code to create a shortcode that generates the url of my website:
```
add_shortcode( 'base_url', 'baseurl_shortcode' );
function baseurl_shortcode( $atts ) {
return site_url();
}
```
However, when the url is generated it has `https://` at the beginning of it. Is there a way to remove this please? | That would be: `return parse_url( get_site_url(), PHP_URL_HOST ) );`
Explanation:
[get\_site\_url](https://developer.wordpress.org/reference/functions/get_site_url/) is the WP function that returns the full url (it is the function that `site_url` relies on). [parse\_url](https://www.php.net/manual/en/function.parse-url.php) is a PHP function that splits the url into several components and returns one or more of them. In this case it returns the hostname, which you seem to be looking for. |
411,187 | <p>I am using the following code and I can't see anything in the footer of my site on the front end where the wp_footer function is called. It does, however, appear before the opening <code><!DOCTYPE html></code> in the admin area.</p>
<pre><code>function xyz_footer_print() {
echo 'footer script here';
}
add_action( 'wp_footer', xyz_footer_print() );
</code></pre>
| [
{
"answer_id": 411188,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>What's happening here is your <code>echo</code> is executing before anything else.</p>\n<p>Try using the <code>wp_enqueue_scripts</code> hook instead of <code>wp_footer</code>, and instead of <code>echo</code> you will <code>wp_enqueue_script()</code>.</p>\n<pre><code><?php\n// Using a different hook:\nadd_action( 'wp_enqueue_scripts', 'wpse_411187_script' );\n\nfunction wpse_411187_script() {\n wp_enqueue_script(\n // "Handle" - a unique name for your script\n 'xyz-footer-print',\n // Path to the JS file - adjust as needed\n plugins_url( 'build/xyz-footer-print.js', dirname( __DIR__ ) ),\n // Array of dependencies\n '',\n // Version number\n '1.0',\n // True to place the script the footer\n true\n );\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 411189,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That's because you're not using <code>add_action</code> correctly, what you've written is functionally the same as this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function xyz_footer_print() {\n echo 'footer script here';\n}\n$value = xyz_footer_print();\nadd_action( 'wp_footer', $value );\n</code></pre>\n<p><code>xyz_footer_print()</code> immediately runs the function and returns nothing. As a result your <code>add_action</code> call says that on the <code>wp_footer</code> even, do nothing.</p>\n<p>So you actually have 2 problems not 1, and if you check your PHP error log or install a tool such as query monitor/debug bar you'd see the warning/notice.</p>\n<p>Instead actions always take the form:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'action name', 'callable type value, aka the name of function to run when the action happens' );\n</code></pre>\n<p><strong>That should give you enough information to fix this, but, it's the wrong way to put javascript in your footer.</strong> You should instead use a JS file and enqueue it the way webelaine suggested.</p>\n"
}
] | 2022/11/10 | [
"https://wordpress.stackexchange.com/questions/411187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66660/"
] | I am using the following code and I can't see anything in the footer of my site on the front end where the wp\_footer function is called. It does, however, appear before the opening `<!DOCTYPE html>` in the admin area.
```
function xyz_footer_print() {
echo 'footer script here';
}
add_action( 'wp_footer', xyz_footer_print() );
``` | That's because you're not using `add_action` correctly, what you've written is functionally the same as this:
```php
function xyz_footer_print() {
echo 'footer script here';
}
$value = xyz_footer_print();
add_action( 'wp_footer', $value );
```
`xyz_footer_print()` immediately runs the function and returns nothing. As a result your `add_action` call says that on the `wp_footer` even, do nothing.
So you actually have 2 problems not 1, and if you check your PHP error log or install a tool such as query monitor/debug bar you'd see the warning/notice.
Instead actions always take the form:
```php
add_action( 'action name', 'callable type value, aka the name of function to run when the action happens' );
```
**That should give you enough information to fix this, but, it's the wrong way to put javascript in your footer.** You should instead use a JS file and enqueue it the way webelaine suggested. |
411,323 | <p>I made a WordPress plugin, so now what I want is, I want to set a logic like if a certain theme is active, then load the plugin. Else, only keep the plugin activated, but don't apply any changes on the site.
Any idea how can I achieve that? Sorry if I sound very nerdy :')</p>
| [
{
"answer_id": 411325,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>Use <code>get_stylesheet()</code> to get the directory name of the theme being used. If a child theme is being used you can determine the parent with <code>get_template()</code>.</p>\n<p>At the top of the plugin file you can simply <code>return</code> early if the value is not what you want.</p>\n<pre><code>if ( 'my-theme' !== get_stylesheet() ) {\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 411342,
"author": "mehdi eybak abadi",
"author_id": 225135,
"author_profile": "https://wordpress.stackexchange.com/users/225135",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>wp_get_theme()</code> function to get information about the active theme and specify its name.</p>\n<pre><code>\nadd_action('init', 'pre_function_test');\nfunction pre_function_test()\n{\n $var = wp_get_theme();\n $theme_name = $var['Name'];\n if( $theme_name == 'Hello Elementor'){\n wp_die('is theme verify !');\n }\n}\n</code></pre>\n<p>Here my theme name is Hello Elementor and my condition is executed.</p>\n<p><strong>Note</strong>: You can see the theme name from the theme directory and style.css file.</p>\n<p>The wp_get_theme() function returns the current theme information.</p>\n<p>See in this picture:</p>\n<p><a href=\"https://i.stack.imgur.com/9gvSQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9gvSQ.png\" alt=\"get wordpress theme name\" /></a></p>\n"
}
] | 2022/11/16 | [
"https://wordpress.stackexchange.com/questions/411323",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/227221/"
] | I made a WordPress plugin, so now what I want is, I want to set a logic like if a certain theme is active, then load the plugin. Else, only keep the plugin activated, but don't apply any changes on the site.
Any idea how can I achieve that? Sorry if I sound very nerdy :') | Use `get_stylesheet()` to get the directory name of the theme being used. If a child theme is being used you can determine the parent with `get_template()`.
At the top of the plugin file you can simply `return` early if the value is not what you want.
```
if ( 'my-theme' !== get_stylesheet() ) {
return;
}
``` |
411,478 | <p>I am pulling a response from an API using PHP to display a list of content on my WordPress website from an external service. The way they have their API set up, I need to create a loop that checks if there is a "next page" of data that I can access. The API returns a header item called "Links", with the following content:</p>
<pre><code><https://external.service.com/myusername/api/opportunities>; rel="first",<https://external.service.com/myusername/api/opportunities?before=512a7905-65a3-4845-bb8f-d2363c9e1d95>; rel="prev",<https://external.service.com/myusername/api/opportunities?after=2ab72e09-82d9-4c80-a3bb-4a2fea248695>; rel="next"
</code></pre>
<p>I can use the "Next" link to call the API again, which gives me the next page of data. A bit odd, but that's the way they have their API set up...not much I can do about it.</p>
<p>I'm assuming the best way to do this is by using a regular expression to copy the "Next" link to a variable, and create a loop which calls the link stored in the variable, updating it each time. I'm having trouble coming up with the regular expression that could do this, though. Is it possible to do without it catching the other three links as well?</p>
| [
{
"answer_id": 411325,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>Use <code>get_stylesheet()</code> to get the directory name of the theme being used. If a child theme is being used you can determine the parent with <code>get_template()</code>.</p>\n<p>At the top of the plugin file you can simply <code>return</code> early if the value is not what you want.</p>\n<pre><code>if ( 'my-theme' !== get_stylesheet() ) {\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 411342,
"author": "mehdi eybak abadi",
"author_id": 225135,
"author_profile": "https://wordpress.stackexchange.com/users/225135",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>wp_get_theme()</code> function to get information about the active theme and specify its name.</p>\n<pre><code>\nadd_action('init', 'pre_function_test');\nfunction pre_function_test()\n{\n $var = wp_get_theme();\n $theme_name = $var['Name'];\n if( $theme_name == 'Hello Elementor'){\n wp_die('is theme verify !');\n }\n}\n</code></pre>\n<p>Here my theme name is Hello Elementor and my condition is executed.</p>\n<p><strong>Note</strong>: You can see the theme name from the theme directory and style.css file.</p>\n<p>The wp_get_theme() function returns the current theme information.</p>\n<p>See in this picture:</p>\n<p><a href=\"https://i.stack.imgur.com/9gvSQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9gvSQ.png\" alt=\"get wordpress theme name\" /></a></p>\n"
}
] | 2022/11/23 | [
"https://wordpress.stackexchange.com/questions/411478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/227335/"
] | I am pulling a response from an API using PHP to display a list of content on my WordPress website from an external service. The way they have their API set up, I need to create a loop that checks if there is a "next page" of data that I can access. The API returns a header item called "Links", with the following content:
```
<https://external.service.com/myusername/api/opportunities>; rel="first",<https://external.service.com/myusername/api/opportunities?before=512a7905-65a3-4845-bb8f-d2363c9e1d95>; rel="prev",<https://external.service.com/myusername/api/opportunities?after=2ab72e09-82d9-4c80-a3bb-4a2fea248695>; rel="next"
```
I can use the "Next" link to call the API again, which gives me the next page of data. A bit odd, but that's the way they have their API set up...not much I can do about it.
I'm assuming the best way to do this is by using a regular expression to copy the "Next" link to a variable, and create a loop which calls the link stored in the variable, updating it each time. I'm having trouble coming up with the regular expression that could do this, though. Is it possible to do without it catching the other three links as well? | Use `get_stylesheet()` to get the directory name of the theme being used. If a child theme is being used you can determine the parent with `get_template()`.
At the top of the plugin file you can simply `return` early if the value is not what you want.
```
if ( 'my-theme' !== get_stylesheet() ) {
return;
}
``` |
411,644 | <p>I made a true/false ACF field called <code>display_sorting</code>. It appears that it returns <code>null</code> no matter if I set the default value or not.</p>
<pre><code><?php var_dump(get_field('display_sorting'));?>
returns :
[...].php:26:null
</code></pre>
<p>If I update the value from the page the field appears, the value will be correctly set to <code>true</code> or <code>false</code>.</p>
<pre><code><?php var_dump(get_field('display_sorting'));?>
will return this time :
[...].php:26:false
or
[...].php:26:true
</code></pre>
<p>My problem is that I would like to set the default value to <code>true</code> (which is supposed to be the option I try here) so I don't have to set manually the value on x pages, but currently the default value isn't properly read.</p>
<p>Am I missing something ?</p>
| [
{
"answer_id": 411645,
"author": "Harit Panchal",
"author_id": 184415,
"author_profile": "https://wordpress.stackexchange.com/users/184415",
"pm_score": 2,
"selected": false,
"text": "<p>You will need to update every existing post otherwise, you will get NULL every time even if you set the default value to <strong>TRUE</strong>.</p>\n<p>You can bulk edit/update altogether.</p>\n"
},
{
"answer_id": 411646,
"author": "Buttered_Toast",
"author_id": 192133,
"author_profile": "https://wordpress.stackexchange.com/users/192133",
"pm_score": 2,
"selected": false,
"text": "<p>As Harit Panchal mentioned.<br />\nCreating a new ACF field, true/false in this case, and setting a default value for it, wont automatically set this value for every existing post, page, term, etc, it's connected to.</p>\n<p>What you can do in this case is this.<br />\nWe know that non existing field value is <code>null</code>, you want that the default will be true, and instead of going one by one and updating the field you can so this condition.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// set the value to a variable as we will use it more than once\n$display_sorting = get_field('display_sorting');\n\nif ($display_sorting === true || is_null($display_sorting)) {\n \n} else {\n \n}\n</code></pre>\n<p>Because we want the default to be true and we know that non existing meta returns <code>null</code>, we created a logic that would consider both cases as a truthy value.</p>\n"
},
{
"answer_id": 411689,
"author": "MD-Tech",
"author_id": 227946,
"author_profile": "https://wordpress.stackexchange.com/users/227946",
"pm_score": 1,
"selected": false,
"text": "<p>The answers so far explain how to fix this but not why it happens. The issue exists because when you created the existing items the default was null. This means that the existing items have a value in the display_sorting field. When you change the default the code doesn't know whether or not to update the existing items all it knows is that the default for new items is "true". It isn't clear whether or not null is still a valid value for items that were created prior to the new default. The principle of "least surprise" indicates that if there's a choice of doing something and doing nothing with no further information a system should do nothing. The code doesn't even know whether you have something that specifically handles the old nulls.</p>\n<p>To illustrate slightly differently, imagine this is a price field where the previous default was $1 (i.e. not implicitly null), somethings are currently correctly priced at $1, and you're updating your default price to $2 for inflation. Do you suddenly want everything priced at $1 to be priced at $2? $1 is still a valid price for some items, would you like to review which items will double in price before mass updating them? I'd want to know which items were changing.</p>\n<p>If you know that all of your null values are to be updated to true then you have to specifically do that yourself. The alternative is far worse than the current solution.</p>\n"
}
] | 2022/11/29 | [
"https://wordpress.stackexchange.com/questions/411644",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/227910/"
] | I made a true/false ACF field called `display_sorting`. It appears that it returns `null` no matter if I set the default value or not.
```
<?php var_dump(get_field('display_sorting'));?>
returns :
[...].php:26:null
```
If I update the value from the page the field appears, the value will be correctly set to `true` or `false`.
```
<?php var_dump(get_field('display_sorting'));?>
will return this time :
[...].php:26:false
or
[...].php:26:true
```
My problem is that I would like to set the default value to `true` (which is supposed to be the option I try here) so I don't have to set manually the value on x pages, but currently the default value isn't properly read.
Am I missing something ? | You will need to update every existing post otherwise, you will get NULL every time even if you set the default value to **TRUE**.
You can bulk edit/update altogether. |
411,663 | <p>I want to display an block attribute named "paragraph" that exists in each post inside a CPT named "test".
I have no issues displaying the current page attributes(selectLgColumns & borderClass). The problem is I am not able to get the block attributes from the post that are indise the CPT. I don't know much php. I used the documentation to come up with the following code. Can anyone please help?</p>
<pre class="lang-php prettyprint-override"><code><?php
add_action('plugins_loaded', 'register_latest_post');
function register_latest_post() {
register_block_type('boot/block-lead1', [ 'render_callback' => 'render_latest_post1'
]);
}
function render_latest_post1( $attributes ) {
$column = $attributes['selectLgColumns'];
$border = $attributes['borderClass'];
$desc = $attributes['desc'];
$latest_posts1 = wp_get_recent_posts( [
'post_type' => 'test',
'numberposts' => 3,
'post_status' => 'publish',
'attributes' => 'attributes' //not sure how to get the attributes from each post.
] );
if(empty($latest_posts1)){
return '<p>No posts</p>';
}
$posts_output = '<div class="latest-postss">';
foreach($latest_posts1 as $post ) {
$post_id = $post['ID'];
function render_latest_post( $attributes ) { //not sure how to use this function
$para = $attributes['paragraph']; // I need to display this attribute from the block Thats added in the post
}
$post_thumbnail = get_the_post_thumbnail_url( $post_id, 'full' );
$posts_output .= '<div class="post-title ' .$column. ' ' .$border. '">
<img src="'. $post_thumbnail .'" class="img-fluid" loading="lazy" />
<h2>
<a href="'.get_permalink($post_id). '">
'.get_the_title( $post_id ).'
</a>
</h2>
<p> ' .$column. ' ' .$border. ' </p>
<p>Desc: ' . $para . ' </p>
</div>';
}
$posts_output .= '</div>';
return $posts_output;
}
add_action('rest_api_init', 'register_rest_images1' );
function register_rest_images1(){
register_rest_field( array('test'),
'fimg_url',
array(
'get_callback' => 'get_rest_featured_image1',
'update_callback' => null,
'schema' => null,
)
);
}
function get_rest_featured_image1( $object, $field_name, $request) { if( $object['featured_media'] ) {
$img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' ); return $img[0];
}
return false;
}
function parse_blocks1( $content ) {
$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
$parser = new $parser_class();
return $parser->parse( $content );
}
</code></pre>
| [
{
"answer_id": 411659,
"author": "Scriptile",
"author_id": 125086,
"author_profile": "https://wordpress.stackexchange.com/users/125086",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, so I had 5.5 version of wordpress and it was Incompatible with 8 PHP (on new server) so I updated Wordpress to 6.1 and it worked.</p>\n"
},
{
"answer_id": 411672,
"author": "rexkogitans",
"author_id": 196282,
"author_profile": "https://wordpress.stackexchange.com/users/196282",
"pm_score": 1,
"selected": false,
"text": "<p>Too long for a comment, but here is a suggestion. What have you done so far? I recently moved a site successfully like this:</p>\n<ol>\n<li>Dump DB</li>\n<li>In the Dump, replace every occurence of the old site URL by the new site URL.</li>\n<li>Copy over the entire directory</li>\n<li>Fit the configuration <code>wp-config.php</code> (DB access, site URL, TLS proxy)</li>\n<li>Replay the modified dump in the new database</li>\n<li>Load WordPress</li>\n<li>Flush all caches, if there are some</li>\n</ol>\n<p>Note that points 2 and 4 are crucial.</p>\n"
}
] | 2022/11/29 | [
"https://wordpress.stackexchange.com/questions/411663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192926/"
] | I want to display an block attribute named "paragraph" that exists in each post inside a CPT named "test".
I have no issues displaying the current page attributes(selectLgColumns & borderClass). The problem is I am not able to get the block attributes from the post that are indise the CPT. I don't know much php. I used the documentation to come up with the following code. Can anyone please help?
```php
<?php
add_action('plugins_loaded', 'register_latest_post');
function register_latest_post() {
register_block_type('boot/block-lead1', [ 'render_callback' => 'render_latest_post1'
]);
}
function render_latest_post1( $attributes ) {
$column = $attributes['selectLgColumns'];
$border = $attributes['borderClass'];
$desc = $attributes['desc'];
$latest_posts1 = wp_get_recent_posts( [
'post_type' => 'test',
'numberposts' => 3,
'post_status' => 'publish',
'attributes' => 'attributes' //not sure how to get the attributes from each post.
] );
if(empty($latest_posts1)){
return '<p>No posts</p>';
}
$posts_output = '<div class="latest-postss">';
foreach($latest_posts1 as $post ) {
$post_id = $post['ID'];
function render_latest_post( $attributes ) { //not sure how to use this function
$para = $attributes['paragraph']; // I need to display this attribute from the block Thats added in the post
}
$post_thumbnail = get_the_post_thumbnail_url( $post_id, 'full' );
$posts_output .= '<div class="post-title ' .$column. ' ' .$border. '">
<img src="'. $post_thumbnail .'" class="img-fluid" loading="lazy" />
<h2>
<a href="'.get_permalink($post_id). '">
'.get_the_title( $post_id ).'
</a>
</h2>
<p> ' .$column. ' ' .$border. ' </p>
<p>Desc: ' . $para . ' </p>
</div>';
}
$posts_output .= '</div>';
return $posts_output;
}
add_action('rest_api_init', 'register_rest_images1' );
function register_rest_images1(){
register_rest_field( array('test'),
'fimg_url',
array(
'get_callback' => 'get_rest_featured_image1',
'update_callback' => null,
'schema' => null,
)
);
}
function get_rest_featured_image1( $object, $field_name, $request) { if( $object['featured_media'] ) {
$img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' ); return $img[0];
}
return false;
}
function parse_blocks1( $content ) {
$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
$parser = new $parser_class();
return $parser->parse( $content );
}
``` | Ok, so I had 5.5 version of wordpress and it was Incompatible with 8 PHP (on new server) so I updated Wordpress to 6.1 and it worked. |
411,759 | <p>I am looking for a function to fill a user meta data automatically when they register.</p>
<p>In the registration form we ask for user email. Once they validate their registration, we want to get that value and store it in a custom field (already created) named "Form_URL" like this :
<a href="https://www.ourwebsite.com/USEREMAIL/form/" rel="nofollow noreferrer">https://www.ourwebsite.com/USEREMAIL/form/</a></p>
<p>So we need to concatenate "https://www.ourwebsite.com/" the user email and "/form/" and store it in the custom fied "Form_URL" after the registration.</p>
<p>So we start the following function but we are blocked :</p>
<pre><code>add_action('user_register', 'add_form_link', 10, 1);
function add_form_link($user_id)
{
$emailurl = 'https://www.ourwebsite.com/' . ???? . '/form/';
add_user_meta( $user_id, 'Form_URL', $emailurl , true );
}
</code></pre>
<p>PS : Our website is a Wordpress and we use Gravity Forms as the registration Form.</p>
| [
{
"answer_id": 411659,
"author": "Scriptile",
"author_id": 125086,
"author_profile": "https://wordpress.stackexchange.com/users/125086",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, so I had 5.5 version of wordpress and it was Incompatible with 8 PHP (on new server) so I updated Wordpress to 6.1 and it worked.</p>\n"
},
{
"answer_id": 411672,
"author": "rexkogitans",
"author_id": 196282,
"author_profile": "https://wordpress.stackexchange.com/users/196282",
"pm_score": 1,
"selected": false,
"text": "<p>Too long for a comment, but here is a suggestion. What have you done so far? I recently moved a site successfully like this:</p>\n<ol>\n<li>Dump DB</li>\n<li>In the Dump, replace every occurence of the old site URL by the new site URL.</li>\n<li>Copy over the entire directory</li>\n<li>Fit the configuration <code>wp-config.php</code> (DB access, site URL, TLS proxy)</li>\n<li>Replay the modified dump in the new database</li>\n<li>Load WordPress</li>\n<li>Flush all caches, if there are some</li>\n</ol>\n<p>Note that points 2 and 4 are crucial.</p>\n"
}
] | 2022/12/02 | [
"https://wordpress.stackexchange.com/questions/411759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/228013/"
] | I am looking for a function to fill a user meta data automatically when they register.
In the registration form we ask for user email. Once they validate their registration, we want to get that value and store it in a custom field (already created) named "Form\_URL" like this :
<https://www.ourwebsite.com/USEREMAIL/form/>
So we need to concatenate "https://www.ourwebsite.com/" the user email and "/form/" and store it in the custom fied "Form\_URL" after the registration.
So we start the following function but we are blocked :
```
add_action('user_register', 'add_form_link', 10, 1);
function add_form_link($user_id)
{
$emailurl = 'https://www.ourwebsite.com/' . ???? . '/form/';
add_user_meta( $user_id, 'Form_URL', $emailurl , true );
}
```
PS : Our website is a Wordpress and we use Gravity Forms as the registration Form. | Ok, so I had 5.5 version of wordpress and it was Incompatible with 8 PHP (on new server) so I updated Wordpress to 6.1 and it worked. |
Subsets and Splits