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
|
---|---|---|---|---|---|---|
378,842 | <p>I have come across a wonderful portfolio website <a href="https://dogstudio.co/" rel="nofollow noreferrer">https://dogstudio.co/</a> while I was looking for examples of design. Upon exploring the source-code, it was apparent that this was a wordpress website after all.</p>
<p>What I don't understand is how and why does it not have the typical wordpress directory hierarchy. For example, this is the URL to their CSS file, <a href="https://dogstudio.co/app/themes/portfolio-2018/static/css/main.css" rel="nofollow noreferrer">https://dogstudio.co/app/themes/portfolio-2018/static/css/main.css</a>.</p>
<p>A typical wordpress website would have something like this, <a href="https://www.example.com/wp-content/themes/theme_name/style.css" rel="nofollow noreferrer">https://www.example.com/wp-content/themes/theme_name/style.css</a> (the <strong>wp-content</strong> and <strong>wp-</strong> prefixed directories) as a general rule of thumb for making wordpress themes.</p>
<p>So was it made using a framework? I really need to understand this.</p>
| [
{
"answer_id": 378875,
"author": "Brian Burton",
"author_id": 158744,
"author_profile": "https://wordpress.stackexchange.com/users/158744",
"pm_score": 0,
"selected": false,
"text": "<p>You can store WordPress static assets anywhere, even on a CDN completely separate from the server hosting your website. Most likely what they're doing here are utilizing server rewrites that point /app/themes -> /wp-content/themes.</p>\n<p>It's also possible to change the location of the wp-content/themes path completely using the <code>register_theme_directory(ABSPATH . 'app/themes')</code> function.</p>\n<p>If you're asking why they did this, it could be as simple as code aesthetics or as complex as a customized multisite installation with once centralized WordPress codebase.</p>\n"
},
{
"answer_id": 378880,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an <code>app</code> subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.</p>\n<p>It's also possible they use standard WordPress but have renamed <code>wp-content</code> using constants in <code>wp-config.php</code> , e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('WP_CONTENT_URL', 'https://example.com/app');\ndefine('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');\n</code></pre>\n<h2>Why Change the wp-content directory location?</h2>\n<p>If you want to use a git submodule to install WordPress, or a package manager such as <code>composer</code>, having WordPress in a subfolder on its own makes it easier to update and install.</p>\n<p>This necessitates moving <code>wp-content</code> out of that folder though to avoid nested folders. E.g <code>composer</code> updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.</p>\n<p>So instead, you might have a folder structure like this:</p>\n<pre><code> - wordpress ( sometimes wp )\n - wp-content\n - themes\n - plugins\n - etc..\n - wp-config.php\n - index.php\n</code></pre>\n<p>Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.</p>\n<p>As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">https://roots.io/bedrock/</a> and ask in their community</p>\n"
}
] | 2020/11/26 | [
"https://wordpress.stackexchange.com/questions/378842",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192517/"
] | I have come across a wonderful portfolio website <https://dogstudio.co/> while I was looking for examples of design. Upon exploring the source-code, it was apparent that this was a wordpress website after all.
What I don't understand is how and why does it not have the typical wordpress directory hierarchy. For example, this is the URL to their CSS file, <https://dogstudio.co/app/themes/portfolio-2018/static/css/main.css>.
A typical wordpress website would have something like this, <https://www.example.com/wp-content/themes/theme_name/style.css> (the **wp-content** and **wp-** prefixed directories) as a general rule of thumb for making wordpress themes.
So was it made using a framework? I really need to understand this. | That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an `app` subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.
It's also possible they use standard WordPress but have renamed `wp-content` using constants in `wp-config.php` , e.g.
```php
define('WP_CONTENT_URL', 'https://example.com/app');
define('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');
```
Why Change the wp-content directory location?
---------------------------------------------
If you want to use a git submodule to install WordPress, or a package manager such as `composer`, having WordPress in a subfolder on its own makes it easier to update and install.
This necessitates moving `wp-content` out of that folder though to avoid nested folders. E.g `composer` updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.
So instead, you might have a folder structure like this:
```
- wordpress ( sometimes wp )
- wp-content
- themes
- plugins
- etc..
- wp-config.php
- index.php
```
Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.
As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <https://roots.io/bedrock/> and ask in their community |
378,869 | <p>I have main menu which displays two types of links: CPT and Subcategory.
I create the menu with a custom request: I retrieve the Custom Post Type then the sub-categories of the main category in Alphabetical order :</p>
<pre><code>Category A: - Product a - Product b - sub category a - sub category b ...
</code></pre>
<p>But, my client wants a custom display example:</p>
<pre><code>Category A: sub category a - Product b - Product a - sub category b ...
</code></pre>
<p>I thought about creating a Drag Drop solution ... but how to implement it</p>
| [
{
"answer_id": 378875,
"author": "Brian Burton",
"author_id": 158744,
"author_profile": "https://wordpress.stackexchange.com/users/158744",
"pm_score": 0,
"selected": false,
"text": "<p>You can store WordPress static assets anywhere, even on a CDN completely separate from the server hosting your website. Most likely what they're doing here are utilizing server rewrites that point /app/themes -> /wp-content/themes.</p>\n<p>It's also possible to change the location of the wp-content/themes path completely using the <code>register_theme_directory(ABSPATH . 'app/themes')</code> function.</p>\n<p>If you're asking why they did this, it could be as simple as code aesthetics or as complex as a customized multisite installation with once centralized WordPress codebase.</p>\n"
},
{
"answer_id": 378880,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an <code>app</code> subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.</p>\n<p>It's also possible they use standard WordPress but have renamed <code>wp-content</code> using constants in <code>wp-config.php</code> , e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('WP_CONTENT_URL', 'https://example.com/app');\ndefine('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');\n</code></pre>\n<h2>Why Change the wp-content directory location?</h2>\n<p>If you want to use a git submodule to install WordPress, or a package manager such as <code>composer</code>, having WordPress in a subfolder on its own makes it easier to update and install.</p>\n<p>This necessitates moving <code>wp-content</code> out of that folder though to avoid nested folders. E.g <code>composer</code> updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.</p>\n<p>So instead, you might have a folder structure like this:</p>\n<pre><code> - wordpress ( sometimes wp )\n - wp-content\n - themes\n - plugins\n - etc..\n - wp-config.php\n - index.php\n</code></pre>\n<p>Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.</p>\n<p>As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">https://roots.io/bedrock/</a> and ask in their community</p>\n"
}
] | 2020/11/26 | [
"https://wordpress.stackexchange.com/questions/378869",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65465/"
] | I have main menu which displays two types of links: CPT and Subcategory.
I create the menu with a custom request: I retrieve the Custom Post Type then the sub-categories of the main category in Alphabetical order :
```
Category A: - Product a - Product b - sub category a - sub category b ...
```
But, my client wants a custom display example:
```
Category A: sub category a - Product b - Product a - sub category b ...
```
I thought about creating a Drag Drop solution ... but how to implement it | That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an `app` subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.
It's also possible they use standard WordPress but have renamed `wp-content` using constants in `wp-config.php` , e.g.
```php
define('WP_CONTENT_URL', 'https://example.com/app');
define('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');
```
Why Change the wp-content directory location?
---------------------------------------------
If you want to use a git submodule to install WordPress, or a package manager such as `composer`, having WordPress in a subfolder on its own makes it easier to update and install.
This necessitates moving `wp-content` out of that folder though to avoid nested folders. E.g `composer` updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.
So instead, you might have a folder structure like this:
```
- wordpress ( sometimes wp )
- wp-content
- themes
- plugins
- etc..
- wp-config.php
- index.php
```
Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.
As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <https://roots.io/bedrock/> and ask in their community |
378,893 | <p>I am trying to use custom HTML in a widget and I can't make an <code>img</code> tag to work because I have no idea where to store the image.</p>
<p>Where does one store an image inside a WordPress website ? And not by "Upload Image", no. By using FTP. Where exactly do I have to store images so that I can link them to an <code>img</code> tag.</p>
| [
{
"answer_id": 378875,
"author": "Brian Burton",
"author_id": 158744,
"author_profile": "https://wordpress.stackexchange.com/users/158744",
"pm_score": 0,
"selected": false,
"text": "<p>You can store WordPress static assets anywhere, even on a CDN completely separate from the server hosting your website. Most likely what they're doing here are utilizing server rewrites that point /app/themes -> /wp-content/themes.</p>\n<p>It's also possible to change the location of the wp-content/themes path completely using the <code>register_theme_directory(ABSPATH . 'app/themes')</code> function.</p>\n<p>If you're asking why they did this, it could be as simple as code aesthetics or as complex as a customized multisite installation with once centralized WordPress codebase.</p>\n"
},
{
"answer_id": 378880,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an <code>app</code> subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.</p>\n<p>It's also possible they use standard WordPress but have renamed <code>wp-content</code> using constants in <code>wp-config.php</code> , e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('WP_CONTENT_URL', 'https://example.com/app');\ndefine('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');\n</code></pre>\n<h2>Why Change the wp-content directory location?</h2>\n<p>If you want to use a git submodule to install WordPress, or a package manager such as <code>composer</code>, having WordPress in a subfolder on its own makes it easier to update and install.</p>\n<p>This necessitates moving <code>wp-content</code> out of that folder though to avoid nested folders. E.g <code>composer</code> updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.</p>\n<p>So instead, you might have a folder structure like this:</p>\n<pre><code> - wordpress ( sometimes wp )\n - wp-content\n - themes\n - plugins\n - etc..\n - wp-config.php\n - index.php\n</code></pre>\n<p>Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.</p>\n<p>As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">https://roots.io/bedrock/</a> and ask in their community</p>\n"
}
] | 2020/11/26 | [
"https://wordpress.stackexchange.com/questions/378893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198154/"
] | I am trying to use custom HTML in a widget and I can't make an `img` tag to work because I have no idea where to store the image.
Where does one store an image inside a WordPress website ? And not by "Upload Image", no. By using FTP. Where exactly do I have to store images so that I can link them to an `img` tag. | That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an `app` subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.
It's also possible they use standard WordPress but have renamed `wp-content` using constants in `wp-config.php` , e.g.
```php
define('WP_CONTENT_URL', 'https://example.com/app');
define('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');
```
Why Change the wp-content directory location?
---------------------------------------------
If you want to use a git submodule to install WordPress, or a package manager such as `composer`, having WordPress in a subfolder on its own makes it easier to update and install.
This necessitates moving `wp-content` out of that folder though to avoid nested folders. E.g `composer` updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.
So instead, you might have a folder structure like this:
```
- wordpress ( sometimes wp )
- wp-content
- themes
- plugins
- etc..
- wp-config.php
- index.php
```
Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.
As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <https://roots.io/bedrock/> and ask in their community |
378,952 | <p>I use norebo theme</p>
<p>I use it when I open a Portfolio the link is in this format</p>
<pre><code>https://www.hshnorm.com/project/fruit-flavored-powder-juice/
</code></pre>
<p>How can I remove the word <code>project</code></p>
<p>To be the link in this format</p>
<pre><code>https://www.hshnorm.com/fruit-flavored-powder-juice/
</code></pre>
| [
{
"answer_id": 378875,
"author": "Brian Burton",
"author_id": 158744,
"author_profile": "https://wordpress.stackexchange.com/users/158744",
"pm_score": 0,
"selected": false,
"text": "<p>You can store WordPress static assets anywhere, even on a CDN completely separate from the server hosting your website. Most likely what they're doing here are utilizing server rewrites that point /app/themes -> /wp-content/themes.</p>\n<p>It's also possible to change the location of the wp-content/themes path completely using the <code>register_theme_directory(ABSPATH . 'app/themes')</code> function.</p>\n<p>If you're asking why they did this, it could be as simple as code aesthetics or as complex as a customized multisite installation with once centralized WordPress codebase.</p>\n"
},
{
"answer_id": 378880,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an <code>app</code> subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.</p>\n<p>It's also possible they use standard WordPress but have renamed <code>wp-content</code> using constants in <code>wp-config.php</code> , e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('WP_CONTENT_URL', 'https://example.com/app');\ndefine('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');\n</code></pre>\n<h2>Why Change the wp-content directory location?</h2>\n<p>If you want to use a git submodule to install WordPress, or a package manager such as <code>composer</code>, having WordPress in a subfolder on its own makes it easier to update and install.</p>\n<p>This necessitates moving <code>wp-content</code> out of that folder though to avoid nested folders. E.g <code>composer</code> updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.</p>\n<p>So instead, you might have a folder structure like this:</p>\n<pre><code> - wordpress ( sometimes wp )\n - wp-content\n - themes\n - plugins\n - etc..\n - wp-config.php\n - index.php\n</code></pre>\n<p>Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.</p>\n<p>As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">https://roots.io/bedrock/</a> and ask in their community</p>\n"
}
] | 2020/11/27 | [
"https://wordpress.stackexchange.com/questions/378952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198191/"
] | I use norebo theme
I use it when I open a Portfolio the link is in this format
```
https://www.hshnorm.com/project/fruit-flavored-powder-juice/
```
How can I remove the word `project`
To be the link in this format
```
https://www.hshnorm.com/fruit-flavored-powder-juice/
``` | That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an `app` subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.
It's also possible they use standard WordPress but have renamed `wp-content` using constants in `wp-config.php` , e.g.
```php
define('WP_CONTENT_URL', 'https://example.com/app');
define('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');
```
Why Change the wp-content directory location?
---------------------------------------------
If you want to use a git submodule to install WordPress, or a package manager such as `composer`, having WordPress in a subfolder on its own makes it easier to update and install.
This necessitates moving `wp-content` out of that folder though to avoid nested folders. E.g `composer` updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.
So instead, you might have a folder structure like this:
```
- wordpress ( sometimes wp )
- wp-content
- themes
- plugins
- etc..
- wp-config.php
- index.php
```
Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.
As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <https://roots.io/bedrock/> and ask in their community |
378,977 | <p>I need to deregister JS scripts everywhere except on one product page, so far this is my code:</p>
<pre><code>add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
if ( !is_product('67688') ) {
wp_deregister_script( 'wc-lottery-jquery-plugin' );
wp_deregister_script( 'wc-lottery-countdown' );
wp_deregister_script( 'wc-lottery-countdown-language' );
wp_deregister_script( 'wc-lottery-public' );
}
}
</code></pre>
<p>Is this correct? Many thanks for your confirmation!</p>
| [
{
"answer_id": 378875,
"author": "Brian Burton",
"author_id": 158744,
"author_profile": "https://wordpress.stackexchange.com/users/158744",
"pm_score": 0,
"selected": false,
"text": "<p>You can store WordPress static assets anywhere, even on a CDN completely separate from the server hosting your website. Most likely what they're doing here are utilizing server rewrites that point /app/themes -> /wp-content/themes.</p>\n<p>It's also possible to change the location of the wp-content/themes path completely using the <code>register_theme_directory(ABSPATH . 'app/themes')</code> function.</p>\n<p>If you're asking why they did this, it could be as simple as code aesthetics or as complex as a customized multisite installation with once centralized WordPress codebase.</p>\n"
},
{
"answer_id": 378880,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an <code>app</code> subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.</p>\n<p>It's also possible they use standard WordPress but have renamed <code>wp-content</code> using constants in <code>wp-config.php</code> , e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('WP_CONTENT_URL', 'https://example.com/app');\ndefine('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');\n</code></pre>\n<h2>Why Change the wp-content directory location?</h2>\n<p>If you want to use a git submodule to install WordPress, or a package manager such as <code>composer</code>, having WordPress in a subfolder on its own makes it easier to update and install.</p>\n<p>This necessitates moving <code>wp-content</code> out of that folder though to avoid nested folders. E.g <code>composer</code> updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.</p>\n<p>So instead, you might have a folder structure like this:</p>\n<pre><code> - wordpress ( sometimes wp )\n - wp-content\n - themes\n - plugins\n - etc..\n - wp-config.php\n - index.php\n</code></pre>\n<p>Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.</p>\n<p>As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">https://roots.io/bedrock/</a> and ask in their community</p>\n"
}
] | 2020/11/28 | [
"https://wordpress.stackexchange.com/questions/378977",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/169807/"
] | I need to deregister JS scripts everywhere except on one product page, so far this is my code:
```
add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
if ( !is_product('67688') ) {
wp_deregister_script( 'wc-lottery-jquery-plugin' );
wp_deregister_script( 'wc-lottery-countdown' );
wp_deregister_script( 'wc-lottery-countdown-language' );
wp_deregister_script( 'wc-lottery-public' );
}
}
```
Is this correct? Many thanks for your confirmation! | That site probably uses the Roots Bedrock framework, which moves the theme/plugin folders around into an `app` subfolder. This is mainly due to the preference of that framework though, rather than for any structural benefit.
It's also possible they use standard WordPress but have renamed `wp-content` using constants in `wp-config.php` , e.g.
```php
define('WP_CONTENT_URL', 'https://example.com/app');
define('WP_CONTENT_DIR', '/var/www/example.com/public_html/app/');
```
Why Change the wp-content directory location?
---------------------------------------------
If you want to use a git submodule to install WordPress, or a package manager such as `composer`, having WordPress in a subfolder on its own makes it easier to update and install.
This necessitates moving `wp-content` out of that folder though to avoid nested folders. E.g `composer` updates packages by deleting them and installing the new version, which would destroy all uploaded files, plugins, and themes.
So instead, you might have a folder structure like this:
```
- wordpress ( sometimes wp )
- wp-content
- themes
- plugins
- etc..
- wp-config.php
- index.php
```
Such a setup requires more steps to set up than a normal WordPress install however, and isn't well suited for most use cases and hosts. If you're using the auto-updater to keep WordPress up to date and don't use a site-wide version control, or use WP CLI to update WordPress, then you won't see many benefits by moving to this setup.
As for why Bedrock does it that way, the answer is simple, the maintainers prefer those folder names and organisation. Other than that Bedrock provides a local environment, but not much else. It's a boilerplate for setting up WordPress. For more info or if you have questions about Bedrock, you should visit <https://roots.io/bedrock/> and ask in their community |
378,988 | <p>I try to list pages of custom post type in archive.php, and I get this error message:</p>
<p>Invalid argument supplied for foreach()</p>
<pre><code>$post_type = get_post_type( get_the_ID() );
$pages = get_pages(array( 'post_type' => $post_type ) );
foreach ($pages as $page ) {
echo '<div class = "prop-sidebar-section">';
echo $page->post_title;
echo '</div>';
}
</code></pre>
<p>the weird thing is, that with <code>get_pages(array( 'post_type' => 'page');</code> is working, and if I use <code> get_pages(array( 'post_type' => 'post') );</code> is not.</p>
| [
{
"answer_id": 378992,
"author": "user3575665",
"author_id": 198226,
"author_profile": "https://wordpress.stackexchange.com/users/198226",
"pm_score": 0,
"selected": false,
"text": "<p>I am assuming your code is not within a wordpress loop,\nsomething like <code>while(have_posts()): the_post();</code>\nwhich means get_the_ID will return null,\ntry var_dump(get_the_ID); if it is null thats why your code is not working.</p>\n<p>and to get your post type you can use this:</p>\n<pre><code>var_dump($wp_query->query,get_queried_object()); die;\n</code></pre>\n<p><code>$wp_query->query</code> will have post_type component for custom post types. That will not be there for post post types. get_queried_object will return quite a bit of data for custom post types but null for post post type.</p>\n"
},
{
"answer_id": 378994,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\"><code>get_pages()</code></a> is intended only for <em>hierarchical</em> post types like <code>page</code>. For non-hierarchical post types like <code>post</code>, <code>get_pages()</code> will return a <code>false</code>, hence that explains why <code>get_pages( array( 'post_type' => 'post' ) )</code> "doesn't work", i.e. the returned value is not an array, so it can't be used with <code>foreach</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Good: 'page' is a hierarchical post type.\n$pages = get_pages( array( 'post_type' => 'page' ) );\n// Output: $pages is an array. Can do foreach ( $pages ... )\n\n// Not good: 'post' is a non-hierarchical post type.\n$posts = get_pages( array( 'post_type' => 'post' ) );\n// Output: $posts is a FALSE. Can't do foreach ( $posts ... )\n// because foreach ( false ... ) is invalid.\n</code></pre>\n<p>So for non-hierarchical post types, you would use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> or make a new instance of <code>WP_Query</code> (i.e. <code>new WP_Query()</code>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$posts = get_posts( array( 'post_type' => 'post' ) );\n\n// or..\n$query = new WP_Query( array( 'post_type' => 'post' ) );\n$posts = $query->posts;\n</code></pre>\n"
},
{
"answer_id": 378995,
"author": "tiago calado",
"author_id": 198152,
"author_profile": "https://wordpress.stackexchange.com/users/198152",
"pm_score": 0,
"selected": false,
"text": "<p>Run this code and will return all you got, then you can check if there your $post_type is returning 'page' or 'your_custom_post_type', and also check all available with the function get_pages();</p>\n<pre><code>$post_type = get_post_type( get_the_ID() );\necho '<pre>';\nprint_r($post_type);\necho '<br> ####################################### <br>';\n$pages = get_pages(array( 'sort_order' => 'ASC',\n 'sort_column' => 'post_title',\n 'hierarchical' => 1,) );\necho '<pre>';\nprint_r($pages);\n</code></pre>\n<p>In my case I only have $post_type returning 'page' and $pages have a lot of info but all post_types are 'page'. Hope that can help some how!..</p>\n<p>And a few minutes later after reading Sally CJ answer, I had use the get_posts instead and works like a charm.</p>\n<pre><code>$post_type = get_post_type( get_the_ID() );\n$pages = get_posts( array( 'post_type' => $post_type ) );\n foreach ($pages as $page ) {\n echo '<div class = "prop-sidebar-section">';\n echo $page->post_title;\n echo '</div>';\n }\n</code></pre>\n"
}
] | 2020/11/28 | [
"https://wordpress.stackexchange.com/questions/378988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163786/"
] | I try to list pages of custom post type in archive.php, and I get this error message:
Invalid argument supplied for foreach()
```
$post_type = get_post_type( get_the_ID() );
$pages = get_pages(array( 'post_type' => $post_type ) );
foreach ($pages as $page ) {
echo '<div class = "prop-sidebar-section">';
echo $page->post_title;
echo '</div>';
}
```
the weird thing is, that with `get_pages(array( 'post_type' => 'page');` is working, and if I use `get_pages(array( 'post_type' => 'post') );` is not. | [`get_pages()`](https://developer.wordpress.org/reference/functions/get_pages/) is intended only for *hierarchical* post types like `page`. For non-hierarchical post types like `post`, `get_pages()` will return a `false`, hence that explains why `get_pages( array( 'post_type' => 'post' ) )` "doesn't work", i.e. the returned value is not an array, so it can't be used with `foreach`:
```php
// Good: 'page' is a hierarchical post type.
$pages = get_pages( array( 'post_type' => 'page' ) );
// Output: $pages is an array. Can do foreach ( $pages ... )
// Not good: 'post' is a non-hierarchical post type.
$posts = get_pages( array( 'post_type' => 'post' ) );
// Output: $posts is a FALSE. Can't do foreach ( $posts ... )
// because foreach ( false ... ) is invalid.
```
So for non-hierarchical post types, you would use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) or make a new instance of `WP_Query` (i.e. `new WP_Query()`):
```php
$posts = get_posts( array( 'post_type' => 'post' ) );
// or..
$query = new WP_Query( array( 'post_type' => 'post' ) );
$posts = $query->posts;
``` |
379,014 | <p>I used wordfence plugin to clean unwanted files from my site. Post this, my posts page is broken. If i try to load any of my posts page, page will load but without header, footer, css. Homepage looks fine. Posts page works normal if i'm logged in.
here's one of my post url: <a href="https://m.androidestate.com/xiaomi-redmi-k20-pro/" rel="nofollow noreferrer">https://m.androidestate.com/xiaomi-redmi-k20-pro/</a>
Please let me know what went wrong. BTW i'm newbie :(
Update: Wierdly, some pages are loading as expected. <a href="https://m.androidestate.com/asus-rog-phone-ii/" rel="nofollow noreferrer">https://m.androidestate.com/asus-rog-phone-ii/</a></p>
| [
{
"answer_id": 378992,
"author": "user3575665",
"author_id": 198226,
"author_profile": "https://wordpress.stackexchange.com/users/198226",
"pm_score": 0,
"selected": false,
"text": "<p>I am assuming your code is not within a wordpress loop,\nsomething like <code>while(have_posts()): the_post();</code>\nwhich means get_the_ID will return null,\ntry var_dump(get_the_ID); if it is null thats why your code is not working.</p>\n<p>and to get your post type you can use this:</p>\n<pre><code>var_dump($wp_query->query,get_queried_object()); die;\n</code></pre>\n<p><code>$wp_query->query</code> will have post_type component for custom post types. That will not be there for post post types. get_queried_object will return quite a bit of data for custom post types but null for post post type.</p>\n"
},
{
"answer_id": 378994,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\"><code>get_pages()</code></a> is intended only for <em>hierarchical</em> post types like <code>page</code>. For non-hierarchical post types like <code>post</code>, <code>get_pages()</code> will return a <code>false</code>, hence that explains why <code>get_pages( array( 'post_type' => 'post' ) )</code> "doesn't work", i.e. the returned value is not an array, so it can't be used with <code>foreach</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Good: 'page' is a hierarchical post type.\n$pages = get_pages( array( 'post_type' => 'page' ) );\n// Output: $pages is an array. Can do foreach ( $pages ... )\n\n// Not good: 'post' is a non-hierarchical post type.\n$posts = get_pages( array( 'post_type' => 'post' ) );\n// Output: $posts is a FALSE. Can't do foreach ( $posts ... )\n// because foreach ( false ... ) is invalid.\n</code></pre>\n<p>So for non-hierarchical post types, you would use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> or make a new instance of <code>WP_Query</code> (i.e. <code>new WP_Query()</code>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$posts = get_posts( array( 'post_type' => 'post' ) );\n\n// or..\n$query = new WP_Query( array( 'post_type' => 'post' ) );\n$posts = $query->posts;\n</code></pre>\n"
},
{
"answer_id": 378995,
"author": "tiago calado",
"author_id": 198152,
"author_profile": "https://wordpress.stackexchange.com/users/198152",
"pm_score": 0,
"selected": false,
"text": "<p>Run this code and will return all you got, then you can check if there your $post_type is returning 'page' or 'your_custom_post_type', and also check all available with the function get_pages();</p>\n<pre><code>$post_type = get_post_type( get_the_ID() );\necho '<pre>';\nprint_r($post_type);\necho '<br> ####################################### <br>';\n$pages = get_pages(array( 'sort_order' => 'ASC',\n 'sort_column' => 'post_title',\n 'hierarchical' => 1,) );\necho '<pre>';\nprint_r($pages);\n</code></pre>\n<p>In my case I only have $post_type returning 'page' and $pages have a lot of info but all post_types are 'page'. Hope that can help some how!..</p>\n<p>And a few minutes later after reading Sally CJ answer, I had use the get_posts instead and works like a charm.</p>\n<pre><code>$post_type = get_post_type( get_the_ID() );\n$pages = get_posts( array( 'post_type' => $post_type ) );\n foreach ($pages as $page ) {\n echo '<div class = "prop-sidebar-section">';\n echo $page->post_title;\n echo '</div>';\n }\n</code></pre>\n"
}
] | 2020/11/29 | [
"https://wordpress.stackexchange.com/questions/379014",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198237/"
] | I used wordfence plugin to clean unwanted files from my site. Post this, my posts page is broken. If i try to load any of my posts page, page will load but without header, footer, css. Homepage looks fine. Posts page works normal if i'm logged in.
here's one of my post url: <https://m.androidestate.com/xiaomi-redmi-k20-pro/>
Please let me know what went wrong. BTW i'm newbie :(
Update: Wierdly, some pages are loading as expected. <https://m.androidestate.com/asus-rog-phone-ii/> | [`get_pages()`](https://developer.wordpress.org/reference/functions/get_pages/) is intended only for *hierarchical* post types like `page`. For non-hierarchical post types like `post`, `get_pages()` will return a `false`, hence that explains why `get_pages( array( 'post_type' => 'post' ) )` "doesn't work", i.e. the returned value is not an array, so it can't be used with `foreach`:
```php
// Good: 'page' is a hierarchical post type.
$pages = get_pages( array( 'post_type' => 'page' ) );
// Output: $pages is an array. Can do foreach ( $pages ... )
// Not good: 'post' is a non-hierarchical post type.
$posts = get_pages( array( 'post_type' => 'post' ) );
// Output: $posts is a FALSE. Can't do foreach ( $posts ... )
// because foreach ( false ... ) is invalid.
```
So for non-hierarchical post types, you would use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) or make a new instance of `WP_Query` (i.e. `new WP_Query()`):
```php
$posts = get_posts( array( 'post_type' => 'post' ) );
// or..
$query = new WP_Query( array( 'post_type' => 'post' ) );
$posts = $query->posts;
``` |
379,023 | <p>I'm having problems with my code. I'm trying to remove a category from a post that's using that category and then adding that same category when saving a post.</p>
<p>For example, if I have a post that's using "First post", when saving any post that is using that category gets removed and the new post that's being saved is added to the category "First post".</p>
<p>The code I'm using adds the category when saving a post but the previous post that's using that category doesn't get removed.</p>
<p>Here's my code:</p>
<pre><code>function save_category($post_ID){
// get all posts using 'First post' category
$categories = wp_get_object_terms( $post_ID, 'First post' );
// query to get posts using 'First post' category
if ($categories) {
foreach ($categories as $key => $category)
// if post is using 'First post' category then remove the category
if ($category->name == "First post") {
wp_remove_object_terms( $post_ID, 'First post', 'category' );
}
return;
}
// Add 'First post' to post when saving
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) );
}
add_action('save_post', 'save_category');
</code></pre>
| [
{
"answer_id": 379024,
"author": "hrsetyono",
"author_id": 33361,
"author_profile": "https://wordpress.stackexchange.com/users/33361",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see you querying for the posts that are using that category,</p>\n<p>Use <code>get_posts</code> like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$first_posts = get_posts([\n 'category_name' => 'first-post', // your category slug is\n]);\n\nforeach( $first_posts as $p ) {\n wp_remove_object_terms( $p->ID, 'first-post' );\n}\n</code></pre>\n"
},
{
"answer_id": 379031,
"author": "tiago calado",
"author_id": 198152,
"author_profile": "https://wordpress.stackexchange.com/users/198152",
"pm_score": 3,
"selected": true,
"text": "<p>Your foreach doesnt have brackets or semicolons, probably thatś why.\nand also not very well idented.\nHere it is the code properly idented, just one maybe, the foreach closing brackets probably must be after the return like in the code bellow, or maybe right before. if this code doesnt work cut and paste "return;" to right after the "endforeach;".</p>\n<pre><code>function save_category($post_ID){ // get all posts using 'First post' category\n $categories = wp_get_object_terms( $post_ID, 'First post' );\n if ($categories) { // query to get posts using 'First post' category\n foreach ($categories as $key => $category) :\n if ($category->name == "First post") { // if post is using 'First post' category then remove the category\n wp_remove_object_terms( $post_ID, 'First post', 'category' );\n }\n return;\n endforeach;\n }\n wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); // Add 'First post' to post when saving\n}\nadd_action('save_post', 'save_category');\n\n</code></pre>\n"
}
] | 2020/11/29 | [
"https://wordpress.stackexchange.com/questions/379023",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181902/"
] | I'm having problems with my code. I'm trying to remove a category from a post that's using that category and then adding that same category when saving a post.
For example, if I have a post that's using "First post", when saving any post that is using that category gets removed and the new post that's being saved is added to the category "First post".
The code I'm using adds the category when saving a post but the previous post that's using that category doesn't get removed.
Here's my code:
```
function save_category($post_ID){
// get all posts using 'First post' category
$categories = wp_get_object_terms( $post_ID, 'First post' );
// query to get posts using 'First post' category
if ($categories) {
foreach ($categories as $key => $category)
// if post is using 'First post' category then remove the category
if ($category->name == "First post") {
wp_remove_object_terms( $post_ID, 'First post', 'category' );
}
return;
}
// Add 'First post' to post when saving
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) );
}
add_action('save_post', 'save_category');
``` | Your foreach doesnt have brackets or semicolons, probably thatś why.
and also not very well idented.
Here it is the code properly idented, just one maybe, the foreach closing brackets probably must be after the return like in the code bellow, or maybe right before. if this code doesnt work cut and paste "return;" to right after the "endforeach;".
```
function save_category($post_ID){ // get all posts using 'First post' category
$categories = wp_get_object_terms( $post_ID, 'First post' );
if ($categories) { // query to get posts using 'First post' category
foreach ($categories as $key => $category) :
if ($category->name == "First post") { // if post is using 'First post' category then remove the category
wp_remove_object_terms( $post_ID, 'First post', 'category' );
}
return;
endforeach;
}
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); // Add 'First post' to post when saving
}
add_action('save_post', 'save_category');
``` |
379,041 | <p>5 WordPress sites (that is all of them) on our server (Apache, Ubuntu) were infected by some malicious code injecting javascript. I have deleted all the wp databases that were full of the injections and reuploaded them back from a backup. Almost all is well now, but one of the WordPress sites from one domain now redirects automatically to another WordPress on a different domain, which shouldn't be happening. Both domains and WordPress installations are hosted on the same server and worked just fine before. The database seems to be ok, .htaccess seems to be unchanged, I certainly haven't changed any domain configuration files on the server, plus I checked them and they seem unchanged as well. I have no idea where the problem is. Could you, please, point me to a probable cause? I have very limited experience with sorting out this kind of troubles. Thank you.</p>
| [
{
"answer_id": 379024,
"author": "hrsetyono",
"author_id": 33361,
"author_profile": "https://wordpress.stackexchange.com/users/33361",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see you querying for the posts that are using that category,</p>\n<p>Use <code>get_posts</code> like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$first_posts = get_posts([\n 'category_name' => 'first-post', // your category slug is\n]);\n\nforeach( $first_posts as $p ) {\n wp_remove_object_terms( $p->ID, 'first-post' );\n}\n</code></pre>\n"
},
{
"answer_id": 379031,
"author": "tiago calado",
"author_id": 198152,
"author_profile": "https://wordpress.stackexchange.com/users/198152",
"pm_score": 3,
"selected": true,
"text": "<p>Your foreach doesnt have brackets or semicolons, probably thatś why.\nand also not very well idented.\nHere it is the code properly idented, just one maybe, the foreach closing brackets probably must be after the return like in the code bellow, or maybe right before. if this code doesnt work cut and paste "return;" to right after the "endforeach;".</p>\n<pre><code>function save_category($post_ID){ // get all posts using 'First post' category\n $categories = wp_get_object_terms( $post_ID, 'First post' );\n if ($categories) { // query to get posts using 'First post' category\n foreach ($categories as $key => $category) :\n if ($category->name == "First post") { // if post is using 'First post' category then remove the category\n wp_remove_object_terms( $post_ID, 'First post', 'category' );\n }\n return;\n endforeach;\n }\n wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); // Add 'First post' to post when saving\n}\nadd_action('save_post', 'save_category');\n\n</code></pre>\n"
}
] | 2020/11/29 | [
"https://wordpress.stackexchange.com/questions/379041",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150082/"
] | 5 WordPress sites (that is all of them) on our server (Apache, Ubuntu) were infected by some malicious code injecting javascript. I have deleted all the wp databases that were full of the injections and reuploaded them back from a backup. Almost all is well now, but one of the WordPress sites from one domain now redirects automatically to another WordPress on a different domain, which shouldn't be happening. Both domains and WordPress installations are hosted on the same server and worked just fine before. The database seems to be ok, .htaccess seems to be unchanged, I certainly haven't changed any domain configuration files on the server, plus I checked them and they seem unchanged as well. I have no idea where the problem is. Could you, please, point me to a probable cause? I have very limited experience with sorting out this kind of troubles. Thank you. | Your foreach doesnt have brackets or semicolons, probably thatś why.
and also not very well idented.
Here it is the code properly idented, just one maybe, the foreach closing brackets probably must be after the return like in the code bellow, or maybe right before. if this code doesnt work cut and paste "return;" to right after the "endforeach;".
```
function save_category($post_ID){ // get all posts using 'First post' category
$categories = wp_get_object_terms( $post_ID, 'First post' );
if ($categories) { // query to get posts using 'First post' category
foreach ($categories as $key => $category) :
if ($category->name == "First post") { // if post is using 'First post' category then remove the category
wp_remove_object_terms( $post_ID, 'First post', 'category' );
}
return;
endforeach;
}
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); // Add 'First post' to post when saving
}
add_action('save_post', 'save_category');
``` |
379,092 | <p>Is it safe to remove</p>
<pre><code>get_footer();
</code></pre>
<p>from the index.php ?</p>
<p>I don't need any footer.</p>
| [
{
"answer_id": 379094,
"author": "user3288647",
"author_id": 198299,
"author_profile": "https://wordpress.stackexchange.com/users/198299",
"pm_score": 3,
"selected": true,
"text": "<p>Its not safe and not recommended. Thats action that read all Javascripts, CSS from other plugins or theme.</p>\n<p>Hide your footer with css or theme option.</p>\n<pre class=\"lang-css prettyprint-override\"><code>#footer,footer{display:none!important}\n</code></pre>\n"
},
{
"answer_id": 379149,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it should be safe if you replace it with <a href=\"https://developer.wordpress.org/reference/functions/wp_footer/\" rel=\"nofollow noreferrer\"><code>wp_footer()</code></a>, which is the function that includes enqueued scripts in the page and other footer actions in the page. (and maybe optionally <code>do_action( 'get_footer', null, array() );</code> first, in case you have anything that hooks that.)</p>\n<p>But IMO the best / clearest thing to do would be to override footer.php in a child theme with a version that was just</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php wp_footer();\n</code></pre>\n<p>and leave index.php calling get_footer() as usual.</p>\n<p>However there's still a risk that any of the theme scripts you have loaded assume the footer element always exists and try to access it. So please check you don't have any script errors afterwards. If you do, you'd either have to fix the script or leave the footer on the page and use the display:none from the other answer.</p>\n"
}
] | 2020/11/30 | [
"https://wordpress.stackexchange.com/questions/379092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198297/"
] | Is it safe to remove
```
get_footer();
```
from the index.php ?
I don't need any footer. | Its not safe and not recommended. Thats action that read all Javascripts, CSS from other plugins or theme.
Hide your footer with css or theme option.
```css
#footer,footer{display:none!important}
``` |
379,098 | <p>I'm having font problems, or maybe character encoding on wordpress.</p>
<p>I am building a Thai website, most of the articles are in the correct language and there is no problem.</p>
<p>But there are a number of articles posted when posting errors in the article letters.</p>
<p>Such as:</p>
<p><a href="https://prnt.sc/vswh8j" rel="nofollow noreferrer">https://prnt.sc/vswh8j</a> or <a href="https://prnt.sc/vswi15" rel="nofollow noreferrer">https://prnt.sc/vswi15</a></p>
<p><a href="https://i.stack.imgur.com/JP7Yl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JP7Yl.png" alt="enter image description here" /></a></p>
<p>As in the picture I have given, some of the first characters can be Thai, but the following characters are like: "ี่๠€ ภ£ ๠‡ วà¸" and I don't translate get it in any language.</p>
<p>I don't think my source code supports Thai or something like that. I have tried researching on this problem a lot and tried many ways but to no avail.</p>
<p>Hope you can guide me to fix it. Thank you very much</p>
| [
{
"answer_id": 379094,
"author": "user3288647",
"author_id": 198299,
"author_profile": "https://wordpress.stackexchange.com/users/198299",
"pm_score": 3,
"selected": true,
"text": "<p>Its not safe and not recommended. Thats action that read all Javascripts, CSS from other plugins or theme.</p>\n<p>Hide your footer with css or theme option.</p>\n<pre class=\"lang-css prettyprint-override\"><code>#footer,footer{display:none!important}\n</code></pre>\n"
},
{
"answer_id": 379149,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it should be safe if you replace it with <a href=\"https://developer.wordpress.org/reference/functions/wp_footer/\" rel=\"nofollow noreferrer\"><code>wp_footer()</code></a>, which is the function that includes enqueued scripts in the page and other footer actions in the page. (and maybe optionally <code>do_action( 'get_footer', null, array() );</code> first, in case you have anything that hooks that.)</p>\n<p>But IMO the best / clearest thing to do would be to override footer.php in a child theme with a version that was just</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php wp_footer();\n</code></pre>\n<p>and leave index.php calling get_footer() as usual.</p>\n<p>However there's still a risk that any of the theme scripts you have loaded assume the footer element always exists and try to access it. So please check you don't have any script errors afterwards. If you do, you'd either have to fix the script or leave the footer on the page and use the display:none from the other answer.</p>\n"
}
] | 2020/11/30 | [
"https://wordpress.stackexchange.com/questions/379098",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198301/"
] | I'm having font problems, or maybe character encoding on wordpress.
I am building a Thai website, most of the articles are in the correct language and there is no problem.
But there are a number of articles posted when posting errors in the article letters.
Such as:
<https://prnt.sc/vswh8j> or <https://prnt.sc/vswi15>
[](https://i.stack.imgur.com/JP7Yl.png)
As in the picture I have given, some of the first characters can be Thai, but the following characters are like: "ี่๠€ ภ£ ๠‡ วà¸" and I don't translate get it in any language.
I don't think my source code supports Thai or something like that. I have tried researching on this problem a lot and tried many ways but to no avail.
Hope you can guide me to fix it. Thank you very much | Its not safe and not recommended. Thats action that read all Javascripts, CSS from other plugins or theme.
Hide your footer with css or theme option.
```css
#footer,footer{display:none!important}
``` |
379,122 | <p><strong>Hello everybody</strong>, I need help with my custom wordpress pagination.</p>
<p>I'm looking to get this :</p>
<p><a href="https://i.stack.imgur.com/UUM6d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UUM6d.png" alt="enter image description here" /></a></p>
<p>This is what I did :</p>
<p>in the functions.php, I've add this code :</p>
<pre><code>function wp_custom_pagination($args = [], $class = 'pagination') {
if ($GLOBALS['wp_query']->max_num_pages <= 1) return;
$args = wp_parse_args( $args, [
'mid_size' => 2,
'prev_next' => false,
'prev_text' => __('Older posts', 'textdomain'),
'next_text' => __('Newer posts', 'textdomain'),
'screen_reader_text' => __('Posts navigation', 'textdomain'),
]);
$links = paginate_links($args);
$next_link = get_previous_posts_link($args['next_text']);
$prev_link = get_next_posts_link($args['prev_text']);
$template = apply_filters( 'navigation_markup_template', '
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark">%3$s</a>
</div>
<div class="col-auto">
<nav class="navigation %1$s" role="navigation">
<h2 class="screen-reader-text">%2$s</h2>
<ul class="nav-links pagination mb-0 text-dark">
<li class="page-item">%4$s</li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark">%5$s</a>
</div>', $args, $class);
echo sprintf($template, $class, $args['screen_reader_text'], $prev_link, $links, $next_link);}
</code></pre>
<p>After, I've add this code in my home.php</p>
<pre><code><?php wp_custom_pagination(); ?>
</code></pre>
<p>But, the result is really not what I want!</p>
<p>Here is the html structure code that I would need for this wp_custom_pagination :</p>
<pre><code> <div class="row justify-content-between align-items-center">
<div class="col-auto">
<a href="#" class="btn btn-outline-white text-dark">Previous</a>
</div>
<div class="col-auto">
<nav>
<ul class="pagination mb-0 text-dark">
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="#" class="btn btn-outline-white text-dark">Next</a>
</div>
</div>
</code></pre>
<p>If anyone could help me and tell me and show me my mistakes and how to get what I want please.</p>
<p>Thanks a lot</p>
<hr />
<p>At this time, this is the result that I obtain :</p>
<p><a href="https://i.stack.imgur.com/X1z1Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X1z1Y.png" alt="enter image description here" /></a></p>
<p>This is the generated code of my custom pagination page :</p>
<pre><code><div class="row justify-content-between align-items-center">
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark"></a>
<a href="http://192.168.1.87/wordpress/blog/page/2">Older posts</a>
</div>
<div class="col-auto">
<nav class="navigation pagination" role="navigation">
<h2 class="screen-reader-text">Posts navigation</h2>
<ul class="nav-links pagination mb-0 text-dark">
<li class="page-item">
<span aria-current="page" class="page-numbers current">1</span>
<a class="page-numbers" href="http://192.168.1.87/wordpress/blog/page/2">2</a>
</li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark"></a>
</div>
</div>
</code></pre>
<p>So, if you give a look at the result :</p>
<p>1 - You will see that the <em>first link (Older post = %3$s)</em> need to be enclosed with the good css class!</p>
<p>2 - And you'll see that the <em>"1, 2, 3" links</em> need to be inside each one "li" not inside one "li"</p>
| [
{
"answer_id": 379984,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of <code>the_posts_pagination( wp_custom_pagination () );</code>, just use this function <code>paginate_links</code> and add args as per your requirements.</p>\n<p>Sample:</p>\n<pre><code>$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $the_query->max_num_pages,\n 'prev_text' => __( 'Previous' ),\n 'next_text' => __( 'Next' ),\n) );\n</code></pre>\n<p>Ref: <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/paginate_links/</a></p>\n"
},
{
"answer_id": 380642,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 3,
"selected": true,
"text": "<p>Making your Custom Pagination design In Demo According Your Need .</p>\n<p>below function Replace Your Function:</p>\n<pre><code>function wp_custom_pagination($args = [], $class = 'pagination') {\n\nif ($GLOBALS['wp_query']->max_num_pages <= 1) return;\n\n$args = wp_parse_args( $args, [\n 'mid_size' => 2,\n 'prev_next' => false,\n 'prev_text' => __('Previous', 'textdomain'),\n 'next_text' => __('Next', 'textdomain'),\n 'screen_reader_text' => __('Posts navigation', 'textdomain'),\n]);\n\n$links = paginate_links($args);\n$next_link = get_previous_posts_link($args['next_text']);\n$prev_link = get_next_posts_link($args['prev_text']);\n$check_prev = (!empty($prev_link))?$prev_link:'Previous';\n$check_next = (!empty($next_link))?$next_link:'Next';\n$template = apply_filters( 'navigation_markup_template', '\n<div class="container"><div class= "row"><div style="display: flex;justify-content: space-around; align-items: center;" class="paginatin d-flex justify-content-between align-items-center"><div class="col-auto">\n <button type="button" class="btn btn-outline-info" >%3$s</button>\n</div>\n<div class="col-auto">\n <nav class="navigation %1$s" role="navigation">\n <h2 class="screen-reader-text">%2$s</h2>\n <ul class="pagination mb-0 text-dark">\n <li class="page-item">%4$s</li>\n </ul>\n </nav>\n</div>\n<div class="col-auto">\n <button type="button" class="btn btn-outline-info">%5$s</button>\n</div></div></div><div>', $args, $class);\n\necho sprintf($template, $class, $args['screen_reader_text'], $check_next, $links, $check_prev);\n\n}\n</code></pre>\n<p>Add Some Css In Your Header :</p>\n<pre><code>function add_css_pagination(){\n?> \n <style type="text/css">\n span.page-numbers.current {\n background: #a8307c;\n color: white;\n }\n button.btn a {\n color: #f4f4f4;\n text-decoration: none;\n }\n button.btn.btn-outline-info a {\n color: darkslategrey;\n font-weight: 600;\n }\n button.btn.btn-outline-info {\n background: unset;\n border: 1px solid turquoise;\n color: darkslategrey;\n font-weight: 600;\n }\n </style>\n\n <?php\n }\n add_action('wp_head','add_css_pagination');\n</code></pre>\n<p>Screenshot:<a href=\"https://i.stack.imgur.com/JaCut.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JaCut.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2020/12/01 | [
"https://wordpress.stackexchange.com/questions/379122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198331/"
] | **Hello everybody**, I need help with my custom wordpress pagination.
I'm looking to get this :
[](https://i.stack.imgur.com/UUM6d.png)
This is what I did :
in the functions.php, I've add this code :
```
function wp_custom_pagination($args = [], $class = 'pagination') {
if ($GLOBALS['wp_query']->max_num_pages <= 1) return;
$args = wp_parse_args( $args, [
'mid_size' => 2,
'prev_next' => false,
'prev_text' => __('Older posts', 'textdomain'),
'next_text' => __('Newer posts', 'textdomain'),
'screen_reader_text' => __('Posts navigation', 'textdomain'),
]);
$links = paginate_links($args);
$next_link = get_previous_posts_link($args['next_text']);
$prev_link = get_next_posts_link($args['prev_text']);
$template = apply_filters( 'navigation_markup_template', '
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark">%3$s</a>
</div>
<div class="col-auto">
<nav class="navigation %1$s" role="navigation">
<h2 class="screen-reader-text">%2$s</h2>
<ul class="nav-links pagination mb-0 text-dark">
<li class="page-item">%4$s</li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark">%5$s</a>
</div>', $args, $class);
echo sprintf($template, $class, $args['screen_reader_text'], $prev_link, $links, $next_link);}
```
After, I've add this code in my home.php
```
<?php wp_custom_pagination(); ?>
```
But, the result is really not what I want!
Here is the html structure code that I would need for this wp\_custom\_pagination :
```
<div class="row justify-content-between align-items-center">
<div class="col-auto">
<a href="#" class="btn btn-outline-white text-dark">Previous</a>
</div>
<div class="col-auto">
<nav>
<ul class="pagination mb-0 text-dark">
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="#" class="btn btn-outline-white text-dark">Next</a>
</div>
</div>
```
If anyone could help me and tell me and show me my mistakes and how to get what I want please.
Thanks a lot
---
At this time, this is the result that I obtain :
[](https://i.stack.imgur.com/X1z1Y.png)
This is the generated code of my custom pagination page :
```
<div class="row justify-content-between align-items-center">
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark"></a>
<a href="http://192.168.1.87/wordpress/blog/page/2">Older posts</a>
</div>
<div class="col-auto">
<nav class="navigation pagination" role="navigation">
<h2 class="screen-reader-text">Posts navigation</h2>
<ul class="nav-links pagination mb-0 text-dark">
<li class="page-item">
<span aria-current="page" class="page-numbers current">1</span>
<a class="page-numbers" href="http://192.168.1.87/wordpress/blog/page/2">2</a>
</li>
</ul>
</nav>
</div>
<div class="col-auto">
<a href="" class="btn btn-outline-white text-dark"></a>
</div>
</div>
```
So, if you give a look at the result :
1 - You will see that the *first link (Older post = %3$s)* need to be enclosed with the good css class!
2 - And you'll see that the *"1, 2, 3" links* need to be inside each one "li" not inside one "li" | Making your Custom Pagination design In Demo According Your Need .
below function Replace Your Function:
```
function wp_custom_pagination($args = [], $class = 'pagination') {
if ($GLOBALS['wp_query']->max_num_pages <= 1) return;
$args = wp_parse_args( $args, [
'mid_size' => 2,
'prev_next' => false,
'prev_text' => __('Previous', 'textdomain'),
'next_text' => __('Next', 'textdomain'),
'screen_reader_text' => __('Posts navigation', 'textdomain'),
]);
$links = paginate_links($args);
$next_link = get_previous_posts_link($args['next_text']);
$prev_link = get_next_posts_link($args['prev_text']);
$check_prev = (!empty($prev_link))?$prev_link:'Previous';
$check_next = (!empty($next_link))?$next_link:'Next';
$template = apply_filters( 'navigation_markup_template', '
<div class="container"><div class= "row"><div style="display: flex;justify-content: space-around; align-items: center;" class="paginatin d-flex justify-content-between align-items-center"><div class="col-auto">
<button type="button" class="btn btn-outline-info" >%3$s</button>
</div>
<div class="col-auto">
<nav class="navigation %1$s" role="navigation">
<h2 class="screen-reader-text">%2$s</h2>
<ul class="pagination mb-0 text-dark">
<li class="page-item">%4$s</li>
</ul>
</nav>
</div>
<div class="col-auto">
<button type="button" class="btn btn-outline-info">%5$s</button>
</div></div></div><div>', $args, $class);
echo sprintf($template, $class, $args['screen_reader_text'], $check_next, $links, $check_prev);
}
```
Add Some Css In Your Header :
```
function add_css_pagination(){
?>
<style type="text/css">
span.page-numbers.current {
background: #a8307c;
color: white;
}
button.btn a {
color: #f4f4f4;
text-decoration: none;
}
button.btn.btn-outline-info a {
color: darkslategrey;
font-weight: 600;
}
button.btn.btn-outline-info {
background: unset;
border: 1px solid turquoise;
color: darkslategrey;
font-weight: 600;
}
</style>
<?php
}
add_action('wp_head','add_css_pagination');
```
Screenshot:[](https://i.stack.imgur.com/JaCut.png) |
379,153 | <p>I have 2 pages:</p>
<ol>
<li><code>/contact</code></li>
<li><code>/contact-team</code></li>
</ol>
<p>The <code>/contact</code> page has a popup and on user selection, the page must reload but with the contents of <code>/contact-team</code>.</p>
<p>Is there a filter hook which can load a different post altogether after the URL has been generated?</p>
<p>I have tried the <code>pre_get_posts</code> to set the post ID but it gets redirected to that ID. I want the page loaded to be <code>/contact</code> but the content should be from <code>/contact-team</code>.
Any ideas?</p>
| [
{
"answer_id": 379292,
"author": "Awais",
"author_id": 141970,
"author_profile": "https://wordpress.stackexchange.com/users/141970",
"pm_score": 0,
"selected": false,
"text": "<p>You can try <code>the_content</code> filter something like below to load a content from a different post/page</p>\n<pre><code>function get_contact_team_page_content ( $content ) {\n\n // Condition based on user selection via popup e.g. $_GET or $_POST\n if ('condition') {\n $contact_team = get_post(14); // e.g. contact-team page ID\n $content = $contact_team->post_content;\n return $content;\n }\n\n return $content;\n}\n\nadd_filter( 'the_content', 'get_contact_team_page_content');\n</code></pre>\n"
},
{
"answer_id": 379295,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 0,
"selected": false,
"text": "<p>Using a cookie it would be:</p>\n<pre><code>function get_contact_team_page_content ( $content ) {\n if (isset($_COOKIE['alternative_content'])) {\n $contact_team = get_post( (int)$_COOKIE['alternative_content'] ); // e.g. contact-team page ID\n unset($_COOKIE['alternative_content']);\n return $contact_team->post_content;\n }\n return $content;\n}\n\nadd_filter( 'the_content', 'get_contact_team_page_content');\n</code></pre>\n<p>In this way ( adding the code above in functions.php of your theme or plugin) you can filter <code>the_content</code> based on the existence of a cookie</p>\n<p>in you page you attach a function to the click button that reloads the page:</p>\n<pre><code><!-- 158 is your contact-team page ID -->\n<button onClick="loadAlternateContent(158)">change</button>\n<script>\nfunction loadAlternateContent(post_id){\n var date = new Date();\n date.setTime( date.getTime() + (1*60*1000) ); //expiration in 1 minute\n var expires = "; expires=" + date.toGMTString();\n document.cookie = "alternative_content=" + post_id + expires +"; path=/";\n window.location.reload();\n}\n</script>\n</code></pre>\n<p>you see the content is the post_id 158 content but the url is the same.</p>\n<p>At this point, reloading the page manually, the first time will still show the alternative content since the cookie has been deleted by PHP but it's still living in the browser. To avoid this behaviour you should have a function that deletes the cookie on the 'alternative_content' page:</p>\n<pre><code><script>\n window.addEventListener("load", function(event) {\n document.cookie = 'alternative_content=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 379389,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if I understand well your question but,\nyou can get a post data inside another post this way:</p>\n<pre><code>$post = get_post( 123 ); // Where 123 is the ID\n$output = apply_filters( 'the_content', $post->post_content );\n</code></pre>\n<p>You can also use wp_query if you want more control.</p>\n"
},
{
"answer_id": 379577,
"author": "freejack",
"author_id": 124757,
"author_profile": "https://wordpress.stackexchange.com/users/124757",
"pm_score": 2,
"selected": true,
"text": "<p>You can use the <code>request</code> hook to change the loaded page for the same URL:</p>\n<pre><code>add_filter( 'request', function( $request ){\n //Replace this with custom logic to determine if the user should see the contact-team page\n $load_team_contact = true;\n\n if( $load_team_contact && isset( $request['pagename'] ) && 'contact' == $request['pagename'] ){\n $request['pagename'] = 'contact-team';\n }\n return $request;\n} );\n</code></pre>\n<p>You just need to determine if the user should see the contact team page which would vary depending on your setup.</p>\n"
}
] | 2020/12/01 | [
"https://wordpress.stackexchange.com/questions/379153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67538/"
] | I have 2 pages:
1. `/contact`
2. `/contact-team`
The `/contact` page has a popup and on user selection, the page must reload but with the contents of `/contact-team`.
Is there a filter hook which can load a different post altogether after the URL has been generated?
I have tried the `pre_get_posts` to set the post ID but it gets redirected to that ID. I want the page loaded to be `/contact` but the content should be from `/contact-team`.
Any ideas? | You can use the `request` hook to change the loaded page for the same URL:
```
add_filter( 'request', function( $request ){
//Replace this with custom logic to determine if the user should see the contact-team page
$load_team_contact = true;
if( $load_team_contact && isset( $request['pagename'] ) && 'contact' == $request['pagename'] ){
$request['pagename'] = 'contact-team';
}
return $request;
} );
```
You just need to determine if the user should see the contact team page which would vary depending on your setup. |
379,174 | <p>I'm curious that why the get_header() or get_footer() function does not show output if called twice in the same .php file??</p>
<p><a href="https://i.stack.imgur.com/BhaEb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BhaEb.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/sfk0b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sfk0b.png" alt="enter image description here" /></a></p>
<p>I tried to call the get_header() twice in my single.php file it runs fine but on the front end it shows output only once, what is the reason?</p>
| [
{
"answer_id": 379178,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": false,
"text": "<p>The actual templates are loaded with <a href=\"https://www.php.net/manual/en/function.require-once.php\" rel=\"nofollow noreferrer\"><code>require_once</code></a>, so PHP automatically ignores the second attempt to load them. (You will trigger the 'get_header' hook twice though.)</p>\n<p>Here's <a href=\"https://github.com/WordPress/WordPress/blob/5.5.3/wp-includes/general-template.php#L27\" rel=\"nofollow noreferrer\">the relevant code in get_header()</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $templates[] = 'header.php';\n\n if ( ! locate_template( $templates, true, true, $args ) ) {\n return false;\n }\n</code></pre>\n<p>The third parameter to <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\">locate_header()</a>, the second true, is the load-with-require-once flag. There's no filter we can use to change that behaviour here.</p>\n<p>Note that you could include two different header templates, e.g. if you created a copy of header.php as header-duplicate.php in your theme then</p>\n<pre><code>get_header();\nget_header('duplicate');\n</code></pre>\n<p>would include them both, as this wouldn't get blocked by require_once.</p>\n"
},
{
"answer_id": 379179,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 1,
"selected": false,
"text": "<p>The reason for this is simple:</p>\n<p><strong>It's not ment to be called twice!</strong></p>\n<p>The <em>get_header()</em> function loads all necessary scripts and styles for the page to be fully working. That also means all plugin files, and all Hooks or Filters that are ment to be loaded for the header.</p>\n<p>Though I have never tried this, I guess that WordPress is skipping all scripts, when it is being called a second time. You cannot include twice for instance.</p>\n<p>Same goes for the <em>get_footer()</em> function.</p>\n<p>Quote from <a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\">core docs</a>:</p>\n<p><em>Includes the header template for a theme or if a name is specified then a specialised header will be included.</em></p>\n<p><em>For the parameter, if the file is called "header-special.php" then specify "special".</em></p>\n<p>Meaning, that you may load a different part of your header, in case you need to.</p>\n<p>If you want to include some scripts, use <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">wp_enqueue_scripts</a>().\nIf you want to include some different template parts, use <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part</a>().</p>\n"
}
] | 2020/12/01 | [
"https://wordpress.stackexchange.com/questions/379174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198365/"
] | I'm curious that why the get\_header() or get\_footer() function does not show output if called twice in the same .php file??
[](https://i.stack.imgur.com/BhaEb.png)
[](https://i.stack.imgur.com/sfk0b.png)
I tried to call the get\_header() twice in my single.php file it runs fine but on the front end it shows output only once, what is the reason? | The actual templates are loaded with [`require_once`](https://www.php.net/manual/en/function.require-once.php), so PHP automatically ignores the second attempt to load them. (You will trigger the 'get\_header' hook twice though.)
Here's [the relevant code in get\_header()](https://github.com/WordPress/WordPress/blob/5.5.3/wp-includes/general-template.php#L27):
```php
$templates[] = 'header.php';
if ( ! locate_template( $templates, true, true, $args ) ) {
return false;
}
```
The third parameter to [locate\_header()](https://developer.wordpress.org/reference/functions/locate_template/), the second true, is the load-with-require-once flag. There's no filter we can use to change that behaviour here.
Note that you could include two different header templates, e.g. if you created a copy of header.php as header-duplicate.php in your theme then
```
get_header();
get_header('duplicate');
```
would include them both, as this wouldn't get blocked by require\_once. |
379,183 | <p>We have a simple plugin to display a tree menu, which includes the parent page, plus the parent page's children (so, the siblings of the current page).</p>
<p>We're using the following <code>get_pages</code> code:</p>
<pre><code>$pages = get_pages( [
'child_of' => $parent,
'sort_order' => 'ASC',
'sort_column' => 'menu_order',
]);
</code></pre>
<p>However, the pages are listed in ascending order of date created (oldest first).</p>
<p>How do we make the pages be listed in the page order in the right sidebar of the edit page screen?</p>
| [
{
"answer_id": 379184,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 0,
"selected": false,
"text": "<p>Both the <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\"><code>wp_list_pages()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\"><code>get_pages()</code></a> functions have a <code>sort_column</code> parameter where you can pass in <code>menu_order</code>. For example:</p>\n<pre><code>$output = wp_list_pages( [\n 'include' => $page_ids,\n 'title_li' => false,\n 'echo' => false,\n 'sort_column' => 'menu_order',\n] );\n</code></pre>\n<p>Menu Order will be the "Order" field seen in the <a href=\"https://make.wordpress.org/support/user-manual/content/pages/page-attributes/\" rel=\"nofollow noreferrer\">Page Attributes Metabox</a> or Page Attributes section of the Block Editor.</p>\n"
},
{
"answer_id": 379191,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p>When the <code>child_of</code> parameter is set, <code>get_pages()</code> will use <a href=\"https://developer.wordpress.org/reference/functions/get_page_children/\" rel=\"nofollow noreferrer\"><code>get_page_children()</code></a> to get the child pages, and unfortunately, the <code>sort_column</code> will no longer be used, hence the final list will not be sorted by the specified custom sort column, so you'll need to use your own code for getting the list with the expected sort column (and order).</p>\n<p>Here's an example which uses a custom function that's called recursively (until all child pages are retrieved) and then <a href=\"https://developer.wordpress.org/reference/functions/walk_page_tree/\" rel=\"nofollow noreferrer\"><code>walk_page_tree()</code></a> is used (instead of <code>wp_list_pages()</code> which has the same issue as <code>get_pages()</code>) to output the pages in a list (<code>li</code>) layout:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// In the theme functions file:\nfunction my_get_pages( $parent, $orderby = 'menu_order', $order = 'ASC' ) {\n $pages = get_pages( array(\n 'parent' => $parent,\n 'sort_column' => $orderby,\n 'sort_order' => $order,\n ) );\n\n $children = array();\n foreach ( $pages as $page ) {\n $children[] = $page;\n\n // Retrieve grandchildren.\n $children2 = my_get_pages( $page->ID, $orderby, $order );\n if ( ! empty( $children2 ) ) {\n $children = array_merge( $children, $children2 );\n }\n }\n\n return $children;\n}\n\n// In your template:\n$parent = 123; // parent post/Page ID\n\n$pages = my_get_pages( $parent );\n\necho '<ul>' .\n walk_page_tree( $pages, 0, get_queried_object_id(), array() ) .\n'</ul>';\n</code></pre>\n<p>Here's another example, similar to the above, but this one doesn't use <code>walk_page_tree()</code> — and you've got full control over the HTML:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// In the theme functions file:\nfunction my_wp_list_pages( $parent, $orderby = 'menu_order', $order = 'ASC' ) {\n $pages = get_pages( array(\n 'parent' => $parent,\n 'sort_column' => $orderby,\n 'sort_order' => $order,\n ) );\n\n if ( empty( $pages ) ) {\n return;\n }\n\n // Just change the HTML markup based on your liking..\n echo '<ul>';\n\n foreach ( $pages as $page ) {\n printf( '<li><a href="%s">%s</a></li>',\n esc_url( get_permalink( $page ) ),\n get_the_title( $page ) );\n\n // Display grandchildren.\n my_wp_list_pages( $page->ID, $orderby, $order );\n }\n\n echo '</ul>';\n}\n\n// In your template:\n$parent = 123; // parent post/Page ID\n\nmy_wp_list_pages( $parent );\n</code></pre>\n"
}
] | 2020/12/02 | [
"https://wordpress.stackexchange.com/questions/379183",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | We have a simple plugin to display a tree menu, which includes the parent page, plus the parent page's children (so, the siblings of the current page).
We're using the following `get_pages` code:
```
$pages = get_pages( [
'child_of' => $parent,
'sort_order' => 'ASC',
'sort_column' => 'menu_order',
]);
```
However, the pages are listed in ascending order of date created (oldest first).
How do we make the pages be listed in the page order in the right sidebar of the edit page screen? | When the `child_of` parameter is set, `get_pages()` will use [`get_page_children()`](https://developer.wordpress.org/reference/functions/get_page_children/) to get the child pages, and unfortunately, the `sort_column` will no longer be used, hence the final list will not be sorted by the specified custom sort column, so you'll need to use your own code for getting the list with the expected sort column (and order).
Here's an example which uses a custom function that's called recursively (until all child pages are retrieved) and then [`walk_page_tree()`](https://developer.wordpress.org/reference/functions/walk_page_tree/) is used (instead of `wp_list_pages()` which has the same issue as `get_pages()`) to output the pages in a list (`li`) layout:
```php
// In the theme functions file:
function my_get_pages( $parent, $orderby = 'menu_order', $order = 'ASC' ) {
$pages = get_pages( array(
'parent' => $parent,
'sort_column' => $orderby,
'sort_order' => $order,
) );
$children = array();
foreach ( $pages as $page ) {
$children[] = $page;
// Retrieve grandchildren.
$children2 = my_get_pages( $page->ID, $orderby, $order );
if ( ! empty( $children2 ) ) {
$children = array_merge( $children, $children2 );
}
}
return $children;
}
// In your template:
$parent = 123; // parent post/Page ID
$pages = my_get_pages( $parent );
echo '<ul>' .
walk_page_tree( $pages, 0, get_queried_object_id(), array() ) .
'</ul>';
```
Here's another example, similar to the above, but this one doesn't use `walk_page_tree()` — and you've got full control over the HTML:
```php
// In the theme functions file:
function my_wp_list_pages( $parent, $orderby = 'menu_order', $order = 'ASC' ) {
$pages = get_pages( array(
'parent' => $parent,
'sort_column' => $orderby,
'sort_order' => $order,
) );
if ( empty( $pages ) ) {
return;
}
// Just change the HTML markup based on your liking..
echo '<ul>';
foreach ( $pages as $page ) {
printf( '<li><a href="%s">%s</a></li>',
esc_url( get_permalink( $page ) ),
get_the_title( $page ) );
// Display grandchildren.
my_wp_list_pages( $page->ID, $orderby, $order );
}
echo '</ul>';
}
// In your template:
$parent = 123; // parent post/Page ID
my_wp_list_pages( $parent );
``` |
379,206 | <p>According to the announcement on the <a href="https://make.wordpress.org/core/2020/03/02/general-block-editor-api-updates/" rel="noreferrer">Make WordPress Core blog post</a> it appears that to use post meta on a post things have changed quite a bit.</p>
<p>I'm trying to get a simple block to read and save data from a custom field, and for some reason each time I hit save the data is lost.</p>
<p>I start by registering the custom field in PHP (attached to the <code>init</code> hook):</p>
<pre class="lang-php prettyprint-override"><code> register_post_meta('ebook', 'main_video', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
));
</code></pre>
<p>and from the block controls I'm trying to then read and set methods to write into that field as follows:</p>
<pre class="lang-js prettyprint-override"><code>const postType = useSelect((select) => select('core/editor').getCurrentPostType(), []);
const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
const url = meta && meta['main_video'];
const updateUrl = (newValue) => {
setMeta({ ...meta, main_video: newValue.url });
};
</code></pre>
<p>Both <code>url</code> and <code>updateUrl</code> variables are then consumed by a gutenberg component:</p>
<pre><code><LinkControl
className="wp-block-navigation-link__inline-link-input"
value={{ url }}
onChange={updateUrl}
settings={[]}
/>
</code></pre>
<p>If I log the values I can see data coming in and being updated, but as soon as I hit save on the post everything is reset.</p>
<p>The <code>ebook</code> post type where this custom field is being registered has support declared for <code>custom-fields</code>.</p>
<p>I've followed the <a href="https://developer.wordpress.org/block-editor/tutorials/metabox/meta-block-1-intro/" rel="noreferrer">official docs</a> on this a few times and couldn't get it to work as they describe.</p>
<p>Am I missing a key step here or something's amiss?</p>
| [
{
"answer_id": 391761,
"author": "Julio Braña Bouza",
"author_id": 101034,
"author_profile": "https://wordpress.stackexchange.com/users/101034",
"pm_score": 0,
"selected": false,
"text": "<p>I think your onChange function needs to pass the value, like <code>onChange={(value) => updateUrl(value)}</code></p>\n"
},
{
"answer_id": 396627,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>I am very late at this, but I think the problem here was that at registration code for your custom post type <code>ebook</code> (which you did not show) you were missing <code>supports</code> for <code>custom-fields</code> in args array:</p>\n<pre class=\"lang-php prettyprint-override\"><code>'supports' => [ 'title', 'editor', 'custom-fields' ]\n</code></pre>\n<p>and also</p>\n<pre class=\"lang-php prettyprint-override\"><code>'show_in_rest' => true\n</code></pre>\n"
}
] | 2020/12/02 | [
"https://wordpress.stackexchange.com/questions/379206",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62160/"
] | According to the announcement on the [Make WordPress Core blog post](https://make.wordpress.org/core/2020/03/02/general-block-editor-api-updates/) it appears that to use post meta on a post things have changed quite a bit.
I'm trying to get a simple block to read and save data from a custom field, and for some reason each time I hit save the data is lost.
I start by registering the custom field in PHP (attached to the `init` hook):
```php
register_post_meta('ebook', 'main_video', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
));
```
and from the block controls I'm trying to then read and set methods to write into that field as follows:
```js
const postType = useSelect((select) => select('core/editor').getCurrentPostType(), []);
const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
const url = meta && meta['main_video'];
const updateUrl = (newValue) => {
setMeta({ ...meta, main_video: newValue.url });
};
```
Both `url` and `updateUrl` variables are then consumed by a gutenberg component:
```
<LinkControl
className="wp-block-navigation-link__inline-link-input"
value={{ url }}
onChange={updateUrl}
settings={[]}
/>
```
If I log the values I can see data coming in and being updated, but as soon as I hit save on the post everything is reset.
The `ebook` post type where this custom field is being registered has support declared for `custom-fields`.
I've followed the [official docs](https://developer.wordpress.org/block-editor/tutorials/metabox/meta-block-1-intro/) on this a few times and couldn't get it to work as they describe.
Am I missing a key step here or something's amiss? | I am very late at this, but I think the problem here was that at registration code for your custom post type `ebook` (which you did not show) you were missing `supports` for `custom-fields` in args array:
```php
'supports' => [ 'title', 'editor', 'custom-fields' ]
```
and also
```php
'show_in_rest' => true
``` |
379,213 | <p>I'd love to know how to get back into wp-admin and get my site back online.</p>
<p>I contacted GoDaddy tech support again today and the PHP is supposedly updating.. Wordpress has been complaining about the older version of PHP it had a while back, as of 5 months ago, a GoDaddy rep told me I had to wait for the devs to switch me over at their convenience... Sadly, now I can't access wordress admin at all, I can only see this error message when I go to my URL:</p>
<blockquote>
<p>Warning:
require(/home/content/60/11745860/html/wp-includes/class-wp-post.php):
failed to open stream: No such file or directory in
/home/content/60/11745860/html/wp-settings.php on line 199</p>
<p>Fatal error: require(): Failed opening required
'/home/content/60/11745860/html/wp-includes/class-wp-post.php'
(include_path='.:/usr/local/php5_6/lib/php') in
/home/content/60/11745860/html/wp-settings.php on line 199</p>
</blockquote>
<p>Can I find this path / php file with the basic GoDaddy hosting File Manager? Should I wait for it to fix itself? Perhaps I should give up and build a new site? Any advise would be much appreciated. Thanks! - Teale Rose</p>
| [
{
"answer_id": 391761,
"author": "Julio Braña Bouza",
"author_id": 101034,
"author_profile": "https://wordpress.stackexchange.com/users/101034",
"pm_score": 0,
"selected": false,
"text": "<p>I think your onChange function needs to pass the value, like <code>onChange={(value) => updateUrl(value)}</code></p>\n"
},
{
"answer_id": 396627,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>I am very late at this, but I think the problem here was that at registration code for your custom post type <code>ebook</code> (which you did not show) you were missing <code>supports</code> for <code>custom-fields</code> in args array:</p>\n<pre class=\"lang-php prettyprint-override\"><code>'supports' => [ 'title', 'editor', 'custom-fields' ]\n</code></pre>\n<p>and also</p>\n<pre class=\"lang-php prettyprint-override\"><code>'show_in_rest' => true\n</code></pre>\n"
}
] | 2020/12/02 | [
"https://wordpress.stackexchange.com/questions/379213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198417/"
] | I'd love to know how to get back into wp-admin and get my site back online.
I contacted GoDaddy tech support again today and the PHP is supposedly updating.. Wordpress has been complaining about the older version of PHP it had a while back, as of 5 months ago, a GoDaddy rep told me I had to wait for the devs to switch me over at their convenience... Sadly, now I can't access wordress admin at all, I can only see this error message when I go to my URL:
>
> Warning:
> require(/home/content/60/11745860/html/wp-includes/class-wp-post.php):
> failed to open stream: No such file or directory in
> /home/content/60/11745860/html/wp-settings.php on line 199
>
>
> Fatal error: require(): Failed opening required
> '/home/content/60/11745860/html/wp-includes/class-wp-post.php'
> (include\_path='.:/usr/local/php5\_6/lib/php') in
> /home/content/60/11745860/html/wp-settings.php on line 199
>
>
>
Can I find this path / php file with the basic GoDaddy hosting File Manager? Should I wait for it to fix itself? Perhaps I should give up and build a new site? Any advise would be much appreciated. Thanks! - Teale Rose | I am very late at this, but I think the problem here was that at registration code for your custom post type `ebook` (which you did not show) you were missing `supports` for `custom-fields` in args array:
```php
'supports' => [ 'title', 'editor', 'custom-fields' ]
```
and also
```php
'show_in_rest' => true
``` |
379,261 | <p>I have added a page in the admin menu(<em>pxmag-menu</em>) and a submenu(<em>pxmag-plans</em>). There is another page(<em>pxmag-plans-edit</em>) set under the submenu(<em>pxmag-plans</em>) as the parent page.</p>
<pre><code>public function __construct()
{
require('pxMagAdminPlans.class.php');
$this->admPlanObj= new pxMagAdminPlans();
add_action('admin_menu', array($this, 'add_plan_admin_menu'));
}
public function add_plan_admin_menu()
{
add_menu_page(__('Dashboard', 'textdomain'), get_bloginfo('name'), 'manage_options', 'pxmag-menu', array($this, 'pxmag_dash'), 'dashicons-welcome-view-site', 6);
add_submenu_page('pxmag-menu', __('Subscription Plans', 'textdomain'), 'Plans', 'manage_options', 'pxmag-plans', array($this->admPlanObj, 'plan_admin_menu_page'));
add_submenu_page('pxmag-plans', __('Add/edit Plans', 'textdomain'), 'Add/edit plans', 'manage_options', 'pxmag-plans-edit', array($this->admPlanObj, 'plan_admin_menu_edit'));
}
</code></pre>
<p>All the menu and submenu pages load fine.</p>
<p>But, when I open this page(<em>pxmag-plans-edit</em>), the menu selection in the Wordpress admin shows nothing as current item, whereas the <em>pxmag-plans</em> is supposed to be the current selection.</p>
<p>(It is supposed to work like: when I click '<em>Posts > Categories</em>' and subsequently open the '<em>edit category</em>' page, the '<em>Posts > Categories</em>' option in menu keeps selected).</p>
<p>What is going wrong? What is the correct process?</p>
| [
{
"answer_id": 379283,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand it correctly — you want the "Plans" sub-menu to be highlighted when on the "Add/edit plans" (<code>pxmag-plans-edit</code>) page, then you can do it like so:</p>\n<ol>\n<li><p>Use the <a href=\"https://developer.wordpress.org/reference/hooks/add_menu_classes/\" rel=\"nofollow noreferrer\"><code>add_menu_classes</code> hook</a> to highlight the <code>pxmag-menu</code> menu:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function my_add_menu_classes( $menu ) {\n // Do nothing if not on the "Add/edit plans" page.\n global $plugin_page;\n if ( 'pxmag-plans-edit' !== $plugin_page ) {\n return $menu;\n }\n\n foreach ( $menu as $i => $item ) {\n if ( 'pxmag-menu' === $item[2] ) {\n $menu[ $i ][4] = add_cssclass( 'wp-has-current-submenu wp-menu-open', $item[4] );\n }\n }\n\n return $menu;\n}\nadd_filter( 'add_menu_classes', 'my_add_menu_classes' );\n</code></pre>\n</li>\n<li><p>Use the <a href=\"https://developer.wordpress.org/reference/hooks/submenu_file/\" rel=\"nofollow noreferrer\"><code>submenu_file</code> hook</a> to highlight the "Plans" (<code>pxmag-plans</code>) sub-menu:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function my_submenu_file( $submenu_file, $parent_file ) {\n global $plugin_page;\n return ( 'pxmag-plans-edit' === $plugin_page )\n ? 'pxmag-plans' : $submenu_file;\n}\nadd_filter( 'submenu_file', 'my_submenu_file', 10, 2 );\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 379286,
"author": "sariDon",
"author_id": 92425,
"author_profile": "https://wordpress.stackexchange.com/users/92425",
"pm_score": 0,
"selected": false,
"text": "<p>I have slightly modified the code posted as answer by <a href=\"https://wordpress.stackexchange.com/questions/379261/wordpress-add-page-under-admin-submenu-and-retaining-the-active-status-of-the-pa/379283#379283\">@Sally CJ</a> to work with multiple cases:</p>\n<pre><code>public function __construct()\n{\n require('pxMagAdminPlans.class.php');\n require('pxMagAdminPromo.class.php');\n \n $this->admPlanObj= new pxMagAdminPlans();\n $this->admPromoObj= new pxMagAdminPromo();\n \n add_action('admin_menu', array($this, 'add_plan_admin_menu'));\n \n add_filter('add_menu_classes', array($this, 'adjust_menu_classes'));\n add_filter('submenu_file', array($this, 'adjust_submenu_file'), 10, 2 );\n}\n\npublic function add_plan_admin_menu()\n{\n add_menu_page(__('Dashboard', 'textdomain'), get_bloginfo('name'), 'manage_options', 'pxmag-menu', array($this, 'pxmag_dash'), 'dashicons-welcome-view-site', 6);\n \n add_submenu_page('pxmag-menu', __('Subscription Plans', 'textdomain'), 'Plans', 'manage_options', 'pxmag-plans', array($this->admPlanObj, 'plan_admin_menu_page'));\n add_submenu_page('pxmag-plans', __('Add/edit Plans', 'textdomain'), 'Add/edit plans', 'manage_options', 'pxmag-plans-edit', array($this->admPlanObj, 'plan_admin_menu_edit'));\n \n add_submenu_page('pxmag-menu', __('Manage Promotions', 'textdomain'), 'Promotions', 'manage_options', 'pxmag-promotions', array($this->admPromoObj, 'get_promotions'));\n add_submenu_page('pxmag-promotions', __('Add/Edit', 'textdomain'), 'Add/Edit', 'manage_options', 'pxmag-promotions-edit', array($this->admPromoObj, 'manage_promotions'));\n \n remove_submenu_page('pxmag-menu','pxmag-menu');\n}\n \nfunction adjust_submenu_file($submenu_file, $parent_file) {\n global $plugin_page;\n $retsub = $submenu_file;\n if('pxmag-plans-edit' === $plugin_page)\n $retsub = 'pxmag-plans';\n elseif ('pxmag-promotions-edit' === $plugin_page)\n $retsub = 'pxmag-promotions';\n return $retsub;\n}\n\nfunction adjust_menu_classes($menu)\n{\n global $plugin_page;\n $retmenu = $menu;\n\n if (('pxmag-promotions-edit' == $plugin_page) || ('pxmag-plans-edit' == $plugin_page))\n {\n foreach ($menu as $i => $item)\n {\n if ('pxmag-menu' === $item[2])\n {\n $retmenu[$i][4] = add_cssclass('wp-has-current-submenu wp-menu-open', $item[4]);\n }\n }\n }\n return $retmenu;\n}\n</code></pre>\n"
}
] | 2020/12/03 | [
"https://wordpress.stackexchange.com/questions/379261",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92425/"
] | I have added a page in the admin menu(*pxmag-menu*) and a submenu(*pxmag-plans*). There is another page(*pxmag-plans-edit*) set under the submenu(*pxmag-plans*) as the parent page.
```
public function __construct()
{
require('pxMagAdminPlans.class.php');
$this->admPlanObj= new pxMagAdminPlans();
add_action('admin_menu', array($this, 'add_plan_admin_menu'));
}
public function add_plan_admin_menu()
{
add_menu_page(__('Dashboard', 'textdomain'), get_bloginfo('name'), 'manage_options', 'pxmag-menu', array($this, 'pxmag_dash'), 'dashicons-welcome-view-site', 6);
add_submenu_page('pxmag-menu', __('Subscription Plans', 'textdomain'), 'Plans', 'manage_options', 'pxmag-plans', array($this->admPlanObj, 'plan_admin_menu_page'));
add_submenu_page('pxmag-plans', __('Add/edit Plans', 'textdomain'), 'Add/edit plans', 'manage_options', 'pxmag-plans-edit', array($this->admPlanObj, 'plan_admin_menu_edit'));
}
```
All the menu and submenu pages load fine.
But, when I open this page(*pxmag-plans-edit*), the menu selection in the Wordpress admin shows nothing as current item, whereas the *pxmag-plans* is supposed to be the current selection.
(It is supposed to work like: when I click '*Posts > Categories*' and subsequently open the '*edit category*' page, the '*Posts > Categories*' option in menu keeps selected).
What is going wrong? What is the correct process? | If I understand it correctly — you want the "Plans" sub-menu to be highlighted when on the "Add/edit plans" (`pxmag-plans-edit`) page, then you can do it like so:
1. Use the [`add_menu_classes` hook](https://developer.wordpress.org/reference/hooks/add_menu_classes/) to highlight the `pxmag-menu` menu:
```php
function my_add_menu_classes( $menu ) {
// Do nothing if not on the "Add/edit plans" page.
global $plugin_page;
if ( 'pxmag-plans-edit' !== $plugin_page ) {
return $menu;
}
foreach ( $menu as $i => $item ) {
if ( 'pxmag-menu' === $item[2] ) {
$menu[ $i ][4] = add_cssclass( 'wp-has-current-submenu wp-menu-open', $item[4] );
}
}
return $menu;
}
add_filter( 'add_menu_classes', 'my_add_menu_classes' );
```
2. Use the [`submenu_file` hook](https://developer.wordpress.org/reference/hooks/submenu_file/) to highlight the "Plans" (`pxmag-plans`) sub-menu:
```php
function my_submenu_file( $submenu_file, $parent_file ) {
global $plugin_page;
return ( 'pxmag-plans-edit' === $plugin_page )
? 'pxmag-plans' : $submenu_file;
}
add_filter( 'submenu_file', 'my_submenu_file', 10, 2 );
``` |
379,306 | <p>I'm trying to hide error messages on a WordPress installation on a shared hosting. I added the following code to my config.</p>
<pre><code>ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);
</code></pre>
<p>This is pretty much what I find in any article regarding this topic. However, it doesn't work. I keep getting error messages. What could be the reason it isn't working for me?</p>
<hr />
<p><strong>A little update.</strong> One error I sometimes get is a "notice". When I keep all these three lines and put error_reporting to "0" as suggested in the answers, I still get the notice error.</p>
<pre><code>define( 'WP_DEBUG', false );
ini_set('display_errors','Off');
ini_set('error_reporting', 0 );
define('WP_DEBUG_DISPLAY', false);
</code></pre>
<p>However, when I comment the last 3 lines, the notice disappears:</p>
<pre><code>define( 'WP_DEBUG', false );
//ini_set('display_errors','Off');
//ini_set('error_reporting', 0 );
//define('WP_DEBUG_DISPLAY', false);
</code></pre>
<p>Does that make any sense to anyone? What's happening here?</p>
| [
{
"answer_id": 379334,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that this line</p>\n<pre><code>ini_set('error_reporting', E_ALL );\n</code></pre>\n<p>will override other error settings. Will display all errors, even 'benign' ones, to the screen and error log file.</p>\n"
},
{
"answer_id": 379528,
"author": "Andrew",
"author_id": 186772,
"author_profile": "https://wordpress.stackexchange.com/users/186772",
"pm_score": 2,
"selected": false,
"text": "<p>You shoud use</p>\n<pre><code>ini_set('error_reporting', 0 );\n</code></pre>\n<p>instead of:</p>\n<pre><code>ini_set('error_reporting', E_ALL );\n</code></pre>\n<p>because <strong>E_ALL</strong> tell to show every error.</p>\n"
},
{
"answer_id": 380390,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>If your hosting php.ini is properly configured, is not necessary to use <code>ini_set()</code> in your wp-config.php when you are defining <code>WP_DEBUG</code>.</p>\n<p>What is <code>WP_DEBUG</code>? It's a constant used in WP to determine what error notice settings to apply. When WP loads, one of the functions that is run on every load is <code>wp_debug_mode()</code>. I highly suggest you <a href=\"https://developer.wordpress.org/reference/functions/wp_debug_mode/\" rel=\"nofollow noreferrer\">review what it does</a> so you know why you originarily do not need to use <code>ini_set()</code> - because it's already being done in <code>wp_debug_mode()</code>. So what you're doing by adding this to your wp-config.php is the equivalent of flipping the switch on/off/on/off over and over.</p>\n<p>When <code>WP_DEBUG</code> is set to true, it sets <code>error_reporting( E_ALL )</code>. Otherwise, <code>error_reporting()</code> is set to a lesser value. You should not manually set this to 0 unless you know what you're doing - otherwise, you're shutting off all error reporting, which will make it hard when you actually need to debug something but forgot that you turned off all notices. Unless you really have a need to do so, just let WP handle setting the <code>error_reporting()</code> value.</p>\n<p>Next, when <code>WP_DEBUG</code> is true, it handles the display of errors based on the <code>WP_DEBUG_DISPLAY</code> value. If it's true, then <code>ini_set()</code> is run to set 'display_errors' to "1", which will display errors on the screen. If <code>WP_DEBUG_DISPLAY</code> is set to false, it will set 'display_errors' to "0" which will suppress display of any errors.</p>\n<p>I hope this didn't confuse the issue, and I hope that you can see why the last set you had (where all but <code>WP_DEBUG</code> was commented out) suppressed the messages.</p>\n<p>If you want error messages turned off, just set <code>WP_DEBUG</code> and <code>WP_DEBUG_DISPLAY</code> to false, and get rid of the <code>ini_set()</code> lines you have.</p>\n"
}
] | 2020/12/04 | [
"https://wordpress.stackexchange.com/questions/379306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118091/"
] | I'm trying to hide error messages on a WordPress installation on a shared hosting. I added the following code to my config.
```
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);
```
This is pretty much what I find in any article regarding this topic. However, it doesn't work. I keep getting error messages. What could be the reason it isn't working for me?
---
**A little update.** One error I sometimes get is a "notice". When I keep all these three lines and put error\_reporting to "0" as suggested in the answers, I still get the notice error.
```
define( 'WP_DEBUG', false );
ini_set('display_errors','Off');
ini_set('error_reporting', 0 );
define('WP_DEBUG_DISPLAY', false);
```
However, when I comment the last 3 lines, the notice disappears:
```
define( 'WP_DEBUG', false );
//ini_set('display_errors','Off');
//ini_set('error_reporting', 0 );
//define('WP_DEBUG_DISPLAY', false);
```
Does that make any sense to anyone? What's happening here? | I believe that this line
```
ini_set('error_reporting', E_ALL );
```
will override other error settings. Will display all errors, even 'benign' ones, to the screen and error log file. |
379,358 | <p>I'm trying to ensure that all assets are the same size, no matter what resolution they are uploaded in. I'm stuck finding outdated info on the matter, I think.</p>
<p>I've gotten to the following snippet</p>
<pre><code>if( get_the_post_thumbnail_url()){
$image = wp_get_image_editor(get_the_post_thumbnail_url());
if ( !is_wp_error( $image )){
$image->resize( 300, 300, true );
$image->save("image.jpg");
}
}
</code></pre>
<p>Which seems to work, but I have no idea how I get the resized URL (or insert it properly). As I want to add it to my page.
Something like</p>
<pre><code>echo '<img src=" . $image.url() . ">";
</code></pre>
<p>Is what I'm thinking of.
Am I going about this wrong, or how should I continue from here?</p>
<p>Thanks!</p>
| [
{
"answer_id": 379314,
"author": "Marc",
"author_id": 193017,
"author_profile": "https://wordpress.stackexchange.com/users/193017",
"pm_score": 2,
"selected": false,
"text": "<p>By default, that API endpoint is paged and the amount per_page is set to 10. You can see all the defaults for that endpoint here <a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders</a></p>\n<p>If this endpoint works like WP_Query then you'll need to set the per_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders</p>\n"
},
{
"answer_id": 401809,
"author": "babita",
"author_id": 203858,
"author_profile": "https://wordpress.stackexchange.com/users/203858",
"pm_score": 0,
"selected": false,
"text": "<p>this will surely show all orders</p>\n<pre><code> enter code here\n const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;\n\nconst api = new WooCommerceRestApi({\n url: process.env.NEXT_PUBLIC_WORDPRESS_SITE_URL,\n consumerKey: process.env.CONSUMER_KEY,\n consumerSecret: process.env.CONSUMER_SECRET,\n version: "wc/v3"\n});\nexport default async function handler(req, res){\n const responseData = {\n success:false,\n orders: []\n }\n\n const { perPage} = req?.query ?? {};\n try {\n const {data} = await api.get(\n 'orders',\n {\n per_page:perPage||100\n\n\n }\n );\n responseData.success = true;\n responseData.orders = data;\n res.json( responseData);\n } catch ( error ){\n responseData.error = error.message;\n res.status(500).json(responseData);\n }\n}\n\n\n</code></pre>\n"
}
] | 2020/12/05 | [
"https://wordpress.stackexchange.com/questions/379358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198566/"
] | I'm trying to ensure that all assets are the same size, no matter what resolution they are uploaded in. I'm stuck finding outdated info on the matter, I think.
I've gotten to the following snippet
```
if( get_the_post_thumbnail_url()){
$image = wp_get_image_editor(get_the_post_thumbnail_url());
if ( !is_wp_error( $image )){
$image->resize( 300, 300, true );
$image->save("image.jpg");
}
}
```
Which seems to work, but I have no idea how I get the resized URL (or insert it properly). As I want to add it to my page.
Something like
```
echo '<img src=" . $image.url() . ">";
```
Is what I'm thinking of.
Am I going about this wrong, or how should I continue from here?
Thanks! | By default, that API endpoint is paged and the amount per\_page is set to 10. You can see all the defaults for that endpoint here <https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders>
If this endpoint works like WP\_Query then you'll need to set the per\_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders |
379,400 | <p>I need to execute a portion of code after each: Add / Edit / delete a custom taxonomy .
For creation / edition it works well, but for deletion non :</p>
<pre><code> add_action( 'edited_product_category', array ( $this , 'term_edit_success' ), 10, 2 );
add_action( 'create_product_category', array ( $this , 'term_create_success' ), 10, 2 );
add_action( 'delete_product_category', array ( $this , 'term_delete_success' ), 10, 2 );
</code></pre>
| [
{
"answer_id": 379314,
"author": "Marc",
"author_id": 193017,
"author_profile": "https://wordpress.stackexchange.com/users/193017",
"pm_score": 2,
"selected": false,
"text": "<p>By default, that API endpoint is paged and the amount per_page is set to 10. You can see all the defaults for that endpoint here <a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders</a></p>\n<p>If this endpoint works like WP_Query then you'll need to set the per_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders</p>\n"
},
{
"answer_id": 401809,
"author": "babita",
"author_id": 203858,
"author_profile": "https://wordpress.stackexchange.com/users/203858",
"pm_score": 0,
"selected": false,
"text": "<p>this will surely show all orders</p>\n<pre><code> enter code here\n const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;\n\nconst api = new WooCommerceRestApi({\n url: process.env.NEXT_PUBLIC_WORDPRESS_SITE_URL,\n consumerKey: process.env.CONSUMER_KEY,\n consumerSecret: process.env.CONSUMER_SECRET,\n version: "wc/v3"\n});\nexport default async function handler(req, res){\n const responseData = {\n success:false,\n orders: []\n }\n\n const { perPage} = req?.query ?? {};\n try {\n const {data} = await api.get(\n 'orders',\n {\n per_page:perPage||100\n\n\n }\n );\n responseData.success = true;\n responseData.orders = data;\n res.json( responseData);\n } catch ( error ){\n responseData.error = error.message;\n res.status(500).json(responseData);\n }\n}\n\n\n</code></pre>\n"
}
] | 2020/12/06 | [
"https://wordpress.stackexchange.com/questions/379400",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65465/"
] | I need to execute a portion of code after each: Add / Edit / delete a custom taxonomy .
For creation / edition it works well, but for deletion non :
```
add_action( 'edited_product_category', array ( $this , 'term_edit_success' ), 10, 2 );
add_action( 'create_product_category', array ( $this , 'term_create_success' ), 10, 2 );
add_action( 'delete_product_category', array ( $this , 'term_delete_success' ), 10, 2 );
``` | By default, that API endpoint is paged and the amount per\_page is set to 10. You can see all the defaults for that endpoint here <https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders>
If this endpoint works like WP\_Query then you'll need to set the per\_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders |
379,424 | <p>How do I get the id of the most recent wordpress audio media upload.
The reason for this is that I want to use audio cover images/ featured images as a post featured image.
Do I need to retrieve the ID of the thumbnail in the audio.</p>
<p>I tried the code below but it returned error</p>
<pre><code> $attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_status' => null,
'post_mime_type' => 'audio'
) );
foreach ( $attachments as $attachment ) {
$post_id = get_post_thumbnail_id( $attachment->ID);
}
</code></pre>
| [
{
"answer_id": 379314,
"author": "Marc",
"author_id": 193017,
"author_profile": "https://wordpress.stackexchange.com/users/193017",
"pm_score": 2,
"selected": false,
"text": "<p>By default, that API endpoint is paged and the amount per_page is set to 10. You can see all the defaults for that endpoint here <a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders</a></p>\n<p>If this endpoint works like WP_Query then you'll need to set the per_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders</p>\n"
},
{
"answer_id": 401809,
"author": "babita",
"author_id": 203858,
"author_profile": "https://wordpress.stackexchange.com/users/203858",
"pm_score": 0,
"selected": false,
"text": "<p>this will surely show all orders</p>\n<pre><code> enter code here\n const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;\n\nconst api = new WooCommerceRestApi({\n url: process.env.NEXT_PUBLIC_WORDPRESS_SITE_URL,\n consumerKey: process.env.CONSUMER_KEY,\n consumerSecret: process.env.CONSUMER_SECRET,\n version: "wc/v3"\n});\nexport default async function handler(req, res){\n const responseData = {\n success:false,\n orders: []\n }\n\n const { perPage} = req?.query ?? {};\n try {\n const {data} = await api.get(\n 'orders',\n {\n per_page:perPage||100\n\n\n }\n );\n responseData.success = true;\n responseData.orders = data;\n res.json( responseData);\n } catch ( error ){\n responseData.error = error.message;\n res.status(500).json(responseData);\n }\n}\n\n\n</code></pre>\n"
}
] | 2020/12/06 | [
"https://wordpress.stackexchange.com/questions/379424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/197886/"
] | How do I get the id of the most recent wordpress audio media upload.
The reason for this is that I want to use audio cover images/ featured images as a post featured image.
Do I need to retrieve the ID of the thumbnail in the audio.
I tried the code below but it returned error
```
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_status' => null,
'post_mime_type' => 'audio'
) );
foreach ( $attachments as $attachment ) {
$post_id = get_post_thumbnail_id( $attachment->ID);
}
``` | By default, that API endpoint is paged and the amount per\_page is set to 10. You can see all the defaults for that endpoint here <https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders>
If this endpoint works like WP\_Query then you'll need to set the per\_page parameter to -1. Otherwise you'll need to make multiple requests, incrementing the page number each time until you've received all the orders |
379,556 | <p>I am missing some feature to prompt the user for input. In Laravel we have <code>$this->ask('What is your age')</code> (<a href="https://laravel.com/docs/8.x/artisan#prompting-for-input" rel="nofollow noreferrer">https://laravel.com/docs/8.x/artisan#prompting-for-input</a>)</p>
<p>I haven't been able to find any information on this online</p>
| [
{
"answer_id": 395107,
"author": "Robert Gres",
"author_id": 146551,
"author_profile": "https://wordpress.stackexchange.com/users/146551",
"pm_score": 1,
"selected": false,
"text": "<p>I didn't find any wp-cli utility either, but <code>readline</code> php function works just fine.</p>\n<p>PHPStorm warns me that <code>ext-readline</code> must be enabled in order to use it, but it seems like something that is always enabled in cli environment</p>\n"
},
{
"answer_id": 395130,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>There's the <a href=\"https://make.wordpress.org/cli/handbook/references/config/\" rel=\"nofollow noreferrer\">global parameter</a></p>\n<pre><code>--prompt[=<assoc>]\n</code></pre>\n<blockquote>\n<p>Prompt the user to enter values for all command arguments, or a subset\nspecified as comma-separated values.</p>\n</blockquote>\n<h2>Example - Prompting two arguments</h2>\n<p>We can prompt post title and content of a given command with:</p>\n<pre><code>$ wp post create --prompt=post_title,post_content\n\n4/30 [--post_content=<post_content>]: test\n6/30 [--post_title=<post_title>]: test\nwp post create --post_content='test' --post_title='test'\nSuccess: Created post 14464.\n</code></pre>\n<p>where the resulting command is:</p>\n<pre><code>wp post create --post_content='test' --post_title='test'\n</code></pre>\n<h2>Example - Prompting all arguments</h2>\n<p>We can prompt all arguments of a given command with:</p>\n<pre><code>$ wp post create --prompt\n\n1/30 [--post_author=<post_author>]:\n2/30 [--post_date=<post_date>]:\n3/30 [--post_date_gmt=<post_date_gmt>]:\n4/30 [--post_content=<post_content>]: test\n5/30 [--post_content_filtered=<post_content_filtered>]:\n6/30 [--post_title=<post_title>]: test\n7/30 [--post_excerpt=<post_excerpt>]:\n8/30 [--post_status=<post_status>]:\n9/30 [--post_type=<post_type>]:\n10/30 [--comment_status=<comment_status>]:\n11/30 [--ping_status=<ping_status>]:\n12/30 [--post_password=<post_password>]:\n13/30 [--post_name=<post_name>]:\n14/30 [--from-post=<post_id>]:\n15/30 [--to_ping=<to_ping>]:\n16/30 [--pinged=<pinged>]:\n17/30 [--post_modified=<post_modified>]:\n18/30 [--post_modified_gmt=<post_modified_gmt>]:\n19/30 [--post_parent=<post_parent>]:\n20/30 [--menu_order=<menu_order>]:\n21/30 [--post_mime_type=<post_mime_type>]:\n22/30 [--guid=<guid>]:\n23/30 [--post_category=<post_category>]:\n24/30 [--tags_input=<tags_input>]:\n25/30 [--tax_input=<tax_input>]:\n26/30 [--meta_input=<meta_input>]:\n27/30 [<file>]:\n28/30 [--<field>:\n29/30 [--edit] (Y/n):\n30/30 [--porcelain] (Y/n):\nwp post create --post_content='test' --post_title='test'\nSuccess: Created post 14461.\n</code></pre>\n<p>where the resulting command is:</p>\n<pre><code>wp post create --post_content='test' --post_title='test'\n</code></pre>\n<h2>WP_CLI::confirm</h2>\n<p>Looking into <a href=\"https://github.com/wp-cli/wp-cli/blob/ae8be1523c0453ba43347d600c3f9caf8ff5bffc/php/class-wp-cli.php#L921\" rel=\"nofollow noreferrer\">class-wp-cli.php</a> we also have the <code>y/n</code> confirmation:</p>\n<pre><code> * # `wp db drop` asks for confirmation before dropping the database.\n *\n * WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args );\n</code></pre>\n<p>that uses:</p>\n<pre><code>$answer = strtolower( trim( fgets( STDIN ) ) );\n</code></pre>\n<p>to get the user input answer.</p>\n<p>We could use the construction of the <code>confirm</code> method as a base for more general user inputs.</p>\n"
}
] | 2020/12/09 | [
"https://wordpress.stackexchange.com/questions/379556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50042/"
] | I am missing some feature to prompt the user for input. In Laravel we have `$this->ask('What is your age')` (<https://laravel.com/docs/8.x/artisan#prompting-for-input>)
I haven't been able to find any information on this online | There's the [global parameter](https://make.wordpress.org/cli/handbook/references/config/)
```
--prompt[=<assoc>]
```
>
> Prompt the user to enter values for all command arguments, or a subset
> specified as comma-separated values.
>
>
>
Example - Prompting two arguments
---------------------------------
We can prompt post title and content of a given command with:
```
$ wp post create --prompt=post_title,post_content
4/30 [--post_content=<post_content>]: test
6/30 [--post_title=<post_title>]: test
wp post create --post_content='test' --post_title='test'
Success: Created post 14464.
```
where the resulting command is:
```
wp post create --post_content='test' --post_title='test'
```
Example - Prompting all arguments
---------------------------------
We can prompt all arguments of a given command with:
```
$ wp post create --prompt
1/30 [--post_author=<post_author>]:
2/30 [--post_date=<post_date>]:
3/30 [--post_date_gmt=<post_date_gmt>]:
4/30 [--post_content=<post_content>]: test
5/30 [--post_content_filtered=<post_content_filtered>]:
6/30 [--post_title=<post_title>]: test
7/30 [--post_excerpt=<post_excerpt>]:
8/30 [--post_status=<post_status>]:
9/30 [--post_type=<post_type>]:
10/30 [--comment_status=<comment_status>]:
11/30 [--ping_status=<ping_status>]:
12/30 [--post_password=<post_password>]:
13/30 [--post_name=<post_name>]:
14/30 [--from-post=<post_id>]:
15/30 [--to_ping=<to_ping>]:
16/30 [--pinged=<pinged>]:
17/30 [--post_modified=<post_modified>]:
18/30 [--post_modified_gmt=<post_modified_gmt>]:
19/30 [--post_parent=<post_parent>]:
20/30 [--menu_order=<menu_order>]:
21/30 [--post_mime_type=<post_mime_type>]:
22/30 [--guid=<guid>]:
23/30 [--post_category=<post_category>]:
24/30 [--tags_input=<tags_input>]:
25/30 [--tax_input=<tax_input>]:
26/30 [--meta_input=<meta_input>]:
27/30 [<file>]:
28/30 [--<field>:
29/30 [--edit] (Y/n):
30/30 [--porcelain] (Y/n):
wp post create --post_content='test' --post_title='test'
Success: Created post 14461.
```
where the resulting command is:
```
wp post create --post_content='test' --post_title='test'
```
WP\_CLI::confirm
----------------
Looking into [class-wp-cli.php](https://github.com/wp-cli/wp-cli/blob/ae8be1523c0453ba43347d600c3f9caf8ff5bffc/php/class-wp-cli.php#L921) we also have the `y/n` confirmation:
```
* # `wp db drop` asks for confirmation before dropping the database.
*
* WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args );
```
that uses:
```
$answer = strtolower( trim( fgets( STDIN ) ) );
```
to get the user input answer.
We could use the construction of the `confirm` method as a base for more general user inputs. |
379,560 | <p>I am using custom php code to perform data insertion, deletion, updating and other tasks. I am able to insert data into a table in two different ways,</p>
<pre><code>$wpdb->insert($table_name, array('id' => NULL, 'name' => '$name', 'email' => '$email', 'city' => '$city'));
</code></pre>
<p>and</p>
<pre><code>$sql = "INSERT INTO $table_name VALUES('', '$name', '$email', '$city')";
$wpdb->query($sql);
</code></pre>
<p>Is it a good practice to use <code>wpdb->query()</code> function each time by passing my query to the function instead of using the dedicated functions like <code>insert()</code> and <code>delete()</code> etc? If not, what are the disadvantages of this approach?</p>
| [
{
"answer_id": 379565,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>Is it a good practice to use wpdb->query() function each time by passing my query to the function instead of using the dedicated functions like insert() and delete() etc?</p>\n</blockquote>\n<p><strong>No, it is not good practice.</strong> Always prefer the <code>insert</code>/<code>update</code>/etc methods.</p>\n<p>Generally the use of raw SQL in WordPress is a code smell, and using raw SQL when a helper function is available is also bad practice. It implies that the writer is unaware of more convenient APIs with better speed/security, and forces you to reinvent all the fixes and bugs WP developers encountered over the years.</p>\n<p>So:</p>\n<ul>\n<li>Use <code>insert</code> etc to insert, not <code>query</code>, always prefer the more specific function</li>\n<li>Use the 3rd parameter that specifies the format for security reasons</li>\n<li>use <code>query</code> as a fallback for more general SQL queries where a specific function is unavailable\n<ul>\n<li>Always use <code>prepare</code> with raw SQL, the examples in your question have SQL injection attack bugs. <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">See here for how to prepare and secure a raw query</a>. <code>insert</code> etc will do this automatically if you pass a 3rd parameter</li>\n</ul>\n</li>\n<li>Don't wrap variables in <code>'</code>, use <code>$name</code> not <code>'$name'</code> or you'll insert <code>$name</code> not its value.</li>\n<li>you don't need the <code>id</code> set to <code>null</code>, if the table was created right with auto increment you can remove that</li>\n<li>you should check if it succeeded or not, don't just assume it worked</li>\n</ul>\n<pre class=\"lang-php prettyprint-override\"><code>$result = $wpdb->insert(\n $table_name,\n [\n 'name' => $name,\n 'email' => $email,\n 'city' => $city,\n ],\n [\n '%s',\n '%s',\n '%s',\n ]\n);\nif ( false === $result ) {\n // something went wrong\n}\n</code></pre>\n<h2>What About Creating Tables?</h2>\n<p><strong>Use <code>dbDelta</code>,</strong> it will create tables if they don't exist, and update their schema if it changes. No queries to test if the table exists, or update it, or create it, <code>dbDelta</code> does it for you. It takes a table creation query as a parameter, and it has to be formatted in a particular way or it won't work.</p>\n<p><code>wpdb->query</code> is inappropriate for creating tables.</p>\n<h2>A Note on Custom Tables</h2>\n<p>Just because you used a custom table doesn't mean it's faster/better. Make sure you design your tables with keys and indexes that reflect the types of queries you're going to run. A well built table can be lightning fast, but most tables will perform worse the custom post types at scale due to bad design.</p>\n<p>And where possible, avoid writing SQL to interact with your table if you can.</p>\n"
},
{
"answer_id": 379567,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 4,
"selected": true,
"text": "<p>If you look a bit into the source, you'll see that <code>$wpdb->insert()</code> will use <a href=\"https://core.trac.wordpress.org/browser/tags/5.6/src/wp-includes/wp-db.php#L2282\" rel=\"noreferrer\"><code>->query()</code> under the hood</a>. So should be the same, right?</p>\n<p>Not that simple. It doesn't just use <code>->query()</code> but also <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"noreferrer\"><code>->prepare()</code></a>, which is considered best practice. Meanwhile with your code example you've probably just opened yourself to SQL injections.</p>\n<p>The takeaway here: If it is a simple operation and the <code>->insert()</code> etc. method work - use them. They're tested and contain little risk. Writing your own queries always carries the risk of opening yourself up to troubles such as SQL injections.</p>\n"
}
] | 2020/12/09 | [
"https://wordpress.stackexchange.com/questions/379560",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198772/"
] | I am using custom php code to perform data insertion, deletion, updating and other tasks. I am able to insert data into a table in two different ways,
```
$wpdb->insert($table_name, array('id' => NULL, 'name' => '$name', 'email' => '$email', 'city' => '$city'));
```
and
```
$sql = "INSERT INTO $table_name VALUES('', '$name', '$email', '$city')";
$wpdb->query($sql);
```
Is it a good practice to use `wpdb->query()` function each time by passing my query to the function instead of using the dedicated functions like `insert()` and `delete()` etc? If not, what are the disadvantages of this approach? | If you look a bit into the source, you'll see that `$wpdb->insert()` will use [`->query()` under the hood](https://core.trac.wordpress.org/browser/tags/5.6/src/wp-includes/wp-db.php#L2282). So should be the same, right?
Not that simple. It doesn't just use `->query()` but also [`->prepare()`](https://developer.wordpress.org/reference/classes/wpdb/prepare/), which is considered best practice. Meanwhile with your code example you've probably just opened yourself to SQL injections.
The takeaway here: If it is a simple operation and the `->insert()` etc. method work - use them. They're tested and contain little risk. Writing your own queries always carries the risk of opening yourself up to troubles such as SQL injections. |
379,612 | <p>Following up on <a href="https://wordpress.stackexchange.com/q/326959/32946">this question</a>, I want to remove some of the default (core) embed blocks in the WordPress block editor. As of WordPress 5.6, the blocks are no longer available under the <code>core-embed/*</code> namespace.</p>
<p>How can I unregister individual core embed blocks?</p>
| [
{
"answer_id": 379613,
"author": "Sven",
"author_id": 32946,
"author_profile": "https://wordpress.stackexchange.com/users/32946",
"pm_score": 5,
"selected": true,
"text": "<p>With WordPress 5.6 (<a href=\"https://github.com/WordPress/gutenberg/releases/tag/v8.8.0\" rel=\"nofollow noreferrer\">Gutenberg v8.8.0</a>), the implementation of the <code>core-embed/*</code> blocks changed (see pull request <a href=\"https://github.com/WordPress/gutenberg/pull/24090\" rel=\"nofollow noreferrer\">#24090</a>: Refactor embed block to single block with block variations). There are now 43 blocks with block variations of the <code>core/embed</code> block.</p>\n<p>Available core blocks are:</p>\n<pre class=\"lang-html prettyprint-override\"><code>core/paragraph\ncore/image\ncore/heading\ncore/gallery\ncore/list\ncore/quote\ncore/shortcode\ncore/archives\ncore/audio\ncore/button\ncore/buttons\ncore/calendar\ncore/categories\ncore/code\ncore/columns\ncore/column\ncore/cover\ncore/embed\ncore/file\ncore/group\ncore/freeform\ncore/html\ncore/media-text\ncore/latest-comments\ncore/latest-posts\ncore/missing\ncore/more\ncore/nextpage\ncore/preformatted\ncore/pullquote\ncore/rss\ncore/search\ncore/separator\ncore/block\ncore/social-links\ncore/social-link\ncore/spacer\ncore/subhead\ncore/table\ncore/tag-cloud\ncore/text-columns\ncore/verse\ncore/video\n</code></pre>\n<p>Unregister embeds altogether (including variations):</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.domReady(function () {\n wp.blocks.unregisterBlockType('core/embed');\n});\n</code></pre>\n<p>The blocks previously listed as <code>core-embed/*</code> are now available as a variation of <code>core/embed</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>console.table(wp.blocks.getBlockVariations('core/embed'));\n</code></pre>\n<p>Available block variations of <code>core/embed</code> are:</p>\n<pre class=\"lang-html prettyprint-override\"><code>amazon-kindle\nanimoto\ncloudup\ncollegehumor\ncrowdsignal\ndailymotion\nfacebook\nflickr\nimgur\ninstagram\nissuu\nkickstarter\nmeetup-com\nmixcloud\npinterest\npocketcasts\nreddit\nreverbnation\nscreencast\nscribd\nslideshare\nsmugmug\nsoundcloud\nspeaker-deck\nspotify\nted\ntiktok\ntumblr\ntwitter\nvideopress\nvimeo\nwolfram-cloud\nwordpress\nwordpress-tv\nyoutube\n</code></pre>\n<p>You can unregister a single variation like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.domReady(function () {\n wp.blocks.unregisterBlockVariation('core/embed', 'twitter');\n});\n</code></pre>\n<p>Or unregister all variations and only allow individual variations:</p>\n<pre><code>wp.domReady(function () {\n const allowedEmbedBlocks = [\n 'vimeo',\n 'youtube',\n ];\n wp.blocks.getBlockVariations('core/embed').forEach(function (blockVariation) {\n if (-1 === allowedEmbedBlocks.indexOf(blockVariation.name)) {\n wp.blocks.unregisterBlockVariation('core/embed', blockVariation.name);\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 380977,
"author": "Marc",
"author_id": 66405,
"author_profile": "https://wordpress.stackexchange.com/users/66405",
"pm_score": 3,
"selected": false,
"text": "<p>As a theme developer I often want the embed blocks restricted to youtube and vimeo, just as Sven. So, following Sven's answer:\nIn my php code:</p>\n<pre><code>function my_theme_deny_list_blocks() {\n wp_enqueue_script(\n 'deny-list-blocks',\n get_template_directory_uri() . '/assets/js/deny-list-blocks.js',\n array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' )\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'my_theme_deny_list_blocks' );\n</code></pre>\n<p>In my new javascript file deny-list-blocks.js:</p>\n<pre><code>wp.domReady( function() {\n\n var embed_variations = [\n 'amazon-kindle',\n 'animoto',\n 'cloudup',\n 'collegehumor',\n 'crowdsignal',\n 'dailymotion',\n 'facebook',\n 'flickr',\n 'imgur',\n 'instagram',\n 'issuu',\n 'kickstarter',\n 'meetup-com',\n 'mixcloud',\n 'reddit',\n 'reverbnation',\n 'screencast',\n 'scribd',\n 'slideshare',\n 'smugmug',\n 'soundcloud',\n 'speaker-deck',\n 'spotify',\n 'ted',\n 'tiktok',\n 'tumblr',\n 'twitter',\n 'videopress',\n //'vimeo'\n 'wordpress',\n 'wordpress-tv',\n //'youtube'\n ];\n\n for (var i = embed_variations.length - 1; i >= 0; i--) {\n wp.blocks.unregisterBlockVariation('core/embed', embed_variations[i]);\n }\n} );\n</code></pre>\n<p>Notice that <strong>vimeo</strong> and <strong>youtube</strong> are commented. Nevertheless, it should be a better way to do this, for instance disabling all variations in one line, then enabling only the desired ones.</p>\n<p>Also worth noticing that all themes using the <strong>allowed_block_types</strong> filter to disable embeds will have to be modified when updating wordpress to 5.6.</p>\n"
}
] | 2020/12/10 | [
"https://wordpress.stackexchange.com/questions/379612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32946/"
] | Following up on [this question](https://wordpress.stackexchange.com/q/326959/32946), I want to remove some of the default (core) embed blocks in the WordPress block editor. As of WordPress 5.6, the blocks are no longer available under the `core-embed/*` namespace.
How can I unregister individual core embed blocks? | With WordPress 5.6 ([Gutenberg v8.8.0](https://github.com/WordPress/gutenberg/releases/tag/v8.8.0)), the implementation of the `core-embed/*` blocks changed (see pull request [#24090](https://github.com/WordPress/gutenberg/pull/24090): Refactor embed block to single block with block variations). There are now 43 blocks with block variations of the `core/embed` block.
Available core blocks are:
```html
core/paragraph
core/image
core/heading
core/gallery
core/list
core/quote
core/shortcode
core/archives
core/audio
core/button
core/buttons
core/calendar
core/categories
core/code
core/columns
core/column
core/cover
core/embed
core/file
core/group
core/freeform
core/html
core/media-text
core/latest-comments
core/latest-posts
core/missing
core/more
core/nextpage
core/preformatted
core/pullquote
core/rss
core/search
core/separator
core/block
core/social-links
core/social-link
core/spacer
core/subhead
core/table
core/tag-cloud
core/text-columns
core/verse
core/video
```
Unregister embeds altogether (including variations):
```js
wp.domReady(function () {
wp.blocks.unregisterBlockType('core/embed');
});
```
The blocks previously listed as `core-embed/*` are now available as a variation of `core/embed`:
```js
console.table(wp.blocks.getBlockVariations('core/embed'));
```
Available block variations of `core/embed` are:
```html
amazon-kindle
animoto
cloudup
collegehumor
crowdsignal
dailymotion
facebook
flickr
imgur
instagram
issuu
kickstarter
meetup-com
mixcloud
pinterest
pocketcasts
reddit
reverbnation
screencast
scribd
slideshare
smugmug
soundcloud
speaker-deck
spotify
ted
tiktok
tumblr
twitter
videopress
vimeo
wolfram-cloud
wordpress
wordpress-tv
youtube
```
You can unregister a single variation like this:
```js
wp.domReady(function () {
wp.blocks.unregisterBlockVariation('core/embed', 'twitter');
});
```
Or unregister all variations and only allow individual variations:
```
wp.domReady(function () {
const allowedEmbedBlocks = [
'vimeo',
'youtube',
];
wp.blocks.getBlockVariations('core/embed').forEach(function (blockVariation) {
if (-1 === allowedEmbedBlocks.indexOf(blockVariation.name)) {
wp.blocks.unregisterBlockVariation('core/embed', blockVariation.name);
}
});
});
``` |
379,614 | <p>I want to show users password on the admin profile page. I mean admin can see the other user password. I am using this code. but it shows a password for all user!</p>
<pre class="lang-php prettyprint-override"><code>add_action('show_user_profile', 'extra_user_profile_fields');
add_action('edit_user_profile', 'extra_user_profile_fields');
function extra_user_profile_fields($user)
{
$user_info = get_userdata($user->ID);
$wp_pass = $user_info->user_pass;
if (current_user_can('administrator')) {
?>
<tr>
<th><label for="email"><?php _e("Password"); ?></label></th>
<td>
<input type="text" name="pass" id="pass"
value="<?php $wp_pass; ?>"
class="regular-text"/><br/>
</td>
</tr>
</table>
<?php
}
}
</code></pre>
<p>When I <code>vardump(get_userdata($user->ID))</code> its show all information about the user correctly. but it shows the same user password for all user;</p>
| [
{
"answer_id": 379616,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>I think you cannot get a user password by default as it is stored in a hashed format.\nHowever, you can check the user input against stored passwords with the help of the following function.</p>\n<pre><code>wp_check_password($password, $user->user_pass, $userdata->ID);\n</code></pre>\n"
},
{
"answer_id": 379620,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>This cannot be done, it is not possible, and it would be an awful thing to do if it was. Do not attempt or pursue this.</p>\n<h2>Why It Is Not Possible</h2>\n<p>Passwords are ran through a 1 way hashing function before being stored in the database. This allows us to check if a password matches but we can't undo the hash. To do that, we would need to brute force the password which could take decades or even centuries depending on its length.</p>\n<p>This is so that if the password hash is revealed, it's not possible to then plug it into other sites. Passwords are salted with secret keys before hashing so that\nthose hashes are unique to your site.</p>\n<h2>Legality</h2>\n<p>You might then think we can store the passwords in plaintext, or use a magical unhashing function. In many countries this would be illegal, and grounds for lawsuits.</p>\n<p>For example, in the EU and UK, this would breach numerous data protection and privacy regulations, as well as other laws aimed at preventing negligence.</p>\n<p>You would also fail the various forms of PCI compliance, and any security audits. This would mean any kind of sales on your site would breach consumer laws and regulations across multiple continents.</p>\n<p>On top of that, any of your users who found out could sue for negligent mishandling of personal data.</p>\n<h2>Security</h2>\n<p>This would allow any admin to steal user credentials. Coupled with the fact that users tend to reuse passwords, anybody with elevated access to the site could compromise the emails and other accounts of those users, leading to:</p>\n<ul>\n<li>regulatory action</li>\n<li>bad reputation</li>\n<li>data loss</li>\n<li>lawsuits</li>\n</ul>\n<p>--</p>\n<p>The TLDR:</p>\n<ul>\n<li>passwords are stored as hashes, you can't un-hash the password</li>\n<li>even if you could, it's a dangerous thing to do financially, legally, and heavily compromises your sites security</li>\n<li>If you have users who have forgotten their password, use a reset password email with a link.</li>\n<li>If you want to make logging in easier for your users, and to make account recovery easy, this is not the way to do it. There are industry accepted norms such as Signing in using FB/Google, logging in with a link in an email, password managers, etc, that are all easier and more secure</li>\n</ul>\n"
}
] | 2020/12/10 | [
"https://wordpress.stackexchange.com/questions/379614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149802/"
] | I want to show users password on the admin profile page. I mean admin can see the other user password. I am using this code. but it shows a password for all user!
```php
add_action('show_user_profile', 'extra_user_profile_fields');
add_action('edit_user_profile', 'extra_user_profile_fields');
function extra_user_profile_fields($user)
{
$user_info = get_userdata($user->ID);
$wp_pass = $user_info->user_pass;
if (current_user_can('administrator')) {
?>
<tr>
<th><label for="email"><?php _e("Password"); ?></label></th>
<td>
<input type="text" name="pass" id="pass"
value="<?php $wp_pass; ?>"
class="regular-text"/><br/>
</td>
</tr>
</table>
<?php
}
}
```
When I `vardump(get_userdata($user->ID))` its show all information about the user correctly. but it shows the same user password for all user; | This cannot be done, it is not possible, and it would be an awful thing to do if it was. Do not attempt or pursue this.
Why It Is Not Possible
----------------------
Passwords are ran through a 1 way hashing function before being stored in the database. This allows us to check if a password matches but we can't undo the hash. To do that, we would need to brute force the password which could take decades or even centuries depending on its length.
This is so that if the password hash is revealed, it's not possible to then plug it into other sites. Passwords are salted with secret keys before hashing so that
those hashes are unique to your site.
Legality
--------
You might then think we can store the passwords in plaintext, or use a magical unhashing function. In many countries this would be illegal, and grounds for lawsuits.
For example, in the EU and UK, this would breach numerous data protection and privacy regulations, as well as other laws aimed at preventing negligence.
You would also fail the various forms of PCI compliance, and any security audits. This would mean any kind of sales on your site would breach consumer laws and regulations across multiple continents.
On top of that, any of your users who found out could sue for negligent mishandling of personal data.
Security
--------
This would allow any admin to steal user credentials. Coupled with the fact that users tend to reuse passwords, anybody with elevated access to the site could compromise the emails and other accounts of those users, leading to:
* regulatory action
* bad reputation
* data loss
* lawsuits
--
The TLDR:
* passwords are stored as hashes, you can't un-hash the password
* even if you could, it's a dangerous thing to do financially, legally, and heavily compromises your sites security
* If you have users who have forgotten their password, use a reset password email with a link.
* If you want to make logging in easier for your users, and to make account recovery easy, this is not the way to do it. There are industry accepted norms such as Signing in using FB/Google, logging in with a link in an email, password managers, etc, that are all easier and more secure |
379,812 | <p>Heyho,</p>
<p>I've got a problem getting the post_status of a WP_PostObject which is a Woocommerce-Product.
I get all products doing this query:</p>
<pre><code>$onlineShopProducts = get_posts([
'post_type' => ['product', 'product_variation'],
'orderby' => 'post_title',
'order' => 'ASC',
'numberposts' => -1
]);
</code></pre>
<p>Now I want to filter out all products which are in status draft during a foreach-loop:</p>
<pre><code>foreach ($onlineShopProducts as $onlineShopProduct){
if($onlineShopProduct->post_status != 'publish'){
continue;
}
doSomething($onlineShopProduct)
}
</code></pre>
<p>but $onlineShopProduct->post_status and get_post_status($onlineShopProduct->ID) both return "publish", even tho they are set "Draft" in the product-edit-view... (it's in german)</p>
<p><a href="https://i.stack.imgur.com/S0SY9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S0SY9.png" alt="enter image description here" /></a></p>
<p>is there some sort of post_meta I have to query or is this a know bug of some sort? How can I filter out the drafted products?</p>
<p>Greetings</p>
| [
{
"answer_id": 379616,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>I think you cannot get a user password by default as it is stored in a hashed format.\nHowever, you can check the user input against stored passwords with the help of the following function.</p>\n<pre><code>wp_check_password($password, $user->user_pass, $userdata->ID);\n</code></pre>\n"
},
{
"answer_id": 379620,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>This cannot be done, it is not possible, and it would be an awful thing to do if it was. Do not attempt or pursue this.</p>\n<h2>Why It Is Not Possible</h2>\n<p>Passwords are ran through a 1 way hashing function before being stored in the database. This allows us to check if a password matches but we can't undo the hash. To do that, we would need to brute force the password which could take decades or even centuries depending on its length.</p>\n<p>This is so that if the password hash is revealed, it's not possible to then plug it into other sites. Passwords are salted with secret keys before hashing so that\nthose hashes are unique to your site.</p>\n<h2>Legality</h2>\n<p>You might then think we can store the passwords in plaintext, or use a magical unhashing function. In many countries this would be illegal, and grounds for lawsuits.</p>\n<p>For example, in the EU and UK, this would breach numerous data protection and privacy regulations, as well as other laws aimed at preventing negligence.</p>\n<p>You would also fail the various forms of PCI compliance, and any security audits. This would mean any kind of sales on your site would breach consumer laws and regulations across multiple continents.</p>\n<p>On top of that, any of your users who found out could sue for negligent mishandling of personal data.</p>\n<h2>Security</h2>\n<p>This would allow any admin to steal user credentials. Coupled with the fact that users tend to reuse passwords, anybody with elevated access to the site could compromise the emails and other accounts of those users, leading to:</p>\n<ul>\n<li>regulatory action</li>\n<li>bad reputation</li>\n<li>data loss</li>\n<li>lawsuits</li>\n</ul>\n<p>--</p>\n<p>The TLDR:</p>\n<ul>\n<li>passwords are stored as hashes, you can't un-hash the password</li>\n<li>even if you could, it's a dangerous thing to do financially, legally, and heavily compromises your sites security</li>\n<li>If you have users who have forgotten their password, use a reset password email with a link.</li>\n<li>If you want to make logging in easier for your users, and to make account recovery easy, this is not the way to do it. There are industry accepted norms such as Signing in using FB/Google, logging in with a link in an email, password managers, etc, that are all easier and more secure</li>\n</ul>\n"
}
] | 2020/12/14 | [
"https://wordpress.stackexchange.com/questions/379812",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186068/"
] | Heyho,
I've got a problem getting the post\_status of a WP\_PostObject which is a Woocommerce-Product.
I get all products doing this query:
```
$onlineShopProducts = get_posts([
'post_type' => ['product', 'product_variation'],
'orderby' => 'post_title',
'order' => 'ASC',
'numberposts' => -1
]);
```
Now I want to filter out all products which are in status draft during a foreach-loop:
```
foreach ($onlineShopProducts as $onlineShopProduct){
if($onlineShopProduct->post_status != 'publish'){
continue;
}
doSomething($onlineShopProduct)
}
```
but $onlineShopProduct->post\_status and get\_post\_status($onlineShopProduct->ID) both return "publish", even tho they are set "Draft" in the product-edit-view... (it's in german)
[](https://i.stack.imgur.com/S0SY9.png)
is there some sort of post\_meta I have to query or is this a know bug of some sort? How can I filter out the drafted products?
Greetings | This cannot be done, it is not possible, and it would be an awful thing to do if it was. Do not attempt or pursue this.
Why It Is Not Possible
----------------------
Passwords are ran through a 1 way hashing function before being stored in the database. This allows us to check if a password matches but we can't undo the hash. To do that, we would need to brute force the password which could take decades or even centuries depending on its length.
This is so that if the password hash is revealed, it's not possible to then plug it into other sites. Passwords are salted with secret keys before hashing so that
those hashes are unique to your site.
Legality
--------
You might then think we can store the passwords in plaintext, or use a magical unhashing function. In many countries this would be illegal, and grounds for lawsuits.
For example, in the EU and UK, this would breach numerous data protection and privacy regulations, as well as other laws aimed at preventing negligence.
You would also fail the various forms of PCI compliance, and any security audits. This would mean any kind of sales on your site would breach consumer laws and regulations across multiple continents.
On top of that, any of your users who found out could sue for negligent mishandling of personal data.
Security
--------
This would allow any admin to steal user credentials. Coupled with the fact that users tend to reuse passwords, anybody with elevated access to the site could compromise the emails and other accounts of those users, leading to:
* regulatory action
* bad reputation
* data loss
* lawsuits
--
The TLDR:
* passwords are stored as hashes, you can't un-hash the password
* even if you could, it's a dangerous thing to do financially, legally, and heavily compromises your sites security
* If you have users who have forgotten their password, use a reset password email with a link.
* If you want to make logging in easier for your users, and to make account recovery easy, this is not the way to do it. There are industry accepted norms such as Signing in using FB/Google, logging in with a link in an email, password managers, etc, that are all easier and more secure |
379,824 | <p>I want to paginate through all users in a WP site in groups of 100. The code below is a simplified version:</p>
<pre><code>for($offset = 0; $offset < 100; $offset++)
$args = ["number" => 100, 'orderby' => 'ID'];
$args['offset'] = ($offset - 1) * (int) $args['number'];
$users = get_users($args);
//Do Stuff with $users
}
</code></pre>
<p>The issue is that I seem to be skipping over some Users. I've logged the User IDs from the loop and checked them against the Users section in the dashboard, I can find User IDs that don't appear in the logs but do appear in Users.</p>
<p>I'm aware there is also a 'paged' parameter but I got the same result when using it.</p>
<p>Anyone seen anything like this before?</p>
| [
{
"answer_id": 379825,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Your problem is a basic PHP problem. You're only looping over the even numbers, 0, 2, 4, 6</p>\n<p>This is because at the end of every loop <code>$offset</code> increases by 1:</p>\n<pre class=\"lang-php prettyprint-override\"><code>for($offset = 0; $offset < 100; $offset++)\n</code></pre>\n<p>But then for some reason it also gets incremented before the loop ends:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$offset++;\n</code></pre>\n<p>So offset is incremented by 2, and half the values are skipped</p>\n"
},
{
"answer_id": 379992,
"author": "Colin",
"author_id": 112964,
"author_profile": "https://wordpress.stackexchange.com/users/112964",
"pm_score": 0,
"selected": false,
"text": "<p>We ran this code a number of times and we were unable to narrow it down. We hypothesize that it is being caused by some custom caching or SQL limiting mechanism in the hosting company as the User table is quite large (14k records) Or, alternatively, another plugin is hooking the get_user /DB query.</p>\n<p>We eventually wrote a raw query that is based on the User ID:</p>\n<pre><code>$users = $wpdb->get_results("SELECT ID FROM $wpdb->users WHERE ID > $maxUserId ORDER BY ID ASC LIMIT 50");\n</code></pre>\n<p>Where $maxUserId is a variable we store after each run which stores the highest User ID seen in a given result set. Therefore, on each run, we get the next batch of user IDs which is effectively pagination.</p>\n<p>It's not a good solution but it's the only one we found, for this given use case, that would guarantee us seeing each and every User ID in the database.</p>\n"
}
] | 2020/12/14 | [
"https://wordpress.stackexchange.com/questions/379824",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112964/"
] | I want to paginate through all users in a WP site in groups of 100. The code below is a simplified version:
```
for($offset = 0; $offset < 100; $offset++)
$args = ["number" => 100, 'orderby' => 'ID'];
$args['offset'] = ($offset - 1) * (int) $args['number'];
$users = get_users($args);
//Do Stuff with $users
}
```
The issue is that I seem to be skipping over some Users. I've logged the User IDs from the loop and checked them against the Users section in the dashboard, I can find User IDs that don't appear in the logs but do appear in Users.
I'm aware there is also a 'paged' parameter but I got the same result when using it.
Anyone seen anything like this before? | Your problem is a basic PHP problem. You're only looping over the even numbers, 0, 2, 4, 6
This is because at the end of every loop `$offset` increases by 1:
```php
for($offset = 0; $offset < 100; $offset++)
```
But then for some reason it also gets incremented before the loop ends:
```php
$offset++;
```
So offset is incremented by 2, and half the values are skipped |
379,856 | <p>we can use</p>
<pre><code>$user = wp_get_current_user();
if ( !in_array( 'administrator', (array) $user->roles ) )
</code></pre>
<p>to get the user role of the viewer. but i want to ignore who views. i want to get who writes the post. need something like</p>
<pre><code>$user = wp_get_post_author();
if ( !in_array( 'administrator', (array) $user->roles ) )
</code></pre>
<p>so that i can show results depending on the user who writes the post while ignoring who views that.</p>
| [
{
"answer_id": 379864,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": false,
"text": "<p>You can find the author's ID on the post and fetch their user object from that with get_userdata(), e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$author = get_userdata( get_post()->post_author ) ;\nif ( !in_array( 'administrator', (array) $author->roles ) ) { ... }\n</code></pre>\n"
},
{
"answer_id": 379874,
"author": "ZealousWeb",
"author_id": 70780,
"author_profile": "https://wordpress.stackexchange.com/users/70780",
"pm_score": 0,
"selected": false,
"text": "<p>Retrieve the current user object from the wp_get_current_user() and then check administrator role in in_array.</p>\n<pre><code>$user = wp_get_current_user();\nif ( in_array( 'administrator', (array) $user->roles ) ) {\n //The user has the "administrator" role\n}\n</code></pre>\n<p>Here I have shared the link for <a href=\"https://developer.wordpress.org/reference/functions/wp_get_current_user/\" rel=\"nofollow noreferrer\">wp_get_current_user()</a> and <a href=\"https://www.w3schools.com/php/func_array_in_array.asp\" rel=\"nofollow noreferrer\">in_array()</a> for better understanding.</p>\n"
},
{
"answer_id": 379936,
"author": "Abdullah Al Muaz",
"author_id": 198121,
"author_profile": "https://wordpress.stackexchange.com/users/198121",
"pm_score": 1,
"selected": false,
"text": "<p>I tried so hard and got so far\nBut in the end it doesn't even matter</p>\n<pre><code>$post_id = get_queried_object_id();\n$author_ID = get_post_field( 'post_author', $post_id );\n$authorData = get_userdata( $author_ID );\nif ( !in_array( 'administrator', $authorData->roles)){... ...}\n</code></pre>\n"
}
] | 2020/12/15 | [
"https://wordpress.stackexchange.com/questions/379856",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198121/"
] | we can use
```
$user = wp_get_current_user();
if ( !in_array( 'administrator', (array) $user->roles ) )
```
to get the user role of the viewer. but i want to ignore who views. i want to get who writes the post. need something like
```
$user = wp_get_post_author();
if ( !in_array( 'administrator', (array) $user->roles ) )
```
so that i can show results depending on the user who writes the post while ignoring who views that. | You can find the author's ID on the post and fetch their user object from that with get\_userdata(), e.g.
```php
$author = get_userdata( get_post()->post_author ) ;
if ( !in_array( 'administrator', (array) $author->roles ) ) { ... }
``` |
379,861 | <p>Do any of you know a way to check if the current page is the permalink admin page?</p>
| [
{
"answer_id": 379865,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 1,
"selected": false,
"text": "<p>Try below lines into your function.</p>\n<pre><code>global $pagenow;\necho $pagenow; // This should give you current page of admin page\n</code></pre>\n"
},
{
"answer_id": 379875,
"author": "Gabriel Borges",
"author_id": 186694,
"author_profile": "https://wordpress.stackexchange.com/users/186694",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know exactly what you want to do. But basically, you can use:</p>\n<p><code>is_page( 'contact' ) // To see if this page is the page contact</code></p>\n<p><code>is_singular( 'post' ) // To see if this is a spefic post type</code></p>\n<p><code>get_permalink() // To get the permalink of a post inside the loop</code></p>\n<p><code>global $pagenow // To get the page you are now</code></p>\n<p>If you explain better what you want, it is easier to offer a better answer.</p>\n"
},
{
"answer_id": 379879,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n// 'current_screen' action fires after the current screen has been set\nadd_action( 'current_screen', 'my_check_current_screen' );\n\n// $current_screen is WP_Screen object passed by the 'current_screen' action\nfunction my_check_current_screen( $current_screen ) {\n\n // compare current screen ID to the string of your choice\n if( 'options-permalink' === $current_screen->id ) {\n echo 'I am on the "Permalink Settings" screen';\n }\n}\n</code></pre>\n<p>You can check what you can play with using the <code>'current_screen'</code> action instead of <code>global $pagenow</code>:</p>\n<pre><code>add_action( 'current_screen', 'my_print_current_screen_object' );\n\nfunction my_print_current_screen_object( $current_screen ) {\n\n echo '<pre>';\n print_r( $current_screen );\n echo '</pre>';\n\n}\n</code></pre>\n"
}
] | 2020/12/15 | [
"https://wordpress.stackexchange.com/questions/379861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199010/"
] | Do any of you know a way to check if the current page is the permalink admin page? | ```
<?php
// 'current_screen' action fires after the current screen has been set
add_action( 'current_screen', 'my_check_current_screen' );
// $current_screen is WP_Screen object passed by the 'current_screen' action
function my_check_current_screen( $current_screen ) {
// compare current screen ID to the string of your choice
if( 'options-permalink' === $current_screen->id ) {
echo 'I am on the "Permalink Settings" screen';
}
}
```
You can check what you can play with using the `'current_screen'` action instead of `global $pagenow`:
```
add_action( 'current_screen', 'my_print_current_screen_object' );
function my_print_current_screen_object( $current_screen ) {
echo '<pre>';
print_r( $current_screen );
echo '</pre>';
}
``` |
379,870 | <p>I have installed different sites through my admin panel as below screenshot.</p>
<p><a href="https://i.stack.imgur.com/k9XKD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k9XKD.png" alt="enter image description here" /></a></p>
<p>But when I click any of the menus of My Sites it is redirected to the wrong URL like,</p>
<ul>
<li><code>https://www.example.comwp-admin/netowrd</code> instead of <code>https://www.example.com/wp-admin/netowrd</code></li>
<li><code>https://www.example.comwp-admin/netowrd/sites.php</code> instead of <code>https://www.example.com/wp-admin/netowrd/sites.php</code></li>
</ul>
<blockquote>
<p>Problem is happening only with this menu.</p>
</blockquote>
<p>Means slash is removed automatically after domain or before wp-admin.</p>
<p>Why this is happening? How to fix it?</p>
| [
{
"answer_id": 379945,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<p>In your database, check the values of the options in <code>wp_options</code>. I haven't used multisite in a while, but you should make sure that the <code>siteurl</code> and <code>home</code> options have slashes on the end of the URL and see if that fixes it.</p>\n"
},
{
"answer_id": 400601,
"author": "Bronson Quick",
"author_id": 217207,
"author_profile": "https://wordpress.stackexchange.com/users/217207",
"pm_score": 1,
"selected": false,
"text": "<p>I just hit this issue as well and realised I had:</p>\n<pre><code>define( 'PATH_CURRENT_SITE', '' );\n</code></pre>\n<p>in one of my configs and it should've been:</p>\n<pre><code>define( 'PATH_CURRENT_SITE', '/' );\n</code></pre>\n"
}
] | 2020/12/15 | [
"https://wordpress.stackexchange.com/questions/379870",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185810/"
] | I have installed different sites through my admin panel as below screenshot.
[](https://i.stack.imgur.com/k9XKD.png)
But when I click any of the menus of My Sites it is redirected to the wrong URL like,
* `https://www.example.comwp-admin/netowrd` instead of `https://www.example.com/wp-admin/netowrd`
* `https://www.example.comwp-admin/netowrd/sites.php` instead of `https://www.example.com/wp-admin/netowrd/sites.php`
>
> Problem is happening only with this menu.
>
>
>
Means slash is removed automatically after domain or before wp-admin.
Why this is happening? How to fix it? | I just hit this issue as well and realised I had:
```
define( 'PATH_CURRENT_SITE', '' );
```
in one of my configs and it should've been:
```
define( 'PATH_CURRENT_SITE', '/' );
``` |
379,894 | <p>I created a Gutenberg block but after saving it and going back into the post I receive this error:</p>
<blockquote>
<p>This block contains unexpected or invalid content</p>
</blockquote>
<p>I couldn't find any inconsistencies and I had a friend also take a look over to see if there was anything amiss. What am I doing wrong?</p>
<pre><code>registerBlockType('myblog/check-list', {
//Built-in Attributes
title: 'Check List',
description: 'Generate a bulleted list with green checkmarks',
icon: 'list-view',
category: 'design',
//Custom Attributes
attributes: {
title: {
type: 'string',
source: 'html',
selector: 'h2'
},
text: {
type: 'string',
source: 'html',
selector: 'p'
},
titleColor: {
type: 'string',
default: '#383838'
},
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'span'
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'span'
}
},
//Built-in Functions
edit({attributes, setAttributes}) {
const{
title,
text,
titleColor,
checkListItemOne,
checkListItemTwo,
} = attributes;
//Custom Functions
function onChangeTitle(newTitle) {
setAttributes( { title: newTitle } );
}
function onChangeText(newText) {
setAttributes( { text: newText } );
}
function onTitleColorChange(newColor){
setAttributes( { titleColor: newColor } );
}
function onChangeCheckListItemOne(newListItemOne) {
setAttributes( { checkListItemOne: newListItemOne})
}
function onChangeCheckListItemTwo(newListItemTwo) {
setAttributes( { checkListItemTwo: newListItemTwo})
}
return ([
<InspectorControls style={ { marginBottom: '40px' } }>
<PanelBody title={ 'Headline Color' }>
<p><strong>Choose Title Color</strong></p>
<ColorPalette
value={titleColor}
onChange={onTitleColorChange}
/>
</PanelBody>
</InspectorControls>,
<div class="col-md-5 offset-md-1">
<div class="green-check-list-container">
<RichText
key="editable"
tagName="h2"
placeholder="Headline for check list"
value= { title }
onChange= { onChangeTitle }
style= { { color: titleColor } }
/>
<RichText
key="editable"
tagName="p"
placeholder="Additional context for the list"
value= { text }
onChange= { onChangeText }
/>
<ul class="green-check-list-items">
<li>
<RichText
key="editable"
tagName="span"
placeholder="List Item"
value= { checkListItemOne }
onChange= { onChangeCheckListItemOne }
/>
</li>
<li>
<RichText
key="editable"
tagName="span"
placeholder="List Item"
value= { checkListItemTwo }
onChange= { onChangeCheckListItemTwo }
/>
</li>
</ul>
</div>
</div>
]);
},
save({ attributes }) {
const {
title,
text,
titleColor,
checkListItemOne,
checkListItemTwo,
} = attributes;
return (
<div class="col-md-5 offset-md-1">
<div class="green-check-list-container">
<h2 style={ { color: titleColor } }>{title}</h2>
<p>{ text }</p>
<ul class="green-check-list-items">
<li>
<span>{ checkListItemOne }</span>
</li>
<li>
<span>{ checkListItemTwo }</span>
</li>
</ul>
</div>
</div>
);
}
});
</code></pre>
| [
{
"answer_id": 379899,
"author": "Eugene Poluhovich",
"author_id": 197239,
"author_profile": "https://wordpress.stackexchange.com/users/197239",
"pm_score": 1,
"selected": false,
"text": "<p>You can check the WordPress Core file source and try to understand why this error appears, just search for the error message here:</p>\n<p><a href=\"https://raw.githubusercontent.com/WordPress/WordPress/master/wp-includes/js/dist/block-editor.js\" rel=\"nofollow noreferrer\">https://raw.githubusercontent.com/WordPress/WordPress/master/wp-includes/js/dist/block-editor.js</a></p>\n<p>From my point of view, there is might be a problem with using custom HTML elements. Try to replace all custom HTML with casual <code><div></code> and see what will happen. If that error is gone, then the source is these elements.</p>\n"
},
{
"answer_id": 381210,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p>The main issue in your code is with these two attributes which use the exact same selector (the <em>first</em> <code>span</code> element in your block content):</p>\n<pre class=\"lang-js prettyprint-override\"><code>checkListItemOne: {\n type: 'string',\n source: 'html',\n selector: 'span' // same as below\n},\ncheckListItemTwo: {\n type: 'string',\n source: 'html',\n selector: 'span' // same as above\n}\n</code></pre>\n<p>Which means the block editor will always use the content of the <em>first</em> <code>span</code> element in the <em>saved</em> block content, which then results in a "block validation failed" error like so:</p>\n<p><a href=\"https://i.stack.imgur.com/ltQlH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RGvbi.png\" alt=\"enter image description here\" /></a></p>\n<p>Therefore, make sure that you set the proper <code>selector</code> value for your block attributes. Here's an example using the CSS selectors <code>element > element</code> and <code>:nth-child(n)</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>checkListItemOne: {\n type: 'string',\n source: 'html',\n selector: 'li:nth-child(1) > span'\n},\ncheckListItemTwo: {\n type: 'string',\n source: 'html',\n selector: 'li:nth-child(2) > span'\n}\n</code></pre>\n<h2>Additional Issues/Notes</h2>\n<ol>\n<li><p>The block editor handbook <a href=\"https://developer.wordpress.org/block-editor/developers/richtext/#html-formatting-tags-display-in-the-content\" rel=\"nofollow noreferrer\">says</a>:</p>\n<blockquote>\n<h3>HTML Formatting Tags Display in the Content</h3>\n<p>If the HTML tags from text formatting such as <code><strong></code> or <code><em></code> are\nbeing escaped and displayed on the frontend of the site, this is\nlikely due to an issue in your save function. Make sure your code\nlooks something like <code><RichText.Content tagName="h2" value={ heading } /></code> (ESNext) within your save function instead of simply outputting\nthe value with <code><h2>{ heading }</h2></code>.</p>\n</blockquote>\n<p>So for example in your case, you'd use this instead of <code><span>{ checkListItemOne }</span></code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code><RichText.Content tagName="span" value={ checkListItemOne } />\n</code></pre>\n</li>\n<li><p>If you look at the above screenshot, the block's outmost wrapper has two <code>class</code> attributes, which results in the "Expected attribute <code>class</code> of value `..." notice:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div class="col-md-5 offset-md-1" class="wp-block-myblog-check-list">\n</code></pre>\n<p>To fix that, use the <code>className</code> attribute and not <code>class</code> in your <code><div></code>:</p>\n<p>And although <code>class</code> does work (despite being a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_keywords_as_of_ecmascript_2015\" rel=\"nofollow noreferrer\">reserved keyword in JavaScript</a>), the (current) React documentation actually <a href=\"https://reactjs.org/docs/dom-elements.html#classname\" rel=\"nofollow noreferrer\">says</a>, "<em>To specify a CSS class, use the <code>className</code> attribute.</em>", so you should use that attribute in all your <code><div></code> and other elements having a CSS class.</p>\n<pre class=\"lang-js prettyprint-override\"><code>return (\n <div className="col-md-5 offset-md-1">\n <div className="green-check-list-container">\n ... your code.\n </div>\n </div>\n);\n</code></pre>\n</li>\n<li><p>WordPress 5.6.0 uses <a href=\"https://make.wordpress.org/core/2020/11/18/block-api-version-2/\" rel=\"nofollow noreferrer\">block editor API version 2</a> which introduced a new hook named <code>useBlockProps</code>, so I suggest you to use it in your block's <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/\" rel=\"nofollow noreferrer\"><code>edit</code> and <code>save</code></a> callbacks. :)</p>\n<p>Example in your <code>save</code> callback:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const blockProps = useBlockProps.save( { className: 'col-md-5 offset-md-1' } );\n\nreturn (\n <div { ...blockProps }>\n <div className="green-check-list-container">\n ... your code.\n </div>\n </div>\n);\n</code></pre>\n</li>\n</ol>\n"
}
] | 2020/12/15 | [
"https://wordpress.stackexchange.com/questions/379894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114269/"
] | I created a Gutenberg block but after saving it and going back into the post I receive this error:
>
> This block contains unexpected or invalid content
>
>
>
I couldn't find any inconsistencies and I had a friend also take a look over to see if there was anything amiss. What am I doing wrong?
```
registerBlockType('myblog/check-list', {
//Built-in Attributes
title: 'Check List',
description: 'Generate a bulleted list with green checkmarks',
icon: 'list-view',
category: 'design',
//Custom Attributes
attributes: {
title: {
type: 'string',
source: 'html',
selector: 'h2'
},
text: {
type: 'string',
source: 'html',
selector: 'p'
},
titleColor: {
type: 'string',
default: '#383838'
},
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'span'
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'span'
}
},
//Built-in Functions
edit({attributes, setAttributes}) {
const{
title,
text,
titleColor,
checkListItemOne,
checkListItemTwo,
} = attributes;
//Custom Functions
function onChangeTitle(newTitle) {
setAttributes( { title: newTitle } );
}
function onChangeText(newText) {
setAttributes( { text: newText } );
}
function onTitleColorChange(newColor){
setAttributes( { titleColor: newColor } );
}
function onChangeCheckListItemOne(newListItemOne) {
setAttributes( { checkListItemOne: newListItemOne})
}
function onChangeCheckListItemTwo(newListItemTwo) {
setAttributes( { checkListItemTwo: newListItemTwo})
}
return ([
<InspectorControls style={ { marginBottom: '40px' } }>
<PanelBody title={ 'Headline Color' }>
<p><strong>Choose Title Color</strong></p>
<ColorPalette
value={titleColor}
onChange={onTitleColorChange}
/>
</PanelBody>
</InspectorControls>,
<div class="col-md-5 offset-md-1">
<div class="green-check-list-container">
<RichText
key="editable"
tagName="h2"
placeholder="Headline for check list"
value= { title }
onChange= { onChangeTitle }
style= { { color: titleColor } }
/>
<RichText
key="editable"
tagName="p"
placeholder="Additional context for the list"
value= { text }
onChange= { onChangeText }
/>
<ul class="green-check-list-items">
<li>
<RichText
key="editable"
tagName="span"
placeholder="List Item"
value= { checkListItemOne }
onChange= { onChangeCheckListItemOne }
/>
</li>
<li>
<RichText
key="editable"
tagName="span"
placeholder="List Item"
value= { checkListItemTwo }
onChange= { onChangeCheckListItemTwo }
/>
</li>
</ul>
</div>
</div>
]);
},
save({ attributes }) {
const {
title,
text,
titleColor,
checkListItemOne,
checkListItemTwo,
} = attributes;
return (
<div class="col-md-5 offset-md-1">
<div class="green-check-list-container">
<h2 style={ { color: titleColor } }>{title}</h2>
<p>{ text }</p>
<ul class="green-check-list-items">
<li>
<span>{ checkListItemOne }</span>
</li>
<li>
<span>{ checkListItemTwo }</span>
</li>
</ul>
</div>
</div>
);
}
});
``` | The main issue in your code is with these two attributes which use the exact same selector (the *first* `span` element in your block content):
```js
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'span' // same as below
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'span' // same as above
}
```
Which means the block editor will always use the content of the *first* `span` element in the *saved* block content, which then results in a "block validation failed" error like so:
[](https://i.stack.imgur.com/ltQlH.png)
Therefore, make sure that you set the proper `selector` value for your block attributes. Here's an example using the CSS selectors `element > element` and `:nth-child(n)`:
```js
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'li:nth-child(1) > span'
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'li:nth-child(2) > span'
}
```
Additional Issues/Notes
-----------------------
1. The block editor handbook [says](https://developer.wordpress.org/block-editor/developers/richtext/#html-formatting-tags-display-in-the-content):
>
> ### HTML Formatting Tags Display in the Content
>
>
> If the HTML tags from text formatting such as `<strong>` or `<em>` are
> being escaped and displayed on the frontend of the site, this is
> likely due to an issue in your save function. Make sure your code
> looks something like `<RichText.Content tagName="h2" value={ heading } />` (ESNext) within your save function instead of simply outputting
> the value with `<h2>{ heading }</h2>`.
>
>
>
So for example in your case, you'd use this instead of `<span>{ checkListItemOne }</span>`:
```js
<RichText.Content tagName="span" value={ checkListItemOne } />
```
2. If you look at the above screenshot, the block's outmost wrapper has two `class` attributes, which results in the "Expected attribute `class` of value `..." notice:
```html
<div class="col-md-5 offset-md-1" class="wp-block-myblog-check-list">
```
To fix that, use the `className` attribute and not `class` in your `<div>`:
And although `class` does work (despite being a [reserved keyword in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_keywords_as_of_ecmascript_2015)), the (current) React documentation actually [says](https://reactjs.org/docs/dom-elements.html#classname), "*To specify a CSS class, use the `className` attribute.*", so you should use that attribute in all your `<div>` and other elements having a CSS class.
```js
return (
<div className="col-md-5 offset-md-1">
<div className="green-check-list-container">
... your code.
</div>
</div>
);
```
3. WordPress 5.6.0 uses [block editor API version 2](https://make.wordpress.org/core/2020/11/18/block-api-version-2/) which introduced a new hook named `useBlockProps`, so I suggest you to use it in your block's [`edit` and `save`](https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/) callbacks. :)
Example in your `save` callback:
```js
const blockProps = useBlockProps.save( { className: 'col-md-5 offset-md-1' } );
return (
<div { ...blockProps }>
<div className="green-check-list-container">
... your code.
</div>
</div>
);
``` |
380,062 | <p>Please guys</p>
<p>I need help on how to remove special characters in POST TITLE -</p>
<p>Certain SYMBOLS LIKE < > { }</p>
<p>Please Note: I am a beginner coder, kindly make the solution very simple for me to understand</p>
| [
{
"answer_id": 379899,
"author": "Eugene Poluhovich",
"author_id": 197239,
"author_profile": "https://wordpress.stackexchange.com/users/197239",
"pm_score": 1,
"selected": false,
"text": "<p>You can check the WordPress Core file source and try to understand why this error appears, just search for the error message here:</p>\n<p><a href=\"https://raw.githubusercontent.com/WordPress/WordPress/master/wp-includes/js/dist/block-editor.js\" rel=\"nofollow noreferrer\">https://raw.githubusercontent.com/WordPress/WordPress/master/wp-includes/js/dist/block-editor.js</a></p>\n<p>From my point of view, there is might be a problem with using custom HTML elements. Try to replace all custom HTML with casual <code><div></code> and see what will happen. If that error is gone, then the source is these elements.</p>\n"
},
{
"answer_id": 381210,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p>The main issue in your code is with these two attributes which use the exact same selector (the <em>first</em> <code>span</code> element in your block content):</p>\n<pre class=\"lang-js prettyprint-override\"><code>checkListItemOne: {\n type: 'string',\n source: 'html',\n selector: 'span' // same as below\n},\ncheckListItemTwo: {\n type: 'string',\n source: 'html',\n selector: 'span' // same as above\n}\n</code></pre>\n<p>Which means the block editor will always use the content of the <em>first</em> <code>span</code> element in the <em>saved</em> block content, which then results in a "block validation failed" error like so:</p>\n<p><a href=\"https://i.stack.imgur.com/ltQlH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RGvbi.png\" alt=\"enter image description here\" /></a></p>\n<p>Therefore, make sure that you set the proper <code>selector</code> value for your block attributes. Here's an example using the CSS selectors <code>element > element</code> and <code>:nth-child(n)</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>checkListItemOne: {\n type: 'string',\n source: 'html',\n selector: 'li:nth-child(1) > span'\n},\ncheckListItemTwo: {\n type: 'string',\n source: 'html',\n selector: 'li:nth-child(2) > span'\n}\n</code></pre>\n<h2>Additional Issues/Notes</h2>\n<ol>\n<li><p>The block editor handbook <a href=\"https://developer.wordpress.org/block-editor/developers/richtext/#html-formatting-tags-display-in-the-content\" rel=\"nofollow noreferrer\">says</a>:</p>\n<blockquote>\n<h3>HTML Formatting Tags Display in the Content</h3>\n<p>If the HTML tags from text formatting such as <code><strong></code> or <code><em></code> are\nbeing escaped and displayed on the frontend of the site, this is\nlikely due to an issue in your save function. Make sure your code\nlooks something like <code><RichText.Content tagName="h2" value={ heading } /></code> (ESNext) within your save function instead of simply outputting\nthe value with <code><h2>{ heading }</h2></code>.</p>\n</blockquote>\n<p>So for example in your case, you'd use this instead of <code><span>{ checkListItemOne }</span></code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code><RichText.Content tagName="span" value={ checkListItemOne } />\n</code></pre>\n</li>\n<li><p>If you look at the above screenshot, the block's outmost wrapper has two <code>class</code> attributes, which results in the "Expected attribute <code>class</code> of value `..." notice:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div class="col-md-5 offset-md-1" class="wp-block-myblog-check-list">\n</code></pre>\n<p>To fix that, use the <code>className</code> attribute and not <code>class</code> in your <code><div></code>:</p>\n<p>And although <code>class</code> does work (despite being a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_keywords_as_of_ecmascript_2015\" rel=\"nofollow noreferrer\">reserved keyword in JavaScript</a>), the (current) React documentation actually <a href=\"https://reactjs.org/docs/dom-elements.html#classname\" rel=\"nofollow noreferrer\">says</a>, "<em>To specify a CSS class, use the <code>className</code> attribute.</em>", so you should use that attribute in all your <code><div></code> and other elements having a CSS class.</p>\n<pre class=\"lang-js prettyprint-override\"><code>return (\n <div className="col-md-5 offset-md-1">\n <div className="green-check-list-container">\n ... your code.\n </div>\n </div>\n);\n</code></pre>\n</li>\n<li><p>WordPress 5.6.0 uses <a href=\"https://make.wordpress.org/core/2020/11/18/block-api-version-2/\" rel=\"nofollow noreferrer\">block editor API version 2</a> which introduced a new hook named <code>useBlockProps</code>, so I suggest you to use it in your block's <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/\" rel=\"nofollow noreferrer\"><code>edit</code> and <code>save</code></a> callbacks. :)</p>\n<p>Example in your <code>save</code> callback:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const blockProps = useBlockProps.save( { className: 'col-md-5 offset-md-1' } );\n\nreturn (\n <div { ...blockProps }>\n <div className="green-check-list-container">\n ... your code.\n </div>\n </div>\n);\n</code></pre>\n</li>\n</ol>\n"
}
] | 2020/12/18 | [
"https://wordpress.stackexchange.com/questions/380062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181855/"
] | Please guys
I need help on how to remove special characters in POST TITLE -
Certain SYMBOLS LIKE < > { }
Please Note: I am a beginner coder, kindly make the solution very simple for me to understand | The main issue in your code is with these two attributes which use the exact same selector (the *first* `span` element in your block content):
```js
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'span' // same as below
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'span' // same as above
}
```
Which means the block editor will always use the content of the *first* `span` element in the *saved* block content, which then results in a "block validation failed" error like so:
[](https://i.stack.imgur.com/ltQlH.png)
Therefore, make sure that you set the proper `selector` value for your block attributes. Here's an example using the CSS selectors `element > element` and `:nth-child(n)`:
```js
checkListItemOne: {
type: 'string',
source: 'html',
selector: 'li:nth-child(1) > span'
},
checkListItemTwo: {
type: 'string',
source: 'html',
selector: 'li:nth-child(2) > span'
}
```
Additional Issues/Notes
-----------------------
1. The block editor handbook [says](https://developer.wordpress.org/block-editor/developers/richtext/#html-formatting-tags-display-in-the-content):
>
> ### HTML Formatting Tags Display in the Content
>
>
> If the HTML tags from text formatting such as `<strong>` or `<em>` are
> being escaped and displayed on the frontend of the site, this is
> likely due to an issue in your save function. Make sure your code
> looks something like `<RichText.Content tagName="h2" value={ heading } />` (ESNext) within your save function instead of simply outputting
> the value with `<h2>{ heading }</h2>`.
>
>
>
So for example in your case, you'd use this instead of `<span>{ checkListItemOne }</span>`:
```js
<RichText.Content tagName="span" value={ checkListItemOne } />
```
2. If you look at the above screenshot, the block's outmost wrapper has two `class` attributes, which results in the "Expected attribute `class` of value `..." notice:
```html
<div class="col-md-5 offset-md-1" class="wp-block-myblog-check-list">
```
To fix that, use the `className` attribute and not `class` in your `<div>`:
And although `class` does work (despite being a [reserved keyword in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_keywords_as_of_ecmascript_2015)), the (current) React documentation actually [says](https://reactjs.org/docs/dom-elements.html#classname), "*To specify a CSS class, use the `className` attribute.*", so you should use that attribute in all your `<div>` and other elements having a CSS class.
```js
return (
<div className="col-md-5 offset-md-1">
<div className="green-check-list-container">
... your code.
</div>
</div>
);
```
3. WordPress 5.6.0 uses [block editor API version 2](https://make.wordpress.org/core/2020/11/18/block-api-version-2/) which introduced a new hook named `useBlockProps`, so I suggest you to use it in your block's [`edit` and `save`](https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/) callbacks. :)
Example in your `save` callback:
```js
const blockProps = useBlockProps.save( { className: 'col-md-5 offset-md-1' } );
return (
<div { ...blockProps }>
<div className="green-check-list-container">
... your code.
</div>
</div>
);
``` |
380,078 | <p>I am trying to work on my child theme, but I can't get rid of the <code>filemtime(): stat failed</code> warning, which appeared as soon as I activated my child theme.
After reading other questions, I understand that the filemtime warning is often caused by incorrect use of URLs and paths. However, I think I provided URLs and paths correctly, and if that's the case, then there is something else I'm missing.</p>
<p>This function is from the parent theme:</p>
<pre><code>function mtt_styles()
{
wp_enqueue_style(
'mtt-custom-style',
get_stylesheet_directory_uri() . '/dist/css/custom-style.css',
false,
filemtime(get_stylesheet_directory() . '/dist/css/custom-style.css'),
'all'
);
wp_enqueue_style('mtt-main-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'mtt_styles');
</code></pre>
<p>This is from my child theme:</p>
<pre><code>function child_styles()
{
$theme = wp_get_theme();
wp_enqueue_style(
'mtt-custom-style',
get_template_directory_uri() . '/dist/css/custom-style.css',
array(),
filemtime(get_template_directory() . '/dist/css/custom-style.css'),
'all'
);
wp_enqueue_style(
'mtt-main-style',
get_template_directory_uri() . '/style.css',
array(),
$theme->parent()->get('Version'),
'all'
);
wp_enqueue_style(
'child-main-style',
get_stylesheet_uri(),
array('mtt-custom-style', 'mtt-main-style'));
}
add_action('wp_enqueue_scripts', 'child_styles');
</code></pre>
<p>When I go to the page source, I see that the enqueueing worked. All the files are there, and all the styles from the parent theme work well within the child, but the warning remains.</p>
<p>Could someone help me spot what I am missing or doing wrong here?</p>
| [
{
"answer_id": 380080,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>The problem is in your parent theme. The parent theme is using <code>get_stylesheet_directory()</code> here:</p>\n<pre><code>filemtime(get_stylesheet_directory() . '/dist/css/custom-style.css'),\n</code></pre>\n<p>When the parent theme is active, that's fine, because <code>get_stylesheet_directory()</code> will point that file in the parent theme. The problem is that when you activate a child theme, it is trying to get the <code>filemtime()</code> of <code>'/dist/css/custom-style.css'</code> in your <em>child theme</em>, and I'm guessing that this file doesn't exist there. Hence the failure.</p>\n<p>The issue is that because <code>filemtime()</code> is run right away, it doesn't matter if you re-define the script's URL, or dequeue it, because it's already tried and failed to check the time, throwing the error.</p>\n<p>If you're the author of the parent theme, then fixing the issue is as simple has replacing <code>get_stylesheet_directory()</code> with <code>get_template_directory_uri()</code> (or better yet, <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file_path()</code></a>). Then the error won't occur when loading a stylesheet that's missing that file, and you won't need to re-eneueue it from that child theme.</p>\n<p>If you're not the original author, then the right solution would be to just unhook <code>mtt_styles()</code> from <code>wp_enqueue_scripts</code> entirely. Then from the child theme just re-enqueue them using the correct path. You're already doing the latter, so you just need to do the unhooking part. The trick with that is that you'll need to unhook it from within the <code>after_setup_theme</code> hook, because otherwise the original hook will not have been added yet otherwise, since the child theme is loaded first:</p>\n<pre><code>add_action(\n 'after_setup_theme',\n function()\n {\n remove_action( 'wp_enqueue_scripts', 'mtt_styles' );\n }\n);\n</code></pre>\n"
},
{
"answer_id": 380081,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>There are 2 major problems here:</p>\n<h2>Problem 1: <code>get_template__....</code> and <code>get_stylehsheet_...</code> are not the same</h2>\n<p><code>filemtime(get_template_directory() . '/dist/css/custom-style.css'),</code> means get the file modified time of the parent themes <code>dist/css/custom-style.css</code> file.</p>\n<p>I suspect, there is no such file in the parent theme because it exists only in the child theme, so PHP fires off a warning that you asked for the file modified time of a file that does not exist.</p>\n<p><code>get_template_directory</code> and <code>get_stylesheet_directory</code> do not do the same thing.</p>\n<ul>\n<li><code>get_template_directory</code> is the parent theme ( current if not using a child theme</li>\n<li><code>get_stylesheet_directory</code> is the current theme, aka the child theme</li>\n</ul>\n<p>The same goes for all the other functions starting with <code>get_template_...</code> and <code>get_stylesheet_...</code></p>\n<h2>Problem 2: A Misunderstanding of <code>functions.php</code> in child and parent themes, and how child themes work.</h2>\n<p>If you use a child theme, the parent themes <code>functions.php</code> still runs. Child themes don't let you override any file by putting a new file with the same name in the child theme. That only works with templates loaded via <code>get_template_part</code>.</p>\n<p><strong>A PHP file in a child theme, or a JS/CSS file in a child theme does not override the same file in the parent theme.</strong></p>\n<p>So if you enqueue a CSS file in the parent theme, then copy the <code>functions.php</code> to the child theme and change it, it has not overriden the parent. Instead:</p>\n<ul>\n<li>both <code>functions.php</code> files run</li>\n<li>all the duplicated code now runs twice</li>\n<li>the original JS is enqueued, as well as the new JS file you tried to overwrite it with</li>\n</ul>\n"
}
] | 2020/12/18 | [
"https://wordpress.stackexchange.com/questions/380078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199141/"
] | I am trying to work on my child theme, but I can't get rid of the `filemtime(): stat failed` warning, which appeared as soon as I activated my child theme.
After reading other questions, I understand that the filemtime warning is often caused by incorrect use of URLs and paths. However, I think I provided URLs and paths correctly, and if that's the case, then there is something else I'm missing.
This function is from the parent theme:
```
function mtt_styles()
{
wp_enqueue_style(
'mtt-custom-style',
get_stylesheet_directory_uri() . '/dist/css/custom-style.css',
false,
filemtime(get_stylesheet_directory() . '/dist/css/custom-style.css'),
'all'
);
wp_enqueue_style('mtt-main-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'mtt_styles');
```
This is from my child theme:
```
function child_styles()
{
$theme = wp_get_theme();
wp_enqueue_style(
'mtt-custom-style',
get_template_directory_uri() . '/dist/css/custom-style.css',
array(),
filemtime(get_template_directory() . '/dist/css/custom-style.css'),
'all'
);
wp_enqueue_style(
'mtt-main-style',
get_template_directory_uri() . '/style.css',
array(),
$theme->parent()->get('Version'),
'all'
);
wp_enqueue_style(
'child-main-style',
get_stylesheet_uri(),
array('mtt-custom-style', 'mtt-main-style'));
}
add_action('wp_enqueue_scripts', 'child_styles');
```
When I go to the page source, I see that the enqueueing worked. All the files are there, and all the styles from the parent theme work well within the child, but the warning remains.
Could someone help me spot what I am missing or doing wrong here? | The problem is in your parent theme. The parent theme is using `get_stylesheet_directory()` here:
```
filemtime(get_stylesheet_directory() . '/dist/css/custom-style.css'),
```
When the parent theme is active, that's fine, because `get_stylesheet_directory()` will point that file in the parent theme. The problem is that when you activate a child theme, it is trying to get the `filemtime()` of `'/dist/css/custom-style.css'` in your *child theme*, and I'm guessing that this file doesn't exist there. Hence the failure.
The issue is that because `filemtime()` is run right away, it doesn't matter if you re-define the script's URL, or dequeue it, because it's already tried and failed to check the time, throwing the error.
If you're the author of the parent theme, then fixing the issue is as simple has replacing `get_stylesheet_directory()` with `get_template_directory_uri()` (or better yet, [`get_parent_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_path/)). Then the error won't occur when loading a stylesheet that's missing that file, and you won't need to re-eneueue it from that child theme.
If you're not the original author, then the right solution would be to just unhook `mtt_styles()` from `wp_enqueue_scripts` entirely. Then from the child theme just re-enqueue them using the correct path. You're already doing the latter, so you just need to do the unhooking part. The trick with that is that you'll need to unhook it from within the `after_setup_theme` hook, because otherwise the original hook will not have been added yet otherwise, since the child theme is loaded first:
```
add_action(
'after_setup_theme',
function()
{
remove_action( 'wp_enqueue_scripts', 'mtt_styles' );
}
);
``` |
380,083 | <p>How do I get the parent theme's version in a child theme?</p>
<p>I want to use it when loading the parent theme's stylesheet.</p>
<p>Here's how I load the stylesheets in the child theme's <code>functions.php</code> file:</p>
<pre><code>function sometheme_enqueue_styles() {
// Get parent theme version
$parent_theme_version = wp_get_theme()->parent()->get( 'Version' );
// Load parent theme stylesheet
wp_enqueue_style( 'sometheme-style', get_template_directory_uri() . '/style.css', array(), $parent_theme_version );
// Load child theme stylesheet
wp_enqueue_style( 'sometheme-child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'sometheme-style' ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'sometheme_enqueue_styles', 11 );
</code></pre>
<p>However, this will use the child theme's version for both stylesheets...</p>
<p>I have also tried this:</p>
<pre><code>$parent_theme = wp_get_theme('sometheme');
$parent_theme_version = $parent_theme->get( 'Version' );
</code></pre>
<p>...and this:</p>
<pre><code>$parent_theme = wp_get_theme(get_template());
$parent_theme_version = $parent_theme->get( 'Version' );
</code></pre>
<p>But again, the parent theme version keeps getting the version from the child theme.</p>
<h3>Solution</h3>
<p>It turns out that both <code>wp_get_theme()->parent()->get( 'Version' );</code> and <code>wp_get_theme()->parent()->Version;</code> works.</p>
<p>The problem was that the parent theme was using <code>$theme_version = wp_get_theme()->get( 'Version' );</code> as well, which means that it will use the child themes version.</p>
<p>Since I own the parent theme, I changed the parent theme to <code>wp_get_theme('sometheme')->get( 'Version' );</code> so that it always uses its own version.</p>
<p>That way, I can use either <code>wp_get_theme()->parent()->get( 'Version' );</code> or <code>wp_get_theme()->parent()->Version;</code> in the child theme.</p>
| [
{
"answer_id": 380087,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 4,
"selected": true,
"text": "<p>In the <a href=\"https://developer.wordpress.org/reference/classes/wp_theme/\" rel=\"noreferrer\">WP_Theme class</a>, the <code>get</code> method gives you a sanitized theme header. You cannot use it to extract a property. Actually you don't need to, as you can access it directly like this:</p>\n<pre><code> // get the parent object\n $parent = wp_get_theme()->parent();\n // get parent version\n if (!empty($parent)) $parent_version = $parent->Version;\n</code></pre>\n"
},
{
"answer_id": 380089,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 1,
"selected": false,
"text": "<p>Seeing your edit based on the suggested method from cjbj, make sure you are using the actual directory name for the parent theme when calling <code>wp_get_theme()</code>. Note - this is not the slug or written name of the theme in many cases.</p>\n<p>If <code>sometheme</code> is the file directory for the parent theme, then this should return the parent theme object:</p>\n<pre><code>var_dump( wp_get_theme( 'sometheme' ) );\n</code></pre>\n<p>Within that theme object is the version. Let's make sure you are getting the parent theme returned first.</p>\n<p>Add your output for that <code>var_dump()</code> statement to your question if it is not the parent theme.</p>\n"
}
] | 2020/12/18 | [
"https://wordpress.stackexchange.com/questions/380083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105316/"
] | How do I get the parent theme's version in a child theme?
I want to use it when loading the parent theme's stylesheet.
Here's how I load the stylesheets in the child theme's `functions.php` file:
```
function sometheme_enqueue_styles() {
// Get parent theme version
$parent_theme_version = wp_get_theme()->parent()->get( 'Version' );
// Load parent theme stylesheet
wp_enqueue_style( 'sometheme-style', get_template_directory_uri() . '/style.css', array(), $parent_theme_version );
// Load child theme stylesheet
wp_enqueue_style( 'sometheme-child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'sometheme-style' ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'sometheme_enqueue_styles', 11 );
```
However, this will use the child theme's version for both stylesheets...
I have also tried this:
```
$parent_theme = wp_get_theme('sometheme');
$parent_theme_version = $parent_theme->get( 'Version' );
```
...and this:
```
$parent_theme = wp_get_theme(get_template());
$parent_theme_version = $parent_theme->get( 'Version' );
```
But again, the parent theme version keeps getting the version from the child theme.
### Solution
It turns out that both `wp_get_theme()->parent()->get( 'Version' );` and `wp_get_theme()->parent()->Version;` works.
The problem was that the parent theme was using `$theme_version = wp_get_theme()->get( 'Version' );` as well, which means that it will use the child themes version.
Since I own the parent theme, I changed the parent theme to `wp_get_theme('sometheme')->get( 'Version' );` so that it always uses its own version.
That way, I can use either `wp_get_theme()->parent()->get( 'Version' );` or `wp_get_theme()->parent()->Version;` in the child theme. | In the [WP\_Theme class](https://developer.wordpress.org/reference/classes/wp_theme/), the `get` method gives you a sanitized theme header. You cannot use it to extract a property. Actually you don't need to, as you can access it directly like this:
```
// get the parent object
$parent = wp_get_theme()->parent();
// get parent version
if (!empty($parent)) $parent_version = $parent->Version;
``` |
380,086 | <p>I am trying to insert some php code to my WordPress website but it gives security warnings perhaps due to directly accessing <code>$_POST</code> variable.</p>
<p>Instead of <code>$name = $_POST['name'];</code>, I can use <code>$name = filter_input(INPUT_POST, 'name');</code> however I am not able to figure out what alternative piece of code I should use instead of <code>if(isset($_POST) && !empty($_POST)) { //some code }</code>?</p>
<p>Thanks for your help in advance.</p>
| [
{
"answer_id": 380091,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 2,
"selected": true,
"text": "<p><code>filter_input</code> is the proper way to go. If it doesn't return anything valid, it will return <code>null</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n$myvar = filter_input( INPUT_POST, 'something', FILTER_SANITIZE_STRING );\n\nif ( empty( $myvar ) ) {\n // Do whatever you would have done for ! isset( $_POST['something'] )\n}\n\n// Use $myvar\n</code></pre>\n<p><code>filter_input</code> won't throw any notices if the requested index isn't found, so it's like having <code>isset</code> built-in to the function.</p>\n<p><strong>Edit:</strong> just be sure to use a <code>FILTER_</code> to sanitize or validate, and note there are some gotchas that are documented in PHP's documentation about these. For most general use-cases they should work fine, but always validate your user input appropriately once you have it (the same as you would when getting it directly from <code>$_POST</code>).</p>\n"
},
{
"answer_id": 380106,
"author": "Asmat Ali",
"author_id": 198772,
"author_profile": "https://wordpress.stackexchange.com/users/198772",
"pm_score": 0,
"selected": false,
"text": "<p>Though the error was not caused by accessing $_POST variable directly, but I was able to write the alternative to <code>if(isset($_POST))</code>.</p>\n<p>Firstly, you need to give a name to the submit button in your form. Your form should look like,</p>\n<pre><code><form action = "" method = "post">\n Some fields.\n <input type = "submit" name = "submit_button" />\n</form>\n</code></pre>\n<p>And then on the php side,</p>\n<pre><code>$submit = filter_input(INPUT_POST, 'submit_button');\nif (isset($submit)){\n //some code.\n}\n</code></pre>\n<p>Hope this helps someone.</p>\n"
}
] | 2020/12/18 | [
"https://wordpress.stackexchange.com/questions/380086",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198772/"
] | I am trying to insert some php code to my WordPress website but it gives security warnings perhaps due to directly accessing `$_POST` variable.
Instead of `$name = $_POST['name'];`, I can use `$name = filter_input(INPUT_POST, 'name');` however I am not able to figure out what alternative piece of code I should use instead of `if(isset($_POST) && !empty($_POST)) { //some code }`?
Thanks for your help in advance. | `filter_input` is the proper way to go. If it doesn't return anything valid, it will return `null`:
```php
$myvar = filter_input( INPUT_POST, 'something', FILTER_SANITIZE_STRING );
if ( empty( $myvar ) ) {
// Do whatever you would have done for ! isset( $_POST['something'] )
}
// Use $myvar
```
`filter_input` won't throw any notices if the requested index isn't found, so it's like having `isset` built-in to the function.
**Edit:** just be sure to use a `FILTER_` to sanitize or validate, and note there are some gotchas that are documented in PHP's documentation about these. For most general use-cases they should work fine, but always validate your user input appropriately once you have it (the same as you would when getting it directly from `$_POST`). |
380,225 | <p>A while back I stumbled across this post from 2015, that showed how to <a href="https://wisdmlabs.com/blog/add-buttons-menu-options-tinymce-wordpress-post-editor/" rel="nofollow noreferrer">add Tiny MCE-buttons</a>.</p>
<p>It has been working for more than a year. But after the latest WordPress update (to version 5.6) it stopped working (the added dropdown-button isn't in the UI any longer).</p>
<p>What's wierd is that I had made 2 modifications to Tiny MCE:</p>
<ul>
<li><code>add_filter( 'mce_buttons', 'custom_register_mce_button' );</code> - which still works.</li>
<li><code>add_filter( 'mce_external_plugins', 'custom_add_tinymce_plugin' );</code> - which stopped working.</li>
</ul>
<p>I have the same code running on another site, which has also been updated to version 5.6. On it's the same buttons that has disappeared on both sites. So I'm quite sure that it's the WP-update that messed this up.</p>
<p>And I have checked the source code in the backend, and it is to be found in the code (so I can see that it is loaded).</p>
<h2>My code</h2>
<p><strong>In functions.php:</strong></p>
<pre><code>/**
* Add buttons in tinyMCE
*
* Source: https://wisdmlabs.com/blog/add-buttons-menu-options-tinymce-wordpress-post-editor/
*/
function custom_add_mce_button(){
if( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ){
return;
}
if( 'true' == get_user_option( 'rich_editing' ) ){
add_filter( 'mce_external_plugins', 'custom_add_tinymce_plugin' );
add_filter( 'mce_buttons', 'custom_register_mce_button' );
}
}
add_action( 'admin_head', 'custom_add_mce_button' );
function custom_register_mce_button( $buttons ){
array_push( $buttons, 'custom_mce_button' );
return $buttons;
}
function custom_add_tinymce_plugin( $plugin_array ){
$plugin_array['custom_mce_button'] = get_stylesheet_directory_uri() . '/assets/admin/js/tiny-mce-buttons.js';
return $plugin_array;
}
</code></pre>
<p><strong>The contents of tiny-mce-buttons.js:</strong></p>
<pre><code>( function() {
tinymce.PluginManager.add('custom_mce_button', function(editor, url) {
editor.addButton('custom_mce_button', {
text: 'Buttons',
icon: false,
type: 'menubutton',
menu: [
{
text: 'Button (simple)',
onclick: function() {
editor.insertContent('[button button_text="Read more" title="Google" link="https://google.com"]');
}
},
{
text: 'Button (centered)',
onclick: function() {
editor.insertContent('[button button_text="Read more" title="Google" link="https://google.com" class="zbtn__primary centered-button"]');
}
},
{
text: 'Button (all properties)',
onclick: function() {
editor.insertContent('[button button_text="Read more" link="https://google.com" title="Google" open_in_new_tab="yes" class="zbtn__primary"]');
}
}
]
});
});
})();
</code></pre>
<p>How do I add buttons to the Tiny MCE after this update?</p>
<hr />
<h2>Update1</h2>
<ul>
<li>I am using the classic editor indeed.</li>
<li>I have tried both with and without the plugin: Classic Editor. But <a href="https://www.advancedcustomfields.com/" rel="nofollow noreferrer">ACF</a> uses the classic editor as default for all Wysiwyg-fields, which is where I have this problem.</li>
<li>I have tried both with and without the plugin: <a href="https://da.wordpress.org/plugins/tinymce-advanced/" rel="nofollow noreferrer">Advanced Tiny MCE-plugin</a>.</li>
</ul>
| [
{
"answer_id": 383577,
"author": "Justin Roy",
"author_id": 202095,
"author_profile": "https://wordpress.stackexchange.com/users/202095",
"pm_score": 1,
"selected": false,
"text": "<p>This exact thing was happening to me after updating. It seems to be an issue with the new version of WordPress not including jquery-migrate.js by default.</p>\n<p>I'm not sure on a permanent solution, but installing this plugin has temporarily fixed the issue for me: <a href=\"https://wordpress.org/plugins/enable-jquery-migrate-helper/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/enable-jquery-migrate-helper/</a></p>\n"
},
{
"answer_id": 384505,
"author": "N3rdinator",
"author_id": 202851,
"author_profile": "https://wordpress.stackexchange.com/users/202851",
"pm_score": 0,
"selected": false,
"text": "<p>Having the same problem, can confirm that it appears to be a problem with jQuery. I'm trying to make a newsletter plugin viable again, which is no longer supported by the original author. The tinymce editor also failed after the update to 5.6. I'll post details about my code, maybe. we find the cause.</p>\n<p>First Part:</p>\n<pre><code>function plugins_loaded() {\n global $builder_id, $email_newsletter, $wp_customize;\n\n if(isset($wp_customize)) {\n $customizer_theme = $this->get_customizer_theme();\n $builder_theme = $this->get_builder_theme();\n if($builder_id && $customizer_theme == $builder_theme) {\n //Behebung bekannter Kompatibilitätsprobleme\n add_action( 'init', array( &$this, 'cleanup_customizer'), 1 );\n\n add_action( 'setup_theme' , array( &$this, 'setup_builder_header_footer' ), 999 );\n add_filter( 'wp_default_editor', array( &$this, 'force_default_editor' ) );\n add_filter( 'user_can_richedit', array( &$this, 'force_richedit' ) );\n\n add_action( 'admin_head', array( &$this, 'prepare_tinymce' ), 999 );\n\n add_action( 'template_redirect', array( &$this, 'enable_customizer') );\n }\n }\n</code></pre>\n<p>Part 2</p>\n<pre><code>function prepare_tinymce() {\n global $enewsletter_tinymce;\n ob_start();\n\n $tinymce_options = array(\n 'teeny' => false,\n 'media_buttons' => true,\n 'quicktags' => false,\n 'textarea_rows' => 25,\n 'drag_drop_upload' => true,\n 'tinymce' => array(\n 'wp_skip_init' => false,\n 'theme_advanced_disable' => '',\n 'theme_advanced_buttons1_add' => 'code',\n 'theme_advanced_resize_horizontal' => true,\n 'add_unload_trigger' => false,\n 'resize' => 'both'\n ),\n 'editor_css' => '<style type="text/css">body { background: #000; }</style>',\n );\n $email_content = $this->get_builder_email_content('');\n wp_editor($email_content, 'content_tinymce', $tinymce_options);\n\n $enewsletter_tinymce = ob_get_clean();\n</code></pre>\n<p>Part 3</p>\n<pre><code>public function render_content() {\n global $enewsletter_tinymce;\n ?>\n <span class="customize-control-title"><?php echo $this->label; ?></span>\n <textarea id="<?php echo $this->id; ?>" style="display:none" <?php echo $this->link(); ?>><?php echo esc_textarea($this->value()); ?></textarea>\n <?php\n echo $enewsletter_tinymce;\n ?>\n \n <script type="text/javascript">\n jQuery(document).ready( function() {\n var content = 0;\n // Unsere tinyMCE-Funktion feuert bei jeder Änderung\n tinymce_check_changes = setInterval(function() {\n var check_content = tinyMCE.activeEditor.getContent({format : 'raw'});\n \n if(check_content != content && check_content != '<p><br data-mce-bogus="1"></p>') {\n content = check_content;\n\n jQuery('#<?php echo $this->id; ?>').val(content).trigger('change');\n }\n }, 2000);\n\n //enables resizing of email content box\n var resize;\n var prev_emce_width = 0;\n jQuery('#accordion-section-builder_email_content').on('mousedown', '.mce-i-resize, #content_tinymce_resize', function(){\n resize_start();\n });\n jQuery('#accordion-section-builder_email_content h3').click(function(){\n resize_start();\n });\n jQuery("body").mouseup(function() {\n clearInterval(resize);\n });\n\n function resize_start() {\n resize = setInterval(function() {\n emce_width = jQuery('#content_tinymce_ifr').width()+65;\n \n if(emce_width >= '490' && emce_width != prev_emce_width) {\n jQuery('#customize-controls').css("-webkit-animation", "none");\n jQuery('#customize-controls').css("-moz-animation", "none");\n jQuery('#customize-controls').css("-ms-animation", "none");\n jQuery('#customize-controls').css("animation", "none");\n prev_emce_width = emce_width;\n jQuery('#customize-controls, #customize-footer-actions').css("width", emce_width+"px");\n jQuery('.wp-full-overlay').css("margin-left", emce_width+"px");\n jQuery('.wp-full-overlay-sidebar').css("margin-left", "-"+emce_width+"px");\n }\n },50); \n }\n });\n </script>\n <?php\n }\n</code></pre>\n<p>In my Debug i can see: Uncaught TypeError: Cannot read property 'getContent' of null</p>\n<p>I think that tinymce has a problem with the latest jQuery version with the difference between Probertys and Values.</p>\n"
}
] | 2020/12/21 | [
"https://wordpress.stackexchange.com/questions/380225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | A while back I stumbled across this post from 2015, that showed how to [add Tiny MCE-buttons](https://wisdmlabs.com/blog/add-buttons-menu-options-tinymce-wordpress-post-editor/).
It has been working for more than a year. But after the latest WordPress update (to version 5.6) it stopped working (the added dropdown-button isn't in the UI any longer).
What's wierd is that I had made 2 modifications to Tiny MCE:
* `add_filter( 'mce_buttons', 'custom_register_mce_button' );` - which still works.
* `add_filter( 'mce_external_plugins', 'custom_add_tinymce_plugin' );` - which stopped working.
I have the same code running on another site, which has also been updated to version 5.6. On it's the same buttons that has disappeared on both sites. So I'm quite sure that it's the WP-update that messed this up.
And I have checked the source code in the backend, and it is to be found in the code (so I can see that it is loaded).
My code
-------
**In functions.php:**
```
/**
* Add buttons in tinyMCE
*
* Source: https://wisdmlabs.com/blog/add-buttons-menu-options-tinymce-wordpress-post-editor/
*/
function custom_add_mce_button(){
if( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ){
return;
}
if( 'true' == get_user_option( 'rich_editing' ) ){
add_filter( 'mce_external_plugins', 'custom_add_tinymce_plugin' );
add_filter( 'mce_buttons', 'custom_register_mce_button' );
}
}
add_action( 'admin_head', 'custom_add_mce_button' );
function custom_register_mce_button( $buttons ){
array_push( $buttons, 'custom_mce_button' );
return $buttons;
}
function custom_add_tinymce_plugin( $plugin_array ){
$plugin_array['custom_mce_button'] = get_stylesheet_directory_uri() . '/assets/admin/js/tiny-mce-buttons.js';
return $plugin_array;
}
```
**The contents of tiny-mce-buttons.js:**
```
( function() {
tinymce.PluginManager.add('custom_mce_button', function(editor, url) {
editor.addButton('custom_mce_button', {
text: 'Buttons',
icon: false,
type: 'menubutton',
menu: [
{
text: 'Button (simple)',
onclick: function() {
editor.insertContent('[button button_text="Read more" title="Google" link="https://google.com"]');
}
},
{
text: 'Button (centered)',
onclick: function() {
editor.insertContent('[button button_text="Read more" title="Google" link="https://google.com" class="zbtn__primary centered-button"]');
}
},
{
text: 'Button (all properties)',
onclick: function() {
editor.insertContent('[button button_text="Read more" link="https://google.com" title="Google" open_in_new_tab="yes" class="zbtn__primary"]');
}
}
]
});
});
})();
```
How do I add buttons to the Tiny MCE after this update?
---
Update1
-------
* I am using the classic editor indeed.
* I have tried both with and without the plugin: Classic Editor. But [ACF](https://www.advancedcustomfields.com/) uses the classic editor as default for all Wysiwyg-fields, which is where I have this problem.
* I have tried both with and without the plugin: [Advanced Tiny MCE-plugin](https://da.wordpress.org/plugins/tinymce-advanced/). | This exact thing was happening to me after updating. It seems to be an issue with the new version of WordPress not including jquery-migrate.js by default.
I'm not sure on a permanent solution, but installing this plugin has temporarily fixed the issue for me: <https://wordpress.org/plugins/enable-jquery-migrate-helper/> |
380,285 | <p>I have a private custom plugin that I just use on my multiple sites, and since I do a lot of debugging I find it easier to include the wp-config.php file contents in the admin area to ensure I have enabled/disabled debugging properly. Now I am training other designers to help with debugging, so I want to include line numbers similar to the theme/plugin editor. I retrieve the contents of the wp-config file using the <code>file_get_contents()</code> function. Is there a way I can add line numbers to this output?</p>
<p>Here is my function that gets the wp-config file contents:</p>
<pre><code>function eriWpConfig(){
$wp_config = FALSE;
if ( is_readable( ABSPATH . 'wp-config.php' ) )
$wp_config = ABSPATH . 'wp-config.php';
elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
$wp_config = dirname( ABSPATH ) . '/wp-config.php';
if ( $wp_config )
$code = esc_html( file_get_contents( $wp_config ) );
else
$code = 'wp-config.php not found';
echo '<pre class="code"
>Installation path: ' . ABSPATH
. "\n\n"
. $code
. '</pre>';
}
</code></pre>
<p><strong>EDIT:</strong>
Per Q Studio's suggestion, I tried the following and I'm just returning Line 0 at the beginning of the output.</p>
<pre><code>if ( $wp_config ) {
$string = file_get_contents( $wp_config );
$lines = explode('\n', $string);
$modified_lines = [];
$line_count = 0;
foreach($lines as $line){
$modified_lines[] = 'Line '.$line_count.' '.$line;
}
$code = esc_html( implode('<br>', $modified_lines) );
} else {
$code = 'wp-config.php not found';
}
</code></pre>
| [
{
"answer_id": 380289,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps something like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( $wp_config ) { \n \n $string = file_get_contents( $wp_config ); \n $lines = explode('\\n', $string); \n \n $line_count = 0; \n \n foreach( $lines as $line ){\n\n $code .= 'Line: '.$line_count.' | '.$line.'<br />'; \n\n // iterate count ##\n $line_count ++; \n\n } \n \n} else { \n \n $code = 'wp-config.php not found'; \n \n}\n</code></pre>\n"
},
{
"answer_id": 380293,
"author": "Michael",
"author_id": 42925,
"author_profile": "https://wordpress.stackexchange.com/users/42925",
"pm_score": 2,
"selected": false,
"text": "<p>With the help of Q Studio and my own research, I found that exploding with PHP_EOL worked. Here is my modified code:</p>\n<pre><code>function eriWpConfig(){\n $wp_config = FALSE;\n if ( is_readable( ABSPATH . 'wp-config.php' ) )\n $wp_config = ABSPATH . 'wp-config.php';\n elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )\n $wp_config = dirname( ABSPATH ) . '/wp-config.php';\n\n if ( $wp_config ) {\n $string = file_get_contents( $wp_config );\n $lines = explode(PHP_EOL, $string);\n $modified_lines = [];\n $line_count = 0;\n \n foreach($lines as $line){\n $modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);\n $line_count ++; \n }\n \n $code = implode('<br>', $modified_lines);\n \n } else {\n $code = 'wp-config.php not found';\n }\n \n echo '<pre class="code"\n >Installation path: ' . ABSPATH\n . "\\n\\n"\n . $code\n . '</pre>';\n}\n</code></pre>\n"
}
] | 2020/12/22 | [
"https://wordpress.stackexchange.com/questions/380285",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42925/"
] | I have a private custom plugin that I just use on my multiple sites, and since I do a lot of debugging I find it easier to include the wp-config.php file contents in the admin area to ensure I have enabled/disabled debugging properly. Now I am training other designers to help with debugging, so I want to include line numbers similar to the theme/plugin editor. I retrieve the contents of the wp-config file using the `file_get_contents()` function. Is there a way I can add line numbers to this output?
Here is my function that gets the wp-config file contents:
```
function eriWpConfig(){
$wp_config = FALSE;
if ( is_readable( ABSPATH . 'wp-config.php' ) )
$wp_config = ABSPATH . 'wp-config.php';
elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
$wp_config = dirname( ABSPATH ) . '/wp-config.php';
if ( $wp_config )
$code = esc_html( file_get_contents( $wp_config ) );
else
$code = 'wp-config.php not found';
echo '<pre class="code"
>Installation path: ' . ABSPATH
. "\n\n"
. $code
. '</pre>';
}
```
**EDIT:**
Per Q Studio's suggestion, I tried the following and I'm just returning Line 0 at the beginning of the output.
```
if ( $wp_config ) {
$string = file_get_contents( $wp_config );
$lines = explode('\n', $string);
$modified_lines = [];
$line_count = 0;
foreach($lines as $line){
$modified_lines[] = 'Line '.$line_count.' '.$line;
}
$code = esc_html( implode('<br>', $modified_lines) );
} else {
$code = 'wp-config.php not found';
}
``` | With the help of Q Studio and my own research, I found that exploding with PHP\_EOL worked. Here is my modified code:
```
function eriWpConfig(){
$wp_config = FALSE;
if ( is_readable( ABSPATH . 'wp-config.php' ) )
$wp_config = ABSPATH . 'wp-config.php';
elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
$wp_config = dirname( ABSPATH ) . '/wp-config.php';
if ( $wp_config ) {
$string = file_get_contents( $wp_config );
$lines = explode(PHP_EOL, $string);
$modified_lines = [];
$line_count = 0;
foreach($lines as $line){
$modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);
$line_count ++;
}
$code = implode('<br>', $modified_lines);
} else {
$code = 'wp-config.php not found';
}
echo '<pre class="code"
>Installation path: ' . ABSPATH
. "\n\n"
. $code
. '</pre>';
}
``` |
380,299 | <p>Hello I have create a custom taxonomy for a custom post. I want to get the taxonomy term that is used in the current post. How to get it.</p>
| [
{
"answer_id": 380289,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps something like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( $wp_config ) { \n \n $string = file_get_contents( $wp_config ); \n $lines = explode('\\n', $string); \n \n $line_count = 0; \n \n foreach( $lines as $line ){\n\n $code .= 'Line: '.$line_count.' | '.$line.'<br />'; \n\n // iterate count ##\n $line_count ++; \n\n } \n \n} else { \n \n $code = 'wp-config.php not found'; \n \n}\n</code></pre>\n"
},
{
"answer_id": 380293,
"author": "Michael",
"author_id": 42925,
"author_profile": "https://wordpress.stackexchange.com/users/42925",
"pm_score": 2,
"selected": false,
"text": "<p>With the help of Q Studio and my own research, I found that exploding with PHP_EOL worked. Here is my modified code:</p>\n<pre><code>function eriWpConfig(){\n $wp_config = FALSE;\n if ( is_readable( ABSPATH . 'wp-config.php' ) )\n $wp_config = ABSPATH . 'wp-config.php';\n elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )\n $wp_config = dirname( ABSPATH ) . '/wp-config.php';\n\n if ( $wp_config ) {\n $string = file_get_contents( $wp_config );\n $lines = explode(PHP_EOL, $string);\n $modified_lines = [];\n $line_count = 0;\n \n foreach($lines as $line){\n $modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);\n $line_count ++; \n }\n \n $code = implode('<br>', $modified_lines);\n \n } else {\n $code = 'wp-config.php not found';\n }\n \n echo '<pre class="code"\n >Installation path: ' . ABSPATH\n . "\\n\\n"\n . $code\n . '</pre>';\n}\n</code></pre>\n"
}
] | 2020/12/23 | [
"https://wordpress.stackexchange.com/questions/380299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199341/"
] | Hello I have create a custom taxonomy for a custom post. I want to get the taxonomy term that is used in the current post. How to get it. | With the help of Q Studio and my own research, I found that exploding with PHP\_EOL worked. Here is my modified code:
```
function eriWpConfig(){
$wp_config = FALSE;
if ( is_readable( ABSPATH . 'wp-config.php' ) )
$wp_config = ABSPATH . 'wp-config.php';
elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
$wp_config = dirname( ABSPATH ) . '/wp-config.php';
if ( $wp_config ) {
$string = file_get_contents( $wp_config );
$lines = explode(PHP_EOL, $string);
$modified_lines = [];
$line_count = 0;
foreach($lines as $line){
$modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);
$line_count ++;
}
$code = implode('<br>', $modified_lines);
} else {
$code = 'wp-config.php not found';
}
echo '<pre class="code"
>Installation path: ' . ABSPATH
. "\n\n"
. $code
. '</pre>';
}
``` |
380,346 | <p>I have set up WordPress on my computer, installed in /var/www/localhost/htdocs and eventually got the admin page and entered a username and a password.</p>
<p>This is my wp-config.php (I have taken out the MySQL password and the longer comments):</p>
<pre><code>/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );
/** MySQL database username */
define( 'DB_USER', 'root' );
/** MySQL database password */
define( 'DB_PASSWORD', '?xxx?' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );
/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
/** MySQL socket */
define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' );
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define( 'AUTH_KEY', 'put your unique phrase here' );
define( 'SECURE_AUTH_KEY', 'put your unique phrase here' );
define( 'LOGGED_IN_KEY', 'put your unique phrase here' );
define( 'NONCE_KEY', 'put your unique phrase here' );
define( 'AUTH_SALT', 'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT', 'put your unique phrase here' );
define( 'NONCE_SALT', 'put your unique phrase here' );
/**
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
define( 'WP_DEBUG', true );
define('WP_DEBUG_LOG',true);
/* That's all, stop editing! Happy publishing. */
/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', __DIR__ . '/' );
}
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
</code></pre>
<p>I can login using
<code>http://localhost/wp-login.php</code>
but after that I get "403 Forbidden" -- I have set debug on in the hope of further information but I cannot find a log file.</p>
<p>I hope you can help me... (sorry, can't find an appropriate tag)</p>
| [
{
"answer_id": 380289,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps something like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if ( $wp_config ) { \n \n $string = file_get_contents( $wp_config ); \n $lines = explode('\\n', $string); \n \n $line_count = 0; \n \n foreach( $lines as $line ){\n\n $code .= 'Line: '.$line_count.' | '.$line.'<br />'; \n\n // iterate count ##\n $line_count ++; \n\n } \n \n} else { \n \n $code = 'wp-config.php not found'; \n \n}\n</code></pre>\n"
},
{
"answer_id": 380293,
"author": "Michael",
"author_id": 42925,
"author_profile": "https://wordpress.stackexchange.com/users/42925",
"pm_score": 2,
"selected": false,
"text": "<p>With the help of Q Studio and my own research, I found that exploding with PHP_EOL worked. Here is my modified code:</p>\n<pre><code>function eriWpConfig(){\n $wp_config = FALSE;\n if ( is_readable( ABSPATH . 'wp-config.php' ) )\n $wp_config = ABSPATH . 'wp-config.php';\n elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )\n $wp_config = dirname( ABSPATH ) . '/wp-config.php';\n\n if ( $wp_config ) {\n $string = file_get_contents( $wp_config );\n $lines = explode(PHP_EOL, $string);\n $modified_lines = [];\n $line_count = 0;\n \n foreach($lines as $line){\n $modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);\n $line_count ++; \n }\n \n $code = implode('<br>', $modified_lines);\n \n } else {\n $code = 'wp-config.php not found';\n }\n \n echo '<pre class="code"\n >Installation path: ' . ABSPATH\n . "\\n\\n"\n . $code\n . '</pre>';\n}\n</code></pre>\n"
}
] | 2020/12/23 | [
"https://wordpress.stackexchange.com/questions/380346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199384/"
] | I have set up WordPress on my computer, installed in /var/www/localhost/htdocs and eventually got the admin page and entered a username and a password.
This is my wp-config.php (I have taken out the MySQL password and the longer comments):
```
/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );
/** MySQL database username */
define( 'DB_USER', 'root' );
/** MySQL database password */
define( 'DB_PASSWORD', '?xxx?' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );
/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
/** MySQL socket */
define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' );
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define( 'AUTH_KEY', 'put your unique phrase here' );
define( 'SECURE_AUTH_KEY', 'put your unique phrase here' );
define( 'LOGGED_IN_KEY', 'put your unique phrase here' );
define( 'NONCE_KEY', 'put your unique phrase here' );
define( 'AUTH_SALT', 'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT', 'put your unique phrase here' );
define( 'NONCE_SALT', 'put your unique phrase here' );
/**
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
define( 'WP_DEBUG', true );
define('WP_DEBUG_LOG',true);
/* That's all, stop editing! Happy publishing. */
/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', __DIR__ . '/' );
}
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
```
I can login using
`http://localhost/wp-login.php`
but after that I get "403 Forbidden" -- I have set debug on in the hope of further information but I cannot find a log file.
I hope you can help me... (sorry, can't find an appropriate tag) | With the help of Q Studio and my own research, I found that exploding with PHP\_EOL worked. Here is my modified code:
```
function eriWpConfig(){
$wp_config = FALSE;
if ( is_readable( ABSPATH . 'wp-config.php' ) )
$wp_config = ABSPATH . 'wp-config.php';
elseif ( is_readable( dirname( ABSPATH ) . '/wp-config.php' ) )
$wp_config = dirname( ABSPATH ) . '/wp-config.php';
if ( $wp_config ) {
$string = file_get_contents( $wp_config );
$lines = explode(PHP_EOL, $string);
$modified_lines = [];
$line_count = 0;
foreach($lines as $line){
$modified_lines[] = '<span style="color: #ccc;">Line: '.sprintf("%03d", $line_count).' | </span>'.esc_html($line);
$line_count ++;
}
$code = implode('<br>', $modified_lines);
} else {
$code = 'wp-config.php not found';
}
echo '<pre class="code"
>Installation path: ' . ABSPATH
. "\n\n"
. $code
. '</pre>';
}
``` |
380,353 | <p>In Wordpress I need to add a filter where user role subscriber just put his email address in form to login, no need for password, just check if the email is for a subscriber and redirect him to a specific page, I tried many solutions but I didn't get it,
Thanks</p>
| [
{
"answer_id": 380358,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, you can add an <a href=\"https://developer.wordpress.org/reference/hooks/authenticate/\" rel=\"nofollow noreferrer\">authenticate</a> filter to handle the email and no password case with a higher priority than the default wp_authenticate_email_password handler. e.g. (untested)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {\n if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {\n // Already handled by a higher-priority filter\n return $user;\n }\n\n if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {\n // This is an email login with empty password\n $user = get_user_by( 'email', $email );\n\n if ( $user && ! is_wp_error( $user ) ) {\n // TODO: Verify that the user is someone you'd want to login without\n // a password. For now, let's reject anyone who can edit posts.\n if ( $user->has_cap( 'edit_posts' ) ) {\n $error = new WP_Error();\n // TODO: localize the error message\n $error->add( 'empty_password',\n '<strong>Error</strong>: This user requires a password.' );\n return $error;\n }\n\n // We'll allow this user to login without a password.\n // Return the user object and the calling code will handle the login.\n return $user;\n }\n // else could not fetch the user by email address.\n // You'll probably now get a 'password field is empty' error\n // from a later filter.\n // TODO: If you want a different error then generate it here.\n }\n\n return $user;\n}\n\n// Add an authenticate filter with a higher priority (= lower number) than\n// wp_authenticate_email_password which has priority 20.\nadd_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 380359,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress core is full of surprises. You can do many things with that.</p>\n<p>To provide a password less login to desired user role, you can modify how WordPress handles user login authentication. There is a filter named <code>authenticate</code>, which you can use to hook in, and extend the authorization process to enable that.</p>\n<p>WordPress itself hook into this callback with 3 separate function -</p>\n<ul>\n<li><code>wp_authenticate_cookie</code> - This validates if the user is already logged-in.</li>\n<li><code>wp_authenticate_username_password</code> - This validate user_name/password combo</li>\n<li><code>wp_authenticate_email_password</code> - This validates email/password combo.</li>\n</ul>\n<p>Above functions are hooked with a priority of <code>30</code>.\nYou can hook with a function here with higher priority and check if any of these validation returns a <code>WP_Error</code> object. For empty password, the error code would be <code>empty_password</code>. If the error and error code matches, you can perform further validation to test if there is a user with that login/email, and if he is a subscriber.</p>\n<p>Sounds Good? Here's the code -</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_password_less_login_authentication( $user, $username, $password ) {\n if (! is_wp_error($user) && 'empty_password ' !== $user->get_error_code()) {\n return $user;\n }\n\n if (strpos($username, '@')) {\n $find_user = get_user_by( 'email', $username );\n } else {\n $find_user = get_user_by( 'login', $username );\n }\n\n if ( $find_user && ! is_wp_error( $find_user ) && in_array( 'subscriber', $find_user->roles, true ) ) {\n return $find_user;\n }\n \n return $user;\n}\nadd_filter( 'authenticate', 'wpse_password_less_login_authentication', 40, 3 );\n</code></pre>\n<p>This function should go inside your themes <code>functions.php</code> (or included files) or inside an active plugin file.</p>\n"
}
] | 2020/12/23 | [
"https://wordpress.stackexchange.com/questions/380353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199390/"
] | In Wordpress I need to add a filter where user role subscriber just put his email address in form to login, no need for password, just check if the email is for a subscriber and redirect him to a specific page, I tried many solutions but I didn't get it,
Thanks | Yes, you can add an [authenticate](https://developer.wordpress.org/reference/hooks/authenticate/) filter to handle the email and no password case with a higher priority than the default wp\_authenticate\_email\_password handler. e.g. (untested)
```php
function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {
if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {
// Already handled by a higher-priority filter
return $user;
}
if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {
// This is an email login with empty password
$user = get_user_by( 'email', $email );
if ( $user && ! is_wp_error( $user ) ) {
// TODO: Verify that the user is someone you'd want to login without
// a password. For now, let's reject anyone who can edit posts.
if ( $user->has_cap( 'edit_posts' ) ) {
$error = new WP_Error();
// TODO: localize the error message
$error->add( 'empty_password',
'<strong>Error</strong>: This user requires a password.' );
return $error;
}
// We'll allow this user to login without a password.
// Return the user object and the calling code will handle the login.
return $user;
}
// else could not fetch the user by email address.
// You'll probably now get a 'password field is empty' error
// from a later filter.
// TODO: If you want a different error then generate it here.
}
return $user;
}
// Add an authenticate filter with a higher priority (= lower number) than
// wp_authenticate_email_password which has priority 20.
add_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );
``` |
380,367 | <p>I have a separate page at the root of WordPress, for processing certain data, with the "wp-load.php" file connected to it.</p>
<pre><code><?php
require_once( dirname(__FILE__) . '/wp-load.php' );
require_once( dirname(__FILE__) . '/wp-admin/includes/admin.php' );
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
function example_ajax_request() {
if ( isset( $_REQUEST ) ) {
$postID = $_REQUEST['postID'];
print $postID;
}
wp_die();
}
?><!doctype html>
<html lang="ru" dir="ltr">
<head>
<meta charset="utf-8">
<title>Outside page</title>
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>
<script>
var ajaxurl = "<?php print admin_url( 'admin-ajax.php' ); ?>";
</script>
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
$( '#our-work a' ).click( function( e ) {
e.preventDefault();
var postID = $( this ).attr( 'data-id' );
$.ajax({
url: './wp-admin/admin-ajax.php',
data: {
'action' : 'example_ajax_request',
'postID' : postID
},
success : function( data ) {
$( '#hero' ).append( 'Well this seems to work' + data );
},
error : function(errorThrown){
console.log( 'This has thrown an error:' + errorThrown );
}
});
return false;
});
});
</script>
</head>
<body>
<p id="our-work">
<a data-id="123" href=".">Get and push!</a>
</p>
<div id="hero"></div>
</body>
</html>
</code></pre>
<p>Unfortunately I am getting the error:</p>
<p><a href="https://i.stack.imgur.com/bKLlu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bKLlu.png" alt="enter image description here" /></a></p>
<p>Why isn't the Ajax code working here?</p>
<p>Do you need to connect any other file?</p>
| [
{
"answer_id": 380358,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, you can add an <a href=\"https://developer.wordpress.org/reference/hooks/authenticate/\" rel=\"nofollow noreferrer\">authenticate</a> filter to handle the email and no password case with a higher priority than the default wp_authenticate_email_password handler. e.g. (untested)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {\n if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {\n // Already handled by a higher-priority filter\n return $user;\n }\n\n if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {\n // This is an email login with empty password\n $user = get_user_by( 'email', $email );\n\n if ( $user && ! is_wp_error( $user ) ) {\n // TODO: Verify that the user is someone you'd want to login without\n // a password. For now, let's reject anyone who can edit posts.\n if ( $user->has_cap( 'edit_posts' ) ) {\n $error = new WP_Error();\n // TODO: localize the error message\n $error->add( 'empty_password',\n '<strong>Error</strong>: This user requires a password.' );\n return $error;\n }\n\n // We'll allow this user to login without a password.\n // Return the user object and the calling code will handle the login.\n return $user;\n }\n // else could not fetch the user by email address.\n // You'll probably now get a 'password field is empty' error\n // from a later filter.\n // TODO: If you want a different error then generate it here.\n }\n\n return $user;\n}\n\n// Add an authenticate filter with a higher priority (= lower number) than\n// wp_authenticate_email_password which has priority 20.\nadd_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 380359,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress core is full of surprises. You can do many things with that.</p>\n<p>To provide a password less login to desired user role, you can modify how WordPress handles user login authentication. There is a filter named <code>authenticate</code>, which you can use to hook in, and extend the authorization process to enable that.</p>\n<p>WordPress itself hook into this callback with 3 separate function -</p>\n<ul>\n<li><code>wp_authenticate_cookie</code> - This validates if the user is already logged-in.</li>\n<li><code>wp_authenticate_username_password</code> - This validate user_name/password combo</li>\n<li><code>wp_authenticate_email_password</code> - This validates email/password combo.</li>\n</ul>\n<p>Above functions are hooked with a priority of <code>30</code>.\nYou can hook with a function here with higher priority and check if any of these validation returns a <code>WP_Error</code> object. For empty password, the error code would be <code>empty_password</code>. If the error and error code matches, you can perform further validation to test if there is a user with that login/email, and if he is a subscriber.</p>\n<p>Sounds Good? Here's the code -</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_password_less_login_authentication( $user, $username, $password ) {\n if (! is_wp_error($user) && 'empty_password ' !== $user->get_error_code()) {\n return $user;\n }\n\n if (strpos($username, '@')) {\n $find_user = get_user_by( 'email', $username );\n } else {\n $find_user = get_user_by( 'login', $username );\n }\n\n if ( $find_user && ! is_wp_error( $find_user ) && in_array( 'subscriber', $find_user->roles, true ) ) {\n return $find_user;\n }\n \n return $user;\n}\nadd_filter( 'authenticate', 'wpse_password_less_login_authentication', 40, 3 );\n</code></pre>\n<p>This function should go inside your themes <code>functions.php</code> (or included files) or inside an active plugin file.</p>\n"
}
] | 2020/12/24 | [
"https://wordpress.stackexchange.com/questions/380367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/195858/"
] | I have a separate page at the root of WordPress, for processing certain data, with the "wp-load.php" file connected to it.
```
<?php
require_once( dirname(__FILE__) . '/wp-load.php' );
require_once( dirname(__FILE__) . '/wp-admin/includes/admin.php' );
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
function example_ajax_request() {
if ( isset( $_REQUEST ) ) {
$postID = $_REQUEST['postID'];
print $postID;
}
wp_die();
}
?><!doctype html>
<html lang="ru" dir="ltr">
<head>
<meta charset="utf-8">
<title>Outside page</title>
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>
<script>
var ajaxurl = "<?php print admin_url( 'admin-ajax.php' ); ?>";
</script>
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
$( '#our-work a' ).click( function( e ) {
e.preventDefault();
var postID = $( this ).attr( 'data-id' );
$.ajax({
url: './wp-admin/admin-ajax.php',
data: {
'action' : 'example_ajax_request',
'postID' : postID
},
success : function( data ) {
$( '#hero' ).append( 'Well this seems to work' + data );
},
error : function(errorThrown){
console.log( 'This has thrown an error:' + errorThrown );
}
});
return false;
});
});
</script>
</head>
<body>
<p id="our-work">
<a data-id="123" href=".">Get and push!</a>
</p>
<div id="hero"></div>
</body>
</html>
```
Unfortunately I am getting the error:
[](https://i.stack.imgur.com/bKLlu.png)
Why isn't the Ajax code working here?
Do you need to connect any other file? | Yes, you can add an [authenticate](https://developer.wordpress.org/reference/hooks/authenticate/) filter to handle the email and no password case with a higher priority than the default wp\_authenticate\_email\_password handler. e.g. (untested)
```php
function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {
if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {
// Already handled by a higher-priority filter
return $user;
}
if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {
// This is an email login with empty password
$user = get_user_by( 'email', $email );
if ( $user && ! is_wp_error( $user ) ) {
// TODO: Verify that the user is someone you'd want to login without
// a password. For now, let's reject anyone who can edit posts.
if ( $user->has_cap( 'edit_posts' ) ) {
$error = new WP_Error();
// TODO: localize the error message
$error->add( 'empty_password',
'<strong>Error</strong>: This user requires a password.' );
return $error;
}
// We'll allow this user to login without a password.
// Return the user object and the calling code will handle the login.
return $user;
}
// else could not fetch the user by email address.
// You'll probably now get a 'password field is empty' error
// from a later filter.
// TODO: If you want a different error then generate it here.
}
return $user;
}
// Add an authenticate filter with a higher priority (= lower number) than
// wp_authenticate_email_password which has priority 20.
add_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );
``` |
380,408 | <p>If I try to change my email address, it will say it has sent a confirmation email to the new email address. But, I do not see any email request to that email.</p>
<p>Is there a way to troubleshoot this or understand the error?</p>
| [
{
"answer_id": 380358,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, you can add an <a href=\"https://developer.wordpress.org/reference/hooks/authenticate/\" rel=\"nofollow noreferrer\">authenticate</a> filter to handle the email and no password case with a higher priority than the default wp_authenticate_email_password handler. e.g. (untested)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {\n if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {\n // Already handled by a higher-priority filter\n return $user;\n }\n\n if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {\n // This is an email login with empty password\n $user = get_user_by( 'email', $email );\n\n if ( $user && ! is_wp_error( $user ) ) {\n // TODO: Verify that the user is someone you'd want to login without\n // a password. For now, let's reject anyone who can edit posts.\n if ( $user->has_cap( 'edit_posts' ) ) {\n $error = new WP_Error();\n // TODO: localize the error message\n $error->add( 'empty_password',\n '<strong>Error</strong>: This user requires a password.' );\n return $error;\n }\n\n // We'll allow this user to login without a password.\n // Return the user object and the calling code will handle the login.\n return $user;\n }\n // else could not fetch the user by email address.\n // You'll probably now get a 'password field is empty' error\n // from a later filter.\n // TODO: If you want a different error then generate it here.\n }\n\n return $user;\n}\n\n// Add an authenticate filter with a higher priority (= lower number) than\n// wp_authenticate_email_password which has priority 20.\nadd_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 380359,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress core is full of surprises. You can do many things with that.</p>\n<p>To provide a password less login to desired user role, you can modify how WordPress handles user login authentication. There is a filter named <code>authenticate</code>, which you can use to hook in, and extend the authorization process to enable that.</p>\n<p>WordPress itself hook into this callback with 3 separate function -</p>\n<ul>\n<li><code>wp_authenticate_cookie</code> - This validates if the user is already logged-in.</li>\n<li><code>wp_authenticate_username_password</code> - This validate user_name/password combo</li>\n<li><code>wp_authenticate_email_password</code> - This validates email/password combo.</li>\n</ul>\n<p>Above functions are hooked with a priority of <code>30</code>.\nYou can hook with a function here with higher priority and check if any of these validation returns a <code>WP_Error</code> object. For empty password, the error code would be <code>empty_password</code>. If the error and error code matches, you can perform further validation to test if there is a user with that login/email, and if he is a subscriber.</p>\n<p>Sounds Good? Here's the code -</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_password_less_login_authentication( $user, $username, $password ) {\n if (! is_wp_error($user) && 'empty_password ' !== $user->get_error_code()) {\n return $user;\n }\n\n if (strpos($username, '@')) {\n $find_user = get_user_by( 'email', $username );\n } else {\n $find_user = get_user_by( 'login', $username );\n }\n\n if ( $find_user && ! is_wp_error( $find_user ) && in_array( 'subscriber', $find_user->roles, true ) ) {\n return $find_user;\n }\n \n return $user;\n}\nadd_filter( 'authenticate', 'wpse_password_less_login_authentication', 40, 3 );\n</code></pre>\n<p>This function should go inside your themes <code>functions.php</code> (or included files) or inside an active plugin file.</p>\n"
}
] | 2020/12/24 | [
"https://wordpress.stackexchange.com/questions/380408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199437/"
] | If I try to change my email address, it will say it has sent a confirmation email to the new email address. But, I do not see any email request to that email.
Is there a way to troubleshoot this or understand the error? | Yes, you can add an [authenticate](https://developer.wordpress.org/reference/hooks/authenticate/) filter to handle the email and no password case with a higher priority than the default wp\_authenticate\_email\_password handler. e.g. (untested)
```php
function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {
if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {
// Already handled by a higher-priority filter
return $user;
}
if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {
// This is an email login with empty password
$user = get_user_by( 'email', $email );
if ( $user && ! is_wp_error( $user ) ) {
// TODO: Verify that the user is someone you'd want to login without
// a password. For now, let's reject anyone who can edit posts.
if ( $user->has_cap( 'edit_posts' ) ) {
$error = new WP_Error();
// TODO: localize the error message
$error->add( 'empty_password',
'<strong>Error</strong>: This user requires a password.' );
return $error;
}
// We'll allow this user to login without a password.
// Return the user object and the calling code will handle the login.
return $user;
}
// else could not fetch the user by email address.
// You'll probably now get a 'password field is empty' error
// from a later filter.
// TODO: If you want a different error then generate it here.
}
return $user;
}
// Add an authenticate filter with a higher priority (= lower number) than
// wp_authenticate_email_password which has priority 20.
add_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );
``` |
380,430 | <p>Hi all and happy holidays!</p>
<p>I have a page on which I enabled threaded commenting. At present, the comments are ordered new to old by when the thread started:</p>
<pre><code>-Comment 3
-Comment 2
-Comment 5
-Comment 1
-Comment 4
</code></pre>
<p>Actually, I want the last active thread to be the first, in such a way that the listing would resemble:</p>
<pre><code>-Comment 2
-Comment 5
-Comment 1
-Comment 4
-Comment 3
</code></pre>
<p>How could this be achieved?</p>
| [
{
"answer_id": 380358,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, you can add an <a href=\"https://developer.wordpress.org/reference/hooks/authenticate/\" rel=\"nofollow noreferrer\">authenticate</a> filter to handle the email and no password case with a higher priority than the default wp_authenticate_email_password handler. e.g. (untested)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {\n if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {\n // Already handled by a higher-priority filter\n return $user;\n }\n\n if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {\n // This is an email login with empty password\n $user = get_user_by( 'email', $email );\n\n if ( $user && ! is_wp_error( $user ) ) {\n // TODO: Verify that the user is someone you'd want to login without\n // a password. For now, let's reject anyone who can edit posts.\n if ( $user->has_cap( 'edit_posts' ) ) {\n $error = new WP_Error();\n // TODO: localize the error message\n $error->add( 'empty_password',\n '<strong>Error</strong>: This user requires a password.' );\n return $error;\n }\n\n // We'll allow this user to login without a password.\n // Return the user object and the calling code will handle the login.\n return $user;\n }\n // else could not fetch the user by email address.\n // You'll probably now get a 'password field is empty' error\n // from a later filter.\n // TODO: If you want a different error then generate it here.\n }\n\n return $user;\n}\n\n// Add an authenticate filter with a higher priority (= lower number) than\n// wp_authenticate_email_password which has priority 20.\nadd_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 380359,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress core is full of surprises. You can do many things with that.</p>\n<p>To provide a password less login to desired user role, you can modify how WordPress handles user login authentication. There is a filter named <code>authenticate</code>, which you can use to hook in, and extend the authorization process to enable that.</p>\n<p>WordPress itself hook into this callback with 3 separate function -</p>\n<ul>\n<li><code>wp_authenticate_cookie</code> - This validates if the user is already logged-in.</li>\n<li><code>wp_authenticate_username_password</code> - This validate user_name/password combo</li>\n<li><code>wp_authenticate_email_password</code> - This validates email/password combo.</li>\n</ul>\n<p>Above functions are hooked with a priority of <code>30</code>.\nYou can hook with a function here with higher priority and check if any of these validation returns a <code>WP_Error</code> object. For empty password, the error code would be <code>empty_password</code>. If the error and error code matches, you can perform further validation to test if there is a user with that login/email, and if he is a subscriber.</p>\n<p>Sounds Good? Here's the code -</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_password_less_login_authentication( $user, $username, $password ) {\n if (! is_wp_error($user) && 'empty_password ' !== $user->get_error_code()) {\n return $user;\n }\n\n if (strpos($username, '@')) {\n $find_user = get_user_by( 'email', $username );\n } else {\n $find_user = get_user_by( 'login', $username );\n }\n\n if ( $find_user && ! is_wp_error( $find_user ) && in_array( 'subscriber', $find_user->roles, true ) ) {\n return $find_user;\n }\n \n return $user;\n}\nadd_filter( 'authenticate', 'wpse_password_less_login_authentication', 40, 3 );\n</code></pre>\n<p>This function should go inside your themes <code>functions.php</code> (or included files) or inside an active plugin file.</p>\n"
}
] | 2020/12/25 | [
"https://wordpress.stackexchange.com/questions/380430",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20349/"
] | Hi all and happy holidays!
I have a page on which I enabled threaded commenting. At present, the comments are ordered new to old by when the thread started:
```
-Comment 3
-Comment 2
-Comment 5
-Comment 1
-Comment 4
```
Actually, I want the last active thread to be the first, in such a way that the listing would resemble:
```
-Comment 2
-Comment 5
-Comment 1
-Comment 4
-Comment 3
```
How could this be achieved? | Yes, you can add an [authenticate](https://developer.wordpress.org/reference/hooks/authenticate/) filter to handle the email and no password case with a higher priority than the default wp\_authenticate\_email\_password handler. e.g. (untested)
```php
function wpse_380353_authenticate_email_no_password( $user, $email, $password ) {
if ( is_wp_error( $user ) || ( $user instanceof WP_User ) ) {
// Already handled by a higher-priority filter
return $user;
}
if ( ! empty( $email ) && is_email( $email ) && empty( $password ) ) {
// This is an email login with empty password
$user = get_user_by( 'email', $email );
if ( $user && ! is_wp_error( $user ) ) {
// TODO: Verify that the user is someone you'd want to login without
// a password. For now, let's reject anyone who can edit posts.
if ( $user->has_cap( 'edit_posts' ) ) {
$error = new WP_Error();
// TODO: localize the error message
$error->add( 'empty_password',
'<strong>Error</strong>: This user requires a password.' );
return $error;
}
// We'll allow this user to login without a password.
// Return the user object and the calling code will handle the login.
return $user;
}
// else could not fetch the user by email address.
// You'll probably now get a 'password field is empty' error
// from a later filter.
// TODO: If you want a different error then generate it here.
}
return $user;
}
// Add an authenticate filter with a higher priority (= lower number) than
// wp_authenticate_email_password which has priority 20.
add_filter( 'authenticate', 'wpse_380353_authenticate_email_no_password', 10, 3 );
``` |
380,477 | <p>I'm trying to do a super simple block with two rich text areas - description and custom cta button. The button is saved with SVG inside, everything seems ok, but when I refresh the edited post, it sreams following:</p>
<pre><code>Content generated by `save` function:
<div class="wp-block-avmc-cta"><p class="wp-block-avmc-cta_label">test</p><button class="wp-block-avmc-cta_button button">tlačítko s ikonou&lt;svg xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20" class="ico ico__envelope button_ico" role="img" aria-hidden="true">&lt;g>&lt;g>&lt;path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z">&lt;/path>&lt;/g>&lt;/g>&lt;/svg></button></div>
Content retrieved from post body:
<div class="wp-block-avmc-cta"><p class="wp-block-avmc-cta_label">test</p><button class="wp-block-avmc-cta_button button">tlačítko s ikonou<svg xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewbox="0 0 24 20" class="ico ico__envelope button_ico" role="img" aria-hidden="true"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z"></path></g></g></svg></button></div>
</code></pre>
<p>The SVG content gets HTML encoded which should. It drives me nuts, I've tested what I could, what I'm missing?</p>
<p>Here are my attributes:</p>
<pre><code>attributes: {
label: {
type: 'string',
source: 'html',
selector: 'p',
},
button: {
type: 'text',
source: 'html',
selector: 'button',
}
},
</code></pre>
<p>and here is the save function</p>
<pre><code>export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button}
<RawHTML>
<SVG className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><G><G><Path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></G></G></SVG>
</RawHTML>
</button>
</div >;
}
</code></pre>
<p>I've tested</p>
<ul>
<li>using <code><Icon /></code> element</li>
<li>using simple svg inside the save function</li>
<li>using <code><SVG></code> component</li>
<li>wrapping it up in <code><RawHTML></code></li>
</ul>
<p>Thanks for your help!</p>
<p><strong>I've solved the issue, but a more general and "right" solution is really appreciated, see my answer for details.</strong></p>
| [
{
"answer_id": 380479,
"author": "demopix",
"author_id": 174561,
"author_profile": "https://wordpress.stackexchange.com/users/174561",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need thinking about send open and close tag using HTML Entities\n(<code>&lt;</code>) instead (<)</p>\n"
},
{
"answer_id": 380485,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 1,
"selected": true,
"text": "<p>I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.</p>\n<p>So my workaround without adding any additional HTML element was:</p>\n<pre><code>attributes: {\n button: {\n type: 'string',\n source: 'html',\n selector: 'button',\n }\n},\n</code></pre>\n<p>And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.</p>\n<pre><code>// edit.js\n<RichText\n tagName="div"\n className={className + "_button button"}\n onChange={(val) => setAttributes({ button: val })}\n value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n placeholder={__('Add button title', 'avmc-mat')}\n allowedFormats={ }\n/>\n</code></pre>\n<p>And</p>\n<pre><code>// save.js\nexport default function save({ attributes }) {\nconst className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308\n return <div className={className}>\n <p className={className + "_label"}>{attributes.label}</p>\n <button className={className + "_button button"}>\n {attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n <svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>\n </button>\n </div >;\n}\n</code></pre>\n<p>Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction!</p>\n"
}
] | 2020/12/27 | [
"https://wordpress.stackexchange.com/questions/380477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64771/"
] | I'm trying to do a super simple block with two rich text areas - description and custom cta button. The button is saved with SVG inside, everything seems ok, but when I refresh the edited post, it sreams following:
```
Content generated by `save` function:
<div class="wp-block-avmc-cta"><p class="wp-block-avmc-cta_label">test</p><button class="wp-block-avmc-cta_button button">tlačítko s ikonou<svg xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20" class="ico ico__envelope button_ico" role="img" aria-hidden="true"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z"></path></g></g></svg></button></div>
Content retrieved from post body:
<div class="wp-block-avmc-cta"><p class="wp-block-avmc-cta_label">test</p><button class="wp-block-avmc-cta_button button">tlačítko s ikonou<svg xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewbox="0 0 24 20" class="ico ico__envelope button_ico" role="img" aria-hidden="true"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z"></path></g></g></svg></button></div>
```
The SVG content gets HTML encoded which should. It drives me nuts, I've tested what I could, what I'm missing?
Here are my attributes:
```
attributes: {
label: {
type: 'string',
source: 'html',
selector: 'p',
},
button: {
type: 'text',
source: 'html',
selector: 'button',
}
},
```
and here is the save function
```
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button}
<RawHTML>
<SVG className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><G><G><Path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></G></G></SVG>
</RawHTML>
</button>
</div >;
}
```
I've tested
* using `<Icon />` element
* using simple svg inside the save function
* using `<SVG>` component
* wrapping it up in `<RawHTML>`
Thanks for your help!
**I've solved the issue, but a more general and "right" solution is really appreciated, see my answer for details.** | I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.
So my workaround without adding any additional HTML element was:
```
attributes: {
button: {
type: 'string',
source: 'html',
selector: 'button',
}
},
```
And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.
```
// edit.js
<RichText
tagName="div"
className={className + "_button button"}
onChange={(val) => setAttributes({ button: val })}
value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
placeholder={__('Add button title', 'avmc-mat')}
allowedFormats={ }
/>
```
And
```
// save.js
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
<svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>
</button>
</div >;
}
```
Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction! |
380,513 | <p>In the documentation for <a href="https://developer.wordpress.org/rest-api/reference/posts/" rel="nofollow noreferrer">/posts for WordPress REST API</a> it states that I can add a <code>meta</code>-field. But it doesn't say which format that should be in.</p>
<p>I can find <a href="https://stackoverflow.com/a/56508996/1766219">other guides</a> showing how it should be if using Postman:</p>
<pre class="lang-php prettyprint-override"><code>data = {
"title": "test",
"content": "testingfrompython",
"status": "draft",
"author": 1,
"meta": {
"location": "NYC",
"date": "never",
"event_url": "http: //google.com"
},
"featured_media": 1221
}
</code></pre>
<p>But how should it be setup, if I'm call the endpoint using PHP and cURL?</p>
<hr />
<p>This here works for just creating a post:</p>
<pre class="lang-php prettyprint-override"><code>$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
];
$data_string = json_encode( $data );
$endpoint = 'https://example.org/wp-json/wp/v2/posts';
$protocol = "POST";
$headers = [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
'Authorization: Basic ' . base64_encode( 'MYUSERSEMAIL:APPLICATIONPASSWORD' )
];
$ch = custom_setup_curl_function( $endpoint, $protocol, $data_string, $headers );
$result = json_decode( curl_exec($ch) );
</code></pre>
<p>I've tried all kind of things:</p>
<p><strong>Attempt1</strong></p>
<pre><code>$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
'meta' => [
'my_custom_field' => 'Testing 1234'
]
];
</code></pre>
<p><strong>Attempt2</strong></p>
<pre><code>$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
'meta' => [
[
'key' => 'my_custom_field',
'value' => 'Testing 1234'
]
]
];
</code></pre>
<p>... And I could keep going. Every time it simply creates a post, but doesn't add any of the meta-data to my created custom fields.</p>
<p>I don't get why this is not stated in the documentation for the REST API.</p>
| [
{
"answer_id": 380479,
"author": "demopix",
"author_id": 174561,
"author_profile": "https://wordpress.stackexchange.com/users/174561",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need thinking about send open and close tag using HTML Entities\n(<code>&lt;</code>) instead (<)</p>\n"
},
{
"answer_id": 380485,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 1,
"selected": true,
"text": "<p>I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.</p>\n<p>So my workaround without adding any additional HTML element was:</p>\n<pre><code>attributes: {\n button: {\n type: 'string',\n source: 'html',\n selector: 'button',\n }\n},\n</code></pre>\n<p>And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.</p>\n<pre><code>// edit.js\n<RichText\n tagName="div"\n className={className + "_button button"}\n onChange={(val) => setAttributes({ button: val })}\n value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n placeholder={__('Add button title', 'avmc-mat')}\n allowedFormats={ }\n/>\n</code></pre>\n<p>And</p>\n<pre><code>// save.js\nexport default function save({ attributes }) {\nconst className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308\n return <div className={className}>\n <p className={className + "_label"}>{attributes.label}</p>\n <button className={className + "_button button"}>\n {attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n <svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>\n </button>\n </div >;\n}\n</code></pre>\n<p>Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction!</p>\n"
}
] | 2020/12/28 | [
"https://wordpress.stackexchange.com/questions/380513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | In the documentation for [/posts for WordPress REST API](https://developer.wordpress.org/rest-api/reference/posts/) it states that I can add a `meta`-field. But it doesn't say which format that should be in.
I can find [other guides](https://stackoverflow.com/a/56508996/1766219) showing how it should be if using Postman:
```php
data = {
"title": "test",
"content": "testingfrompython",
"status": "draft",
"author": 1,
"meta": {
"location": "NYC",
"date": "never",
"event_url": "http: //google.com"
},
"featured_media": 1221
}
```
But how should it be setup, if I'm call the endpoint using PHP and cURL?
---
This here works for just creating a post:
```php
$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
];
$data_string = json_encode( $data );
$endpoint = 'https://example.org/wp-json/wp/v2/posts';
$protocol = "POST";
$headers = [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
'Authorization: Basic ' . base64_encode( 'MYUSERSEMAIL:APPLICATIONPASSWORD' )
];
$ch = custom_setup_curl_function( $endpoint, $protocol, $data_string, $headers );
$result = json_decode( curl_exec($ch) );
```
I've tried all kind of things:
**Attempt1**
```
$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
'meta' => [
'my_custom_field' => 'Testing 1234'
]
];
```
**Attempt2**
```
$data = [
'title' => 'Test post',
'status' => 'draft',
'content' => 'Some content',
'meta' => [
[
'key' => 'my_custom_field',
'value' => 'Testing 1234'
]
]
];
```
... And I could keep going. Every time it simply creates a post, but doesn't add any of the meta-data to my created custom fields.
I don't get why this is not stated in the documentation for the REST API. | I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.
So my workaround without adding any additional HTML element was:
```
attributes: {
button: {
type: 'string',
source: 'html',
selector: 'button',
}
},
```
And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.
```
// edit.js
<RichText
tagName="div"
className={className + "_button button"}
onChange={(val) => setAttributes({ button: val })}
value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
placeholder={__('Add button title', 'avmc-mat')}
allowedFormats={ }
/>
```
And
```
// save.js
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
<svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>
</button>
</div >;
}
```
Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction! |
380,527 | <p>i want to disable, hide or remove delete buttons from category page</p>
<p><a href="https://i.stack.imgur.com/DuEcr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DuEcr.png" alt="enter image description here" /></a></p>
<p>I tried editing functions.php with no luck:</p>
<pre><code>add_action('admin_head', 'hide_category_buttons');
function hide_category_buttons() {
echo '<style>
.taxonomy-category tr:hover .row-actions {
visibility: hidden;
}
</style>';
}
</code></pre>
| [
{
"answer_id": 380479,
"author": "demopix",
"author_id": 174561,
"author_profile": "https://wordpress.stackexchange.com/users/174561",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need thinking about send open and close tag using HTML Entities\n(<code>&lt;</code>) instead (<)</p>\n"
},
{
"answer_id": 380485,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 1,
"selected": true,
"text": "<p>I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.</p>\n<p>So my workaround without adding any additional HTML element was:</p>\n<pre><code>attributes: {\n button: {\n type: 'string',\n source: 'html',\n selector: 'button',\n }\n},\n</code></pre>\n<p>And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.</p>\n<pre><code>// edit.js\n<RichText\n tagName="div"\n className={className + "_button button"}\n onChange={(val) => setAttributes({ button: val })}\n value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n placeholder={__('Add button title', 'avmc-mat')}\n allowedFormats={ }\n/>\n</code></pre>\n<p>And</p>\n<pre><code>// save.js\nexport default function save({ attributes }) {\nconst className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308\n return <div className={className}>\n <p className={className + "_label"}>{attributes.label}</p>\n <button className={className + "_button button"}>\n {attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n <svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>\n </button>\n </div >;\n}\n</code></pre>\n<p>Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction!</p>\n"
}
] | 2020/12/28 | [
"https://wordpress.stackexchange.com/questions/380527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199552/"
] | i want to disable, hide or remove delete buttons from category page
[](https://i.stack.imgur.com/DuEcr.png)
I tried editing functions.php with no luck:
```
add_action('admin_head', 'hide_category_buttons');
function hide_category_buttons() {
echo '<style>
.taxonomy-category tr:hover .row-actions {
visibility: hidden;
}
</style>';
}
``` | I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.
So my workaround without adding any additional HTML element was:
```
attributes: {
button: {
type: 'string',
source: 'html',
selector: 'button',
}
},
```
And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.
```
// edit.js
<RichText
tagName="div"
className={className + "_button button"}
onChange={(val) => setAttributes({ button: val })}
value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
placeholder={__('Add button title', 'avmc-mat')}
allowedFormats={ }
/>
```
And
```
// save.js
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
<svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>
</button>
</div >;
}
```
Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction! |
380,548 | <p>After a malware attack I am trying to replace a malicious call entries. I keep getting syntax errors due to the configuration of the link. Tried all of the various escape characters to now avail. Familiar with normal find and replace but due to unique code in links <code>update _DVB_posts set post_content = replace(post_content,'<script src=''https\;//`port`.transandfiestas.ga/stat.js?ft=ms'' type=''text/javascript''></script>',' '); </code></p>
<p>I've included one of my versions. Any help would be appreciated.</p>
| [
{
"answer_id": 380479,
"author": "demopix",
"author_id": 174561,
"author_profile": "https://wordpress.stackexchange.com/users/174561",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need thinking about send open and close tag using HTML Entities\n(<code>&lt;</code>) instead (<)</p>\n"
},
{
"answer_id": 380485,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 1,
"selected": true,
"text": "<p>I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.</p>\n<p>So my workaround without adding any additional HTML element was:</p>\n<pre><code>attributes: {\n button: {\n type: 'string',\n source: 'html',\n selector: 'button',\n }\n},\n</code></pre>\n<p>And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.</p>\n<pre><code>// edit.js\n<RichText\n tagName="div"\n className={className + "_button button"}\n onChange={(val) => setAttributes({ button: val })}\n value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n placeholder={__('Add button title', 'avmc-mat')}\n allowedFormats={ }\n/>\n</code></pre>\n<p>And</p>\n<pre><code>// save.js\nexport default function save({ attributes }) {\nconst className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308\n return <div className={className}>\n <p className={className + "_label"}>{attributes.label}</p>\n <button className={className + "_button button"}>\n {attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n <svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>\n </button>\n </div >;\n}\n</code></pre>\n<p>Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction!</p>\n"
}
] | 2020/12/29 | [
"https://wordpress.stackexchange.com/questions/380548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199566/"
] | After a malware attack I am trying to replace a malicious call entries. I keep getting syntax errors due to the configuration of the link. Tried all of the various escape characters to now avail. Familiar with normal find and replace but due to unique code in links `update _DVB_posts set post_content = replace(post_content,'<script src=''https\;//`port`.transandfiestas.ga/stat.js?ft=ms'' type=''text/javascript''></script>',' ');`
I've included one of my versions. Any help would be appreciated. | I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.
So my workaround without adding any additional HTML element was:
```
attributes: {
button: {
type: 'string',
source: 'html',
selector: 'button',
}
},
```
And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.
```
// edit.js
<RichText
tagName="div"
className={className + "_button button"}
onChange={(val) => setAttributes({ button: val })}
value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
placeholder={__('Add button title', 'avmc-mat')}
allowedFormats={ }
/>
```
And
```
// save.js
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
<svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>
</button>
</div >;
}
```
Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction! |
380,568 | <p>I'm trying to match users' data in multiple wordpress applications, so when user created on one app the same user should be created on the other apps.
Here is the problem, I need to get the new created user plain password (outside of wordpress core) before being inserted on one of my apps so that I could insert this user data properly on the other apps.
Is there any action/filter or method to do so?</p>
| [
{
"answer_id": 380479,
"author": "demopix",
"author_id": 174561,
"author_profile": "https://wordpress.stackexchange.com/users/174561",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need thinking about send open and close tag using HTML Entities\n(<code>&lt;</code>) instead (<)</p>\n"
},
{
"answer_id": 380485,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 1,
"selected": true,
"text": "<p>I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.</p>\n<p>So my workaround without adding any additional HTML element was:</p>\n<pre><code>attributes: {\n button: {\n type: 'string',\n source: 'html',\n selector: 'button',\n }\n},\n</code></pre>\n<p>And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.</p>\n<pre><code>// edit.js\n<RichText\n tagName="div"\n className={className + "_button button"}\n onChange={(val) => setAttributes({ button: val })}\n value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n placeholder={__('Add button title', 'avmc-mat')}\n allowedFormats={ }\n/>\n</code></pre>\n<p>And</p>\n<pre><code>// save.js\nexport default function save({ attributes }) {\nconst className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308\n return <div className={className}>\n <p className={className + "_label"}>{attributes.label}</p>\n <button className={className + "_button button"}>\n {attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}\n <svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>\n </button>\n </div >;\n}\n</code></pre>\n<p>Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction!</p>\n"
}
] | 2020/12/29 | [
"https://wordpress.stackexchange.com/questions/380568",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199583/"
] | I'm trying to match users' data in multiple wordpress applications, so when user created on one app the same user should be created on the other apps.
Here is the problem, I need to get the new created user plain password (outside of wordpress core) before being inserted on one of my apps so that I could insert this user data properly on the other apps.
Is there any action/filter or method to do so? | I was playing around with a couple of more hours it and it seems that type "text" is not equal to inner text, it still grabs innerHTML kind of encoded to entities. I've found that out, but forgot to filter it in the save function, which hasn't had an impact on saving (as expected, since the value was from the input field), but for validation yes.
So my workaround without adding any additional HTML element was:
```
attributes: {
button: {
type: 'string',
source: 'html',
selector: 'button',
}
},
```
And then strip HTML out of the attributes.button value each time when used - in edit function & on the frontend, which did the trick.
```
// edit.js
<RichText
tagName="div"
className={className + "_button button"}
onChange={(val) => setAttributes({ button: val })}
value={attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
placeholder={__('Add button title', 'avmc-mat')}
allowedFormats={ }
/>
```
And
```
// save.js
export default function save({ attributes }) {
const className = getBlockDefaultClassName('avmc/cta'); //https://github.com/WordPress/gutenberg/issues/7308
return <div className={className}>
<p className={className + "_label"}>{attributes.label}</p>
<button className={className + "_button button"}>
{attributes.button ? attributes.button.replace(/<[^>]*>?/gm, '') : ''}
<svg className="ico ico__envelope button_ico" xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 24 20"><g><g><path d="M13.78 10.188l-1.483 1.329a.593.593 0 0 1-.793.004l-1.444-1.29-5.324 4.978a.596.596 0 0 1-.814-.87L9.166 9.43 3.9 4.725a.592.592 0 0 1-.048-.84.593.593 0 0 1 .84-.049l5.698 5.097a.96.96 0 0 1 .097.083c0 .005.005.01.01.014l1.399 1.25 7.177-6.44a.598.598 0 0 1 .841.045.599.599 0 0 1-.043.84l-5.205 4.666 5.226 4.96a.597.597 0 0 1-.41 1.026.595.595 0 0 1-.409-.163l-5.292-5.026zm10.19 7.258v-15.5c0-1.103-.898-2-2.001-2h-20c-1.103 0-2 .897-2 2v15.5c0 1.103.897 2 2 2h20c1.103 0 2-.897 2-2z" /></g></g></svg>
</button>
</div >;
}
```
Hope it will be helpful for someone else´. If there is a "built in" function for that, I it would really appreciate pointing me the right direction! |
380,584 | <p>I've got a custom theme I build using an underscores starter theme. Inside one of my template files (page-talent.php) I've got this jQuery ajax function:</p>
<pre><code> $.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
// data: { action : 'get_ajax_posts' },
data: { action : 'get_ajax_posts' , filters: filters },
success: function( response ) {
console.log( response );
//alert(response);
$( '.posts-area' ).html( response );
}
});
})
</code></pre>
<p>then I'm running the code in admin-ajax.php inside the admin folder. I'm not sure why I did that (rather than someplace inside my theme directory) other than that's what some of posts in this forum said to do.</p>
<p>The Problem is that when wordpress updates it wipes it out. So the question is how can I put this inside my theme? I tried just calling a file inside my theme folder and it didn't work.</p>
<p>here is my code that I placed inside the existing admin-ajax.php right before the do_action( 'admin_init' ); section. Again this works fine inside this file, but it gets wiped out every time I update the version of wordpress.</p>
<pre><code>// ------------------------------
// ------------------------------
// talent query code
// ------------------------------
// ------------------------------
function get_ajax_posts() {
// get filters from 3 drop down menus
$tax_query = $_POST['filters'];
$location = $tax_query['location'];
$specialty = $tax_query['specialty'];
$levels = $tax_query['level'];
// create levels array for selected level and above
switch ($levels) {
case 23:
$level = array('23'); // Level 1 through 5
break;
case 24:
$level = array('24'); // Level 2 through 5
break;
case 25:
$level = array('25');// Level 3 through 5
break;
case 26:
$level = array('26');// Level 4 and 5
break;
case 27:
$level = '27';// Level 5
break;
default:
$level = array('23', '24', '25', '26', '27');
}
// Display Talent if only Level is selected
if(isset($tax_query['level']) && empty($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
),
);
}
// Display Talent if only Level and Location is selected
else if(isset($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
),
);
}
// Display Talent if all three are selected
else if(isset($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if Level and specialty is selected
else if(isset($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if only Location is selected
else if(empty($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
),
);
}
// Display Talent if Location and specialty is selected
else if(empty($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if only specialty is selected
else if(empty($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
else{
$args = null;
//echo "else Args: ". $args;
}
wp_reset_query();
// The Query
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
//$response .= get_template_part('products');
$response .= "";
$name = get_field('name');
$main_image = get_field('main_image');
?>
<div class="col-sm-6 col-md-3 talent-col">
<div class="talent">
<a type="button" href="<?php the_permalink() ?>">
<img class="img-responsive" src="<?php echo $main_image; ?>">
<h3 class="dark"><?php echo $name; ?></h3>
</a>
</div><!-- close talent -->
</div><!-- close col -->
<?php
}// end while
} else {
$response .= get_template_part('none');
}
exit; // leave ajax call
}// end get_ajax_posts
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
//===================
// end talent query code
//===================
</code></pre>
<p>If I add this to my functions.php file how do I call it from the Ajax function? Or If I just move the function get_ajax_posts() to a new file (talent-ajax.php) inside my theme folder how do I call that from the ajax function. In other words... what would this part be changed to reach that file?</p>
<pre><code>url: '<?php echo admin_url('admin-ajax.php');?>',
</code></pre>
| [
{
"answer_id": 380586,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 1,
"selected": false,
"text": "<p>Add this all to your theme functions.php file and try again..</p>\n"
},
{
"answer_id": 380587,
"author": "Simon",
"author_id": 197404,
"author_profile": "https://wordpress.stackexchange.com/users/197404",
"pm_score": 2,
"selected": false,
"text": "<p>You should never edit any files in the wp-admin directory. All ajax related to your theme, should be inside your theme directory. You can place your PHP code in any file, functions.php, or include some new file there you will retrive only ajax cals, that will be better.</p>\n"
}
] | 2020/12/29 | [
"https://wordpress.stackexchange.com/questions/380584",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94432/"
] | I've got a custom theme I build using an underscores starter theme. Inside one of my template files (page-talent.php) I've got this jQuery ajax function:
```
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
// data: { action : 'get_ajax_posts' },
data: { action : 'get_ajax_posts' , filters: filters },
success: function( response ) {
console.log( response );
//alert(response);
$( '.posts-area' ).html( response );
}
});
})
```
then I'm running the code in admin-ajax.php inside the admin folder. I'm not sure why I did that (rather than someplace inside my theme directory) other than that's what some of posts in this forum said to do.
The Problem is that when wordpress updates it wipes it out. So the question is how can I put this inside my theme? I tried just calling a file inside my theme folder and it didn't work.
here is my code that I placed inside the existing admin-ajax.php right before the do\_action( 'admin\_init' ); section. Again this works fine inside this file, but it gets wiped out every time I update the version of wordpress.
```
// ------------------------------
// ------------------------------
// talent query code
// ------------------------------
// ------------------------------
function get_ajax_posts() {
// get filters from 3 drop down menus
$tax_query = $_POST['filters'];
$location = $tax_query['location'];
$specialty = $tax_query['specialty'];
$levels = $tax_query['level'];
// create levels array for selected level and above
switch ($levels) {
case 23:
$level = array('23'); // Level 1 through 5
break;
case 24:
$level = array('24'); // Level 2 through 5
break;
case 25:
$level = array('25');// Level 3 through 5
break;
case 26:
$level = array('26');// Level 4 and 5
break;
case 27:
$level = '27';// Level 5
break;
default:
$level = array('23', '24', '25', '26', '27');
}
// Display Talent if only Level is selected
if(isset($tax_query['level']) && empty($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
),
);
}
// Display Talent if only Level and Location is selected
else if(isset($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
),
);
}
// Display Talent if all three are selected
else if(isset($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if Level and specialty is selected
else if(isset($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
),
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if only Location is selected
else if(empty($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
),
);
}
// Display Talent if Location and specialty is selected
else if(empty($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location,
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
// Display Talent if only specialty is selected
else if(empty($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){
// Query Arguments
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'the-talent',
'posts_per_page'=>-1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => $specialty,
),
),
);
}
else{
$args = null;
//echo "else Args: ". $args;
}
wp_reset_query();
// The Query
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
//$response .= get_template_part('products');
$response .= "";
$name = get_field('name');
$main_image = get_field('main_image');
?>
<div class="col-sm-6 col-md-3 talent-col">
<div class="talent">
<a type="button" href="<?php the_permalink() ?>">
<img class="img-responsive" src="<?php echo $main_image; ?>">
<h3 class="dark"><?php echo $name; ?></h3>
</a>
</div><!-- close talent -->
</div><!-- close col -->
<?php
}// end while
} else {
$response .= get_template_part('none');
}
exit; // leave ajax call
}// end get_ajax_posts
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
//===================
// end talent query code
//===================
```
If I add this to my functions.php file how do I call it from the Ajax function? Or If I just move the function get\_ajax\_posts() to a new file (talent-ajax.php) inside my theme folder how do I call that from the ajax function. In other words... what would this part be changed to reach that file?
```
url: '<?php echo admin_url('admin-ajax.php');?>',
``` | You should never edit any files in the wp-admin directory. All ajax related to your theme, should be inside your theme directory. You can place your PHP code in any file, functions.php, or include some new file there you will retrive only ajax cals, that will be better. |
380,618 | <p>I am working on a simple plugin that shows an HTML form where the user can input a keyword which is used to query an external API. I currently have the form and the related jQuery set up, but when passed to the plugin's PHP file, I get a response of simply 0. At this point I'm only just trying to get any response but 0 (see the <code>echo "Whyyyy"</code> part). I've been scouring the internet and feel like I have tried everything that's been suggested, leading me to think I'm making a mistake somewhere.</p>
<p>Any help would be greatly appreciated. </p>
<p>This is the plugin's PHP:</p>
<pre class="lang-php prettyprint-override"><code>defined('ABSPATH') or die('Ah ah ah. You didn\'t say the magic word.');
class News_search {
// Load scripts upon class initiation
public function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_get_news_callback', 'get_news_callback');
add_action('wp_ajax_nopriv_get_news_callback', 'get_news_callback');
add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));
}
function enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));
// Enqueue and localize JS
wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);
wp_localize_script('ajax-script', 'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('my-string-shh'),
));
}
// Handle AJAX request
function get_news_callback() {
check_ajax_referer('my-special-string', 'security');
$keyword = isset($_POST['news-keyword']) ? $_POST['news-keyword'] : null;
echo "Whyyyy";
die();
}
public function wp_news_search_form() {
$content .= '<form id="wp-news-search__form">
<label>
<input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>
</label>
<button id="wp-news-search__submit">' .
__('Search for news', 'wp-news-search') .
'</button>
</form>';
return $content;
}
}
new News_search();
</code></pre>
<p>And this is the JS file:</p>
<pre class="lang-js prettyprint-override"><code>(function ($) {
$(document).ready(function () {
$('#wp-news-search__form').submit(function (event) {
event.preventDefault();
// const keyword = $('#query-input').val();
const values = $(this).serialize();
if (values) {
// send stuff to php
console.log(values);
const data = {
action: 'get_news_callback',
status: 'enabled',
security: ajax_object.security,
form_data: values
}
$.post(ajax_object.ajax_url, data, function(response) {
if (response) {
console.log(`Response is: ${response}`);
}
})
.fail(() => { console.error('error'); })
.always(() => { console.log('form submitted') });
}
});
});
})(jQuery);
</code></pre>
| [
{
"answer_id": 380619,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>check_ajax_referer()</code> function will <code>die()</code> if the check fails, which is why you won't see anything after it, and the reason it's failing is that the action names given to <code>wp_create_nonce()</code> and <code>check_ajax_referer()</code> do not match.</p>\n<p>Here you're using one string, <code>'my-string-shh'</code>:</p>\n<pre><code>'security' => wp_create_nonce('my-string-shh'),\n</code></pre>\n<p>But here you're using another, <code>'my-special-string'</code>:</p>\n<pre><code>check_ajax_referer('my-special-string', 'security');\n</code></pre>\n<p>These need to match.</p>\n"
},
{
"answer_id": 380627,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>your ajax post callable function action "<strong>get_news_callback</strong>" not working in your Class __construct() becuase You Can use simple Wordpress action in the class.</p>\n<p>Use Action In The Class :</p>\n<blockquote>\n<p>add_action('wp_ajax_get_news_callback', array($this,\n'get_news_callback'));\nadd_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));</p>\n</blockquote>\n<p>your Script also change So you Can Use below script to get your ajax response .</p>\n<pre><code>defined('ABSPATH') or die('Ah ah ah. You didn\\'t say the magic word.');\n\nclass News_search {\n\n// Load scripts upon class initiation\npublic function __construct() {\n add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));\n add_action('wp_ajax_get_news_callback', array($this, 'get_news_callback'));\n add_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));\n add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));\n}\n\nfunction enqueue_scripts() {\n // Enqueue CSS\n wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));\n // Enqueue and localize JS\n wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);\n wp_localize_script('ajax-script', 'ajax_object',\n array('ajax_url' => admin_url('admin-ajax.php'),\n 'security' => wp_create_nonce('my-string-shh'),\n ));\n}\n\n// Handle AJAX request\npublic function get_news_callback() {\n \n check_ajax_referer('my-string-shh', 'security');\n\n $keyword = isset($_POST['form_data']) ? $_POST['form_data'] : null;\n \n echo $keyword;\n \n die();\n\n}\n\n\n\npublic function wp_news_search_form() {\n $content .= '<form id="wp-news-search__form">\n <label>\n <input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>\n </label>\n <button id="wp-news-search__submit">' .\n __('Search for news', 'wp-news-search') .\n '</button>\n </form>';\n return $content;\n }\n\n }\n\n new News_search();\n</code></pre>\n<p>Your Js</p>\n<pre><code>(function ($) {\n\n$(document).ready(function () {\n $('#wp-news-search__form').submit(function (event) {\n event.preventDefault();\n\n // const keyword = $('#query-input').val();\n const values = $(this).serialize();\n\n\n if (values) {\n // send stuff to php\n console.log(values);\n const data = {\n action: 'get_news_callback',\n status: 'enabled',\n type: "POST",\n security: ajax_object.security,\n form_data: values \n }\n\n $.post(ajax_object.ajax_url, data, function(response) {\n if (response) {\n console.log(`Response is: ${response}`);\n }\n })\n .fail(() => { console.error('error'); })\n .always(() => { console.log('form submitted') });\n }\n\n });\n\n\n });\n\n})(jQuery);\n</code></pre>\n"
}
] | 2020/12/30 | [
"https://wordpress.stackexchange.com/questions/380618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199623/"
] | I am working on a simple plugin that shows an HTML form where the user can input a keyword which is used to query an external API. I currently have the form and the related jQuery set up, but when passed to the plugin's PHP file, I get a response of simply 0. At this point I'm only just trying to get any response but 0 (see the `echo "Whyyyy"` part). I've been scouring the internet and feel like I have tried everything that's been suggested, leading me to think I'm making a mistake somewhere.
Any help would be greatly appreciated.
This is the plugin's PHP:
```php
defined('ABSPATH') or die('Ah ah ah. You didn\'t say the magic word.');
class News_search {
// Load scripts upon class initiation
public function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_get_news_callback', 'get_news_callback');
add_action('wp_ajax_nopriv_get_news_callback', 'get_news_callback');
add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));
}
function enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));
// Enqueue and localize JS
wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);
wp_localize_script('ajax-script', 'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('my-string-shh'),
));
}
// Handle AJAX request
function get_news_callback() {
check_ajax_referer('my-special-string', 'security');
$keyword = isset($_POST['news-keyword']) ? $_POST['news-keyword'] : null;
echo "Whyyyy";
die();
}
public function wp_news_search_form() {
$content .= '<form id="wp-news-search__form">
<label>
<input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>
</label>
<button id="wp-news-search__submit">' .
__('Search for news', 'wp-news-search') .
'</button>
</form>';
return $content;
}
}
new News_search();
```
And this is the JS file:
```js
(function ($) {
$(document).ready(function () {
$('#wp-news-search__form').submit(function (event) {
event.preventDefault();
// const keyword = $('#query-input').val();
const values = $(this).serialize();
if (values) {
// send stuff to php
console.log(values);
const data = {
action: 'get_news_callback',
status: 'enabled',
security: ajax_object.security,
form_data: values
}
$.post(ajax_object.ajax_url, data, function(response) {
if (response) {
console.log(`Response is: ${response}`);
}
})
.fail(() => { console.error('error'); })
.always(() => { console.log('form submitted') });
}
});
});
})(jQuery);
``` | your ajax post callable function action "**get\_news\_callback**" not working in your Class \_\_construct() becuase You Can use simple Wordpress action in the class.
Use Action In The Class :
>
> add\_action('wp\_ajax\_get\_news\_callback', array($this,
> 'get\_news\_callback'));
> add\_action('wp\_ajax\_nopriv\_get\_news\_callback', array($this, 'get\_news\_callback'));
>
>
>
your Script also change So you Can Use below script to get your ajax response .
```
defined('ABSPATH') or die('Ah ah ah. You didn\'t say the magic word.');
class News_search {
// Load scripts upon class initiation
public function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_get_news_callback', array($this, 'get_news_callback'));
add_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));
add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));
}
function enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));
// Enqueue and localize JS
wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);
wp_localize_script('ajax-script', 'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('my-string-shh'),
));
}
// Handle AJAX request
public function get_news_callback() {
check_ajax_referer('my-string-shh', 'security');
$keyword = isset($_POST['form_data']) ? $_POST['form_data'] : null;
echo $keyword;
die();
}
public function wp_news_search_form() {
$content .= '<form id="wp-news-search__form">
<label>
<input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>
</label>
<button id="wp-news-search__submit">' .
__('Search for news', 'wp-news-search') .
'</button>
</form>';
return $content;
}
}
new News_search();
```
Your Js
```
(function ($) {
$(document).ready(function () {
$('#wp-news-search__form').submit(function (event) {
event.preventDefault();
// const keyword = $('#query-input').val();
const values = $(this).serialize();
if (values) {
// send stuff to php
console.log(values);
const data = {
action: 'get_news_callback',
status: 'enabled',
type: "POST",
security: ajax_object.security,
form_data: values
}
$.post(ajax_object.ajax_url, data, function(response) {
if (response) {
console.log(`Response is: ${response}`);
}
})
.fail(() => { console.error('error'); })
.always(() => { console.log('form submitted') });
}
});
});
})(jQuery);
``` |
380,686 | <p>I want to display a count of items in my header, a count of how many items are in the current category...</p>
<p>Example:
User goes to "T Shirts" > in the header it says "20 Items" --- They go to "Hoodies" > Header says "10 Items"</p>
<p>I'm currently using a shortcode and code in functions.php:</p>
<pre class="lang-php prettyprint-override"><code>add_shortcode( 'products-counter', 'products_counter' );
function products_counter( $atts ) {
$atts = shortcode_atts( [
'category' => '',
], $atts );
$taxonomy = 'product_cat';
if ( is_numeric( $atts['category'] ) ) {
$cat = get_term( $atts['category'], $taxonomy );
} else {
$cat = get_term_by( 'slug', $atts['category'], $taxonomy );
}
if ( $cat && ! is_wp_error( $cat ) ) {
return $cat->count;
}
return '';
}
</code></pre>
<p>Which works great if I define the product category in the shortcode... My issue is it's in the header, so all category pages say the same item count... Is there a way to get it to display based on url?</p>
| [
{
"answer_id": 380619,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>check_ajax_referer()</code> function will <code>die()</code> if the check fails, which is why you won't see anything after it, and the reason it's failing is that the action names given to <code>wp_create_nonce()</code> and <code>check_ajax_referer()</code> do not match.</p>\n<p>Here you're using one string, <code>'my-string-shh'</code>:</p>\n<pre><code>'security' => wp_create_nonce('my-string-shh'),\n</code></pre>\n<p>But here you're using another, <code>'my-special-string'</code>:</p>\n<pre><code>check_ajax_referer('my-special-string', 'security');\n</code></pre>\n<p>These need to match.</p>\n"
},
{
"answer_id": 380627,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>your ajax post callable function action "<strong>get_news_callback</strong>" not working in your Class __construct() becuase You Can use simple Wordpress action in the class.</p>\n<p>Use Action In The Class :</p>\n<blockquote>\n<p>add_action('wp_ajax_get_news_callback', array($this,\n'get_news_callback'));\nadd_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));</p>\n</blockquote>\n<p>your Script also change So you Can Use below script to get your ajax response .</p>\n<pre><code>defined('ABSPATH') or die('Ah ah ah. You didn\\'t say the magic word.');\n\nclass News_search {\n\n// Load scripts upon class initiation\npublic function __construct() {\n add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));\n add_action('wp_ajax_get_news_callback', array($this, 'get_news_callback'));\n add_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));\n add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));\n}\n\nfunction enqueue_scripts() {\n // Enqueue CSS\n wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));\n // Enqueue and localize JS\n wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);\n wp_localize_script('ajax-script', 'ajax_object',\n array('ajax_url' => admin_url('admin-ajax.php'),\n 'security' => wp_create_nonce('my-string-shh'),\n ));\n}\n\n// Handle AJAX request\npublic function get_news_callback() {\n \n check_ajax_referer('my-string-shh', 'security');\n\n $keyword = isset($_POST['form_data']) ? $_POST['form_data'] : null;\n \n echo $keyword;\n \n die();\n\n}\n\n\n\npublic function wp_news_search_form() {\n $content .= '<form id="wp-news-search__form">\n <label>\n <input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>\n </label>\n <button id="wp-news-search__submit">' .\n __('Search for news', 'wp-news-search') .\n '</button>\n </form>';\n return $content;\n }\n\n }\n\n new News_search();\n</code></pre>\n<p>Your Js</p>\n<pre><code>(function ($) {\n\n$(document).ready(function () {\n $('#wp-news-search__form').submit(function (event) {\n event.preventDefault();\n\n // const keyword = $('#query-input').val();\n const values = $(this).serialize();\n\n\n if (values) {\n // send stuff to php\n console.log(values);\n const data = {\n action: 'get_news_callback',\n status: 'enabled',\n type: "POST",\n security: ajax_object.security,\n form_data: values \n }\n\n $.post(ajax_object.ajax_url, data, function(response) {\n if (response) {\n console.log(`Response is: ${response}`);\n }\n })\n .fail(() => { console.error('error'); })\n .always(() => { console.log('form submitted') });\n }\n\n });\n\n\n });\n\n})(jQuery);\n</code></pre>\n"
}
] | 2020/12/31 | [
"https://wordpress.stackexchange.com/questions/380686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104841/"
] | I want to display a count of items in my header, a count of how many items are in the current category...
Example:
User goes to "T Shirts" > in the header it says "20 Items" --- They go to "Hoodies" > Header says "10 Items"
I'm currently using a shortcode and code in functions.php:
```php
add_shortcode( 'products-counter', 'products_counter' );
function products_counter( $atts ) {
$atts = shortcode_atts( [
'category' => '',
], $atts );
$taxonomy = 'product_cat';
if ( is_numeric( $atts['category'] ) ) {
$cat = get_term( $atts['category'], $taxonomy );
} else {
$cat = get_term_by( 'slug', $atts['category'], $taxonomy );
}
if ( $cat && ! is_wp_error( $cat ) ) {
return $cat->count;
}
return '';
}
```
Which works great if I define the product category in the shortcode... My issue is it's in the header, so all category pages say the same item count... Is there a way to get it to display based on url? | your ajax post callable function action "**get\_news\_callback**" not working in your Class \_\_construct() becuase You Can use simple Wordpress action in the class.
Use Action In The Class :
>
> add\_action('wp\_ajax\_get\_news\_callback', array($this,
> 'get\_news\_callback'));
> add\_action('wp\_ajax\_nopriv\_get\_news\_callback', array($this, 'get\_news\_callback'));
>
>
>
your Script also change So you Can Use below script to get your ajax response .
```
defined('ABSPATH') or die('Ah ah ah. You didn\'t say the magic word.');
class News_search {
// Load scripts upon class initiation
public function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_get_news_callback', array($this, 'get_news_callback'));
add_action('wp_ajax_nopriv_get_news_callback', array($this, 'get_news_callback'));
add_shortcode('wp_news_search', array($this, 'wp_news_search_form'));
}
function enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));
// Enqueue and localize JS
wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);
wp_localize_script('ajax-script', 'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('my-string-shh'),
));
}
// Handle AJAX request
public function get_news_callback() {
check_ajax_referer('my-string-shh', 'security');
$keyword = isset($_POST['form_data']) ? $_POST['form_data'] : null;
echo $keyword;
die();
}
public function wp_news_search_form() {
$content .= '<form id="wp-news-search__form">
<label>
<input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>
</label>
<button id="wp-news-search__submit">' .
__('Search for news', 'wp-news-search') .
'</button>
</form>';
return $content;
}
}
new News_search();
```
Your Js
```
(function ($) {
$(document).ready(function () {
$('#wp-news-search__form').submit(function (event) {
event.preventDefault();
// const keyword = $('#query-input').val();
const values = $(this).serialize();
if (values) {
// send stuff to php
console.log(values);
const data = {
action: 'get_news_callback',
status: 'enabled',
type: "POST",
security: ajax_object.security,
form_data: values
}
$.post(ajax_object.ajax_url, data, function(response) {
if (response) {
console.log(`Response is: ${response}`);
}
})
.fail(() => { console.error('error'); })
.always(() => { console.log('form submitted') });
}
});
});
})(jQuery);
``` |
380,708 | <p>I try to update data through ajax, but it not worked. What I did wrong?
Here is jquery ajax code</p>
<p>php code in functions.php</p>
<pre><code>function update_records(){
global $wpdb;
echo $id = $_POST['update_record'];
$db_updated = $wpdb->update( $wpdb->prefix.'contact_form',
array('names' => $_POST['update_name'],
'emails' => $_POST['update_email'],
'gender' => $_POST['update_gender'],
'age' => $_POST['update_age']), array( 'ID' => $id ) );
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );
</code></pre>
<p>jquery ajax code</p>
<pre><code>jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var name = jQuery(this).attr('data-name');
var email = jQuery(this).attr('data-email');
var gender = jQuery(this).attr('data-gender');
var age = jQuery(this).attr('data-age');
alert(age);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'display_func',
update_record:id,
// update_name:name,
// update_email:email,
// update_gender:gender,
// update_age:age,
},
success: function( data ){
// alert("Records are successfully update");
location.reload();
}
});
});
</code></pre>
<p>ajax error screenshot - <a href="https://prnt.sc/wdon1x" rel="nofollow noreferrer">https://prnt.sc/wdon1x</a></p>
| [
{
"answer_id": 380714,
"author": "Had1z",
"author_id": 180121,
"author_profile": "https://wordpress.stackexchange.com/users/180121",
"pm_score": 3,
"selected": true,
"text": "<p>First of all, in your jquery event handler the <code>action</code> parameter's value should be the string after <code>wp_ajax_</code> and <code>wp_ajax_nopriv_</code>. So in your example the <code>action</code> should be <code>update_records</code>. So <code>display_func</code> is wrong.<br />\nThen in line 3 of your php code here the <code>echo</code> keyword should be removed.<br />\nSo your php code should be like this:</p>\n<pre><code>function update_records(){\n global $wpdb;\n $id = $_POST['update_record'];\n\n $db_updated = $wpdb->update( $wpdb->prefix.'contact_form', \n array(\n 'names' => $_POST['update_name'],\n 'emails' => $_POST['update_email'],\n 'gender' => $_POST['update_gender'],\n 'age' => $_POST['update_age']\n ), \n array( 'ID' => $id ) \n );\n} \nadd_action( "wp_ajax_update_records", "update_records" );\nadd_action( "wp_ajax_nopriv_update_records", "update_records" );\n</code></pre>\n"
},
{
"answer_id": 380739,
"author": "Baikare Sandeep",
"author_id": 99404,
"author_profile": "https://wordpress.stackexchange.com/users/99404",
"pm_score": 0,
"selected": false,
"text": "<p>Please sanitize the data before inserting or updating into the database to prevent from attackers <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">Read Documenation</a>:</p>\n<pre>\n<code>\nfunction update_records(){\n global $wpdb;\n $id = intval(sanitize_text_field($_POST['update_record']));\n\n $db_updated = $wpdb->update( $wpdb->prefix.'contact_form', \n array(\n 'names' => sanitize_text_field($_POST['update_name']),\n 'emails' => sanitize_email($_POST['update_email']),\n 'gender' => sanitize_text_field($_POST['update_gender']),\n 'age' => intval(sanitize_text_field($_POST['update_age']))\n ), \n array( 'ID' => $id ) \n );\n} \nadd_action( \"wp_ajax_update_records\", \"update_records\" );\nadd_action( \"wp_ajax_nopriv_update_records\", \"update_records\" );\n</code></pre>\n"
}
] | 2020/12/31 | [
"https://wordpress.stackexchange.com/questions/380708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/196459/"
] | I try to update data through ajax, but it not worked. What I did wrong?
Here is jquery ajax code
php code in functions.php
```
function update_records(){
global $wpdb;
echo $id = $_POST['update_record'];
$db_updated = $wpdb->update( $wpdb->prefix.'contact_form',
array('names' => $_POST['update_name'],
'emails' => $_POST['update_email'],
'gender' => $_POST['update_gender'],
'age' => $_POST['update_age']), array( 'ID' => $id ) );
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );
```
jquery ajax code
```
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var name = jQuery(this).attr('data-name');
var email = jQuery(this).attr('data-email');
var gender = jQuery(this).attr('data-gender');
var age = jQuery(this).attr('data-age');
alert(age);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'display_func',
update_record:id,
// update_name:name,
// update_email:email,
// update_gender:gender,
// update_age:age,
},
success: function( data ){
// alert("Records are successfully update");
location.reload();
}
});
});
```
ajax error screenshot - <https://prnt.sc/wdon1x> | First of all, in your jquery event handler the `action` parameter's value should be the string after `wp_ajax_` and `wp_ajax_nopriv_`. So in your example the `action` should be `update_records`. So `display_func` is wrong.
Then in line 3 of your php code here the `echo` keyword should be removed.
So your php code should be like this:
```
function update_records(){
global $wpdb;
$id = $_POST['update_record'];
$db_updated = $wpdb->update( $wpdb->prefix.'contact_form',
array(
'names' => $_POST['update_name'],
'emails' => $_POST['update_email'],
'gender' => $_POST['update_gender'],
'age' => $_POST['update_age']
),
array( 'ID' => $id )
);
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );
``` |
380,725 | <p>I am trying to add the current custom post type term to the body class of my WordPress admin page. So when I am viewing an existing custom post type that has been assigned a term it will add that term to the body class.</p>
<p>I have found the following code but cannot get it to work for me:</p>
<pre><code>add_filter( 'admin_body_class', 'rw_admin_body_class' );
function rw_admin_body_class( $classes )
{
if ( 'post' != $screen->base )
return $classes;
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );
$terms = wp_list_pluck( $terms, 'slug' );
foreach ( $terms as $term )
{
$classes .= ' my_taxonomy-' . $term;
}
return $classes;
}
</code></pre>
<p>Any pointers on how to get this working?</p>
| [
{
"answer_id": 380730,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 3,
"selected": true,
"text": "<p>I think you're missing <a href=\"https://developer.wordpress.org/reference/classes/wp_screen/\" rel=\"nofollow noreferrer\"><code>get_current_screen()</code></a>.</p>\n<pre><code>add_filter( 'admin_body_class', 'rw_admin_body_class' );\nfunction rw_admin_body_class( $classes ) {\n $screen = get_current_screen();\n if ( 'post' != $screen->base ) {\n return $classes;\n }\n\n global $post;\n $terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );\n $terms = wp_list_pluck( $terms, 'slug' );\n foreach ( $terms as $term )\n {\n $classes .= ' my_taxonomy-' . $term;\n }\n\n return $classes;\n}\n</code></pre>\n"
},
{
"answer_id": 380733,
"author": "Ejaz UL Haq",
"author_id": 178714,
"author_profile": "https://wordpress.stackexchange.com/users/178714",
"pm_score": 0,
"selected": false,
"text": "<p>You can add custom-classe to the your wordpress custom admin page body classes like the following</p>\n<pre><code>$wpdocs_admin_page = add_options_page(__('Wpdocs Admin Page', 'wpdocs_textdomain'),\n __('Wpdocs Admin Page', 'wpdocs_textdomain'),\n 'manage_options', 'wpdocs_textdomain', 'wpdocs_admin_page');\n\nadd_filter( 'admin_body_class', 'rw_admin_body_class' );\nfunction rw_admin_body_class( $classes )\n{\n$screen = get_current_screen();\n if ( wpdocs_admin_page == $screen->id)\n return $classes;\n\n global $post;\n $terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );\n $terms = wp_list_pluck( $terms, 'slug' );\n foreach ( $terms as $term )\n {\n $classes .= ' my_taxonomy-' . $term;\n }\n\n return $classes;\n}\n</code></pre>\n"
}
] | 2020/12/31 | [
"https://wordpress.stackexchange.com/questions/380725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68283/"
] | I am trying to add the current custom post type term to the body class of my WordPress admin page. So when I am viewing an existing custom post type that has been assigned a term it will add that term to the body class.
I have found the following code but cannot get it to work for me:
```
add_filter( 'admin_body_class', 'rw_admin_body_class' );
function rw_admin_body_class( $classes )
{
if ( 'post' != $screen->base )
return $classes;
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );
$terms = wp_list_pluck( $terms, 'slug' );
foreach ( $terms as $term )
{
$classes .= ' my_taxonomy-' . $term;
}
return $classes;
}
```
Any pointers on how to get this working? | I think you're missing [`get_current_screen()`](https://developer.wordpress.org/reference/classes/wp_screen/).
```
add_filter( 'admin_body_class', 'rw_admin_body_class' );
function rw_admin_body_class( $classes ) {
$screen = get_current_screen();
if ( 'post' != $screen->base ) {
return $classes;
}
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );
$terms = wp_list_pluck( $terms, 'slug' );
foreach ( $terms as $term )
{
$classes .= ' my_taxonomy-' . $term;
}
return $classes;
}
``` |
380,749 | <p><a href="https://i.stack.imgur.com/uJJJQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uJJJQ.png" alt="enter image description here" /></a>I have added an image through advanced custom field. I want to retrieve image URL. I have tried with following code. It is returning null.</p>
<pre><code> $url = get_field('aboutus_img','aboutus');
</code></pre>
<p>aboutus_img = field name
aboutus = field group name</p>
| [
{
"answer_id": 380750,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Refer ACF link : <a href=\"https://www.advancedcustomfields.com/resources/image/\" rel=\"nofollow noreferrer\">Link</a></p>\n<p>And use</p>\n<pre><code><?php echo get_field('aboutus_img'); ?>\n</code></pre>\n<p>Choose option image url</p>\n<p><a href=\"https://i.stack.imgur.com/hXPyB.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hXPyB.jpg\" alt=\"enter image description here\" /></a></p>\n<p>This example demonstrates how to display the selected image when using the Image URL return type. This return type allows us to efficiently display a basic image but prevents us from loading any extra data about the image.</p>\n<pre><code><?php if( get_field('image') ): ?>\n <img src="<?php the_field('image_field_name'); ?>" />\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 380751,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>ACF provides good <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">documentation</a> about this function, which shows that it has the following signature:</p>\n<pre><code>get_field($selector, [$post_id], [$format_value]);\n</code></pre>\n<ul>\n<li>$selector (string) (Required) The field name or field key.</li>\n<li>$post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post.</li>\n<li>$format_value (bool) (Optional) Whether to apply formatting logic. Defaults to true.</li>\n</ul>\n<p>You probably need to get the post ID, if you are working outside of a loop - like:</p>\n<pre><code>$url = get_field('aboutus_img', get_post_ID() );\n</code></pre>\n"
}
] | 2021/01/01 | [
"https://wordpress.stackexchange.com/questions/380749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199720/"
] | [](https://i.stack.imgur.com/uJJJQ.png)I have added an image through advanced custom field. I want to retrieve image URL. I have tried with following code. It is returning null.
```
$url = get_field('aboutus_img','aboutus');
```
aboutus\_img = field name
aboutus = field group name | Refer ACF link : [Link](https://www.advancedcustomfields.com/resources/image/)
And use
```
<?php echo get_field('aboutus_img'); ?>
```
Choose option image url
[](https://i.stack.imgur.com/hXPyB.jpg)
This example demonstrates how to display the selected image when using the Image URL return type. This return type allows us to efficiently display a basic image but prevents us from loading any extra data about the image.
```
<?php if( get_field('image') ): ?>
<img src="<?php the_field('image_field_name'); ?>" />
<?php endif; ?>
``` |
380,757 | <p>I'm trying to send an email using <code>wp_mail()</code> through a <code>REST</code> custom route, but it's failing somewhere.</p>
<p>EDIT: I found out where, in "sendContactMail()", <code>$request->get_json_params();</code> returns nothing, although <code>$request</code> contains all my form information. What's the right way to extract this information then?</p>
<pre><code>// custom route callback function
function sendContactMail(WP_REST_Request $request) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
$parameters = $request->get_json_params();
if (count($_POST) > 0) {
$parameters = $_POST;
}
$siteName = wp_strip_all_tags(trim(get_option('blogname')));
$contactName = wp_strip_all_tags(trim($parameters['contact_name']));
$contactEmail = wp_strip_all_tags(trim($parameters['contact_email']));
$contactMessage = wp_strip_all_tags(trim($parameters['contact_message']));
if (!empty($contactName) && !empty($contactEmail) && !empty($contactMessage)) {
$subject = "(New message sent from site $siteName) $contactName <$contactEmail>";
$body = "<h3>$subject</h3><br/>";
$body .= "<p><b>Name:</b> $contactName</p>";
$body .= "<p><b>Email:</b> $contactEmail</p>";
$body .= "<p><b>Message:</b> $contactMessage</p>";
if (send_email($contactEmail, $contactName, $body)) {
$response['status'] = 200;
$response['message'] = 'Form sent successfully.';
}
}
return new WP_REST_Response($response);
}
// custom route declaration
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', array(
'methods' => ['POST','PUT'],
'callback' => 'sendContactMail'
));
});
</code></pre>
<p>Form-related content of <code>$request</code>:</p>
<pre><code>["body":protected]=> string(382) "------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_name" Jack ------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_email" [email protected] ------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_message" This is my message. ------WebKitFormBoundaryoh45oL7PWjTynEQK-- "
</code></pre>
| [
{
"answer_id": 380783,
"author": "Zoltan Febert",
"author_id": 110887,
"author_profile": "https://wordpress.stackexchange.com/users/110887",
"pm_score": 0,
"selected": false,
"text": "<p>I tried to simulate what you did in my test environment.</p>\n<p>When I made the AJAX call like this, it worked.</p>\n<pre><code>$.ajax({\n type: "PUT", //HTTP VERB\n url: "${this.baseUrl}/wp-json/contact/v1/send", //URL\n dataType: 'json', //What type of response you expect back from the server\n contentType: 'text/plain', //What type of data you are trying to send\n data: fromData,\n success: function (response, request) {\n alert(response)\n this.success = true\n this.ApiResponse = respone\n },\n error: function (response, request) {\n alert(response)\n this.success = false\n this.ApiResponse = respone\n }\n\n})\n</code></pre>\n<p>My callback function was very simple:</p>\n<pre><code>function sendContactMail(WP_REST_Request $request) {\n return 'OK';\n}\n</code></pre>\n<p>Once you get the response in Javascript, you can start debug the callback function.</p>\n"
},
{
"answer_id": 381627,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>You didn't include the code for your <code>send_email()</code> function, but I looked at the original <a href=\"https://wordpress.stackexchange.com/revisions/380757/1\">source</a> (revision 1) of your question, and it seems to me that your <code>send_email()</code> function is good, but if this answer doesn't help solve the issue, then add the function code into your question body.</em></p>\n<p>So I don't know why are you setting your (REST) API endpoint's (HTTP) methods to POST <em>and PUT</em>, i.e. <code>'methods' => ['POST','PUT']</code>, because I think POST is enough (i.e. <code>'methods' => 'POST'</code>), but it seems to me that you are not properly sending your form data to the API endpoint.</p>\n<p>And note that, when you use <code>FormData</code> (in JavaScript) with the PUT method, both <code>$request->get_json_params()</code> and the superglobal <code>$_POST</code> are empty, so if you must use the PUT method, then you would want to send your form data as a JSON-encoded string.</p>\n<p>Secondly, regardless the (HTTP) method you use, <em>if you send the data as JSON, then make sure the <code>Content-Type</code> header is set with <code>application/json</code> being the value</em>.</p>\n<p>So here are two examples using JavaScript, one for each HTTP method, and these examples worked fine for me on WordPress 5.6.0:</p>\n<h2>Using <code>fetch()</code>, <code>FormData</code> and the POST method</h2>\n<pre class=\"lang-js prettyprint-override\"><code>const formData = new FormData();\n\nformData.append( 'contact_name', 'John Doe' );\nformData.append( 'contact_email', '[email protected]' );\nformData.append( 'contact_message', 'Just testing' );\n\nfetch( 'https://example.com/wp-json/contact/v1/send', {\n method: 'POST',\n body: formData\n} )\n .then( res => res.json() )\n .then( data => console.log( data ) )\n .catch( error => console.log( error ) );\n</code></pre>\n<h2>Using <code>fetch()</code>, <code>JSON.stringify()</code> and the PUT method</h2>\n<pre class=\"lang-js prettyprint-override\"><code>const formData = {\n contact_name: 'John Doe',\n contact_email: '[email protected]',\n contact_message: 'Just testing'\n};\n\nfetch( 'https://example.com/wp-json/contact/v1/send', {\n method: 'PUT',\n body: JSON.stringify( formData ),\n headers: {\n 'Content-Type': 'application/json'\n }\n} )\n .then( res => res.json() )\n .then( data => console.log( data ) )\n .catch( error => console.log( error ) );\n</code></pre>\n<p>So I hope that helps, and you don't have to use <code>fetch()</code> or even JavaScript, but the point in my answer is, make sure your request uses the <strong>proper body/content and content type header</strong>.</p>\n<h1>UPDATE</h1>\n<h2>How to access the request parameters</h2>\n<p>Please check the <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments\" rel=\"nofollow noreferrer\">Extending the REST API → Adding Custom Endpoints → Arguments</a> section in the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">REST API handbook</a> for more details, but here are two of the most common ways in accessing the parameters:</p>\n<ul>\n<li><p>Use <code>$request->get_params()</code> to get all the parameters (URL-encoded POST body, JSON payload, URL query string, etc.). So in your case:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Instead of this:\n$parameters = $request->get_json_params();\nif (count($_POST) > 0) {\n $parameters = $_POST;\n}\n\n// You could simply do:\n$parameters = $request->get_params();\n</code></pre>\n</li>\n<li><p>Use direct array access on the object passed as the first parameter to your endpoint callback, i.e. the <code>$request</code> variable above. E.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$contactName = $request['contact_name'];\n$contactEmail = $request['contact_email'];\n$contactMessage = $request['contact_message'];\n</code></pre>\n</li>\n</ul>\n<p>And in your case, you should probably just use the second option above.</p>\n<h2>Have you tested your <code>send_email()</code> function via direct function calls (i.e. not through the REST API)?</h2>\n<p>Although I don't know what's the code in your <code>send_email()</code> function, you should test the function by passing test data and see if the function actually works, e.g. does it return true, false, null, is there any errors/notices, etc. And if it's the function that doesn't work, then the problem is not with the REST API, i.e. even on normal requests like the homepage, that function would not work.</p>\n<p>So test your <em>email sending function</em>, confirm that it receives all the necessary parameters and that it actually properly sends the email (e.g. use the correct headers like "From" and "Content-Type").</p>\n<h2>Always set <code>permission_callback</code>, and utilize <code>validate_callback</code> and <code>sanitize_callback</code> for validating/sanitizing the request parameters</h2>\n<p>So basically, except for the <code>send_email()</code> function, your code does work in that the endpoint gets registered and it returns a good response. But here are some things that you should bear in mind when adding custom endpoints:</p>\n<ol>\n<li><p>Make sure to always set a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\"><code>permission_callback</code></a> for your endpoint, because if you don't set it, then the following would happen (but by default, only if <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">debugging</a> is enabled on your site):</p>\n<blockquote>\n<p>As of WordPress\n5.5, if a <code>permission_callback</code> is not provided, the REST API will issue a <code>_doing_it_wrong</code> notice.</p>\n</blockquote>\n<p>Sample notice that would be issued:</p>\n<blockquote>\n<p>The REST API route definition for <code>contact/v1/send</code> is missing the\nrequired <code>permission_callback</code> argument. For REST API routes that are\nintended to be public, use <code>__return_true</code> as the permission callback.</p>\n</blockquote>\n</li>\n<li><p>The third parameter for <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\"><code>register_rest_route()</code></a> accepts an argument named <code>args</code> which is an array of parameters for your endpoint, and for each parameter, you can set a validation callback (<code>validate_callback</code>) and a sanitization callback (<code>sanitize_callback</code>), so you should use that instead of doing the validation/sanitization in your endpoint's main callback. And here's one of the good reasons why would you want to use those callbacks:</p>\n<blockquote>\n<p>Using <code>sanitize_callback</code> and <code>validate_callback</code> allows the main\ncallback to act only to process the request, and prepare data to be\nreturned using the <code>WP_REST_Response</code> class. By using these two\ncallbacks, you will be able to <em>safely assume your inputs are valid\nand safe when processing</em>.</p>\n</blockquote>\n<p>That was a (slightly reformatted) excerpt taken from the API handbook, BTW.</p>\n</li>\n</ol>\n<h2>Try my code</h2>\n<p><strong>Note:</strong> I originally tested your code with a <em>dummy</em> <code>send_email()</code> function, but here, I'm using <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\"><code>wp_mail()</code></a> directly in the main callback.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// The code is basically based on yours.\n\nfunction sendContactMail( WP_REST_Request $request ) {\n $response = array(\n 'status' => 304,\n 'message' => 'There was an error sending the form.'\n );\n\n $siteName = wp_strip_all_tags( trim( get_option( 'blogname' ) ) );\n $contactName = $request['contact_name'];\n $contactEmail = $request['contact_email'];\n $contactMessage = $request['contact_message'];\n\n $subject = "[$siteName] (testing) New message from $contactName";\n// $body = "<h3>$subject</h3><br/>";\n $body = "<p><b>Name:</b> $contactName</p>";\n $body .= "<p><b>Email:</b> $contactEmail</p>";\n $body .= "<p><b>Message:</b> $contactMessage</p>";\n\n $to = get_option( 'admin_email' );\n $headers = array(\n 'Content-Type: text/html; charset=UTF-8',\n "Reply-To: $contactName <$contactEmail>",\n );\n\n if ( wp_mail( $to, $subject, $body, $headers ) ) {\n $response['status'] = 200;\n $response['message'] = 'Form sent successfully.';\n $response['test'] = $body;\n }\n\n return new WP_REST_Response( $response );\n}\n\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'contact/v1', 'send', array(\n 'methods' => 'POST',\n 'callback' => 'sendContactMail',\n 'permission_callback' => '__return_true',\n 'args' => array(\n 'contact_name' => array(\n 'required' => true,\n 'validate_callback' => function ( $value ) {\n return preg_match( '/[a-z0-9]{2,}/i', $value ) ? true :\n new WP_Error( 'invalid_contact_name', 'Your custom error.' );\n },\n 'sanitize_callback' => 'sanitize_text_field',\n ),\n 'contact_email' => array(\n 'required' => true,\n 'validate_callback' => 'is_email',\n 'sanitize_callback' => 'sanitize_email',\n ),\n 'contact_message' => array(\n 'required' => true,\n 'sanitize_callback' => 'sanitize_textarea_field',\n ),\n ),\n ) );\n} );\n</code></pre>\n"
}
] | 2021/01/01 | [
"https://wordpress.stackexchange.com/questions/380757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11634/"
] | I'm trying to send an email using `wp_mail()` through a `REST` custom route, but it's failing somewhere.
EDIT: I found out where, in "sendContactMail()", `$request->get_json_params();` returns nothing, although `$request` contains all my form information. What's the right way to extract this information then?
```
// custom route callback function
function sendContactMail(WP_REST_Request $request) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
$parameters = $request->get_json_params();
if (count($_POST) > 0) {
$parameters = $_POST;
}
$siteName = wp_strip_all_tags(trim(get_option('blogname')));
$contactName = wp_strip_all_tags(trim($parameters['contact_name']));
$contactEmail = wp_strip_all_tags(trim($parameters['contact_email']));
$contactMessage = wp_strip_all_tags(trim($parameters['contact_message']));
if (!empty($contactName) && !empty($contactEmail) && !empty($contactMessage)) {
$subject = "(New message sent from site $siteName) $contactName <$contactEmail>";
$body = "<h3>$subject</h3><br/>";
$body .= "<p><b>Name:</b> $contactName</p>";
$body .= "<p><b>Email:</b> $contactEmail</p>";
$body .= "<p><b>Message:</b> $contactMessage</p>";
if (send_email($contactEmail, $contactName, $body)) {
$response['status'] = 200;
$response['message'] = 'Form sent successfully.';
}
}
return new WP_REST_Response($response);
}
// custom route declaration
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', array(
'methods' => ['POST','PUT'],
'callback' => 'sendContactMail'
));
});
```
Form-related content of `$request`:
```
["body":protected]=> string(382) "------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_name" Jack ------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_email" [email protected] ------WebKitFormBoundaryoh45oL7PWjTynEQK Content-Disposition: form-data; name="contact_message" This is my message. ------WebKitFormBoundaryoh45oL7PWjTynEQK-- "
``` | *You didn't include the code for your `send_email()` function, but I looked at the original [source](https://wordpress.stackexchange.com/revisions/380757/1) (revision 1) of your question, and it seems to me that your `send_email()` function is good, but if this answer doesn't help solve the issue, then add the function code into your question body.*
So I don't know why are you setting your (REST) API endpoint's (HTTP) methods to POST *and PUT*, i.e. `'methods' => ['POST','PUT']`, because I think POST is enough (i.e. `'methods' => 'POST'`), but it seems to me that you are not properly sending your form data to the API endpoint.
And note that, when you use `FormData` (in JavaScript) with the PUT method, both `$request->get_json_params()` and the superglobal `$_POST` are empty, so if you must use the PUT method, then you would want to send your form data as a JSON-encoded string.
Secondly, regardless the (HTTP) method you use, *if you send the data as JSON, then make sure the `Content-Type` header is set with `application/json` being the value*.
So here are two examples using JavaScript, one for each HTTP method, and these examples worked fine for me on WordPress 5.6.0:
Using `fetch()`, `FormData` and the POST method
-----------------------------------------------
```js
const formData = new FormData();
formData.append( 'contact_name', 'John Doe' );
formData.append( 'contact_email', '[email protected]' );
formData.append( 'contact_message', 'Just testing' );
fetch( 'https://example.com/wp-json/contact/v1/send', {
method: 'POST',
body: formData
} )
.then( res => res.json() )
.then( data => console.log( data ) )
.catch( error => console.log( error ) );
```
Using `fetch()`, `JSON.stringify()` and the PUT method
------------------------------------------------------
```js
const formData = {
contact_name: 'John Doe',
contact_email: '[email protected]',
contact_message: 'Just testing'
};
fetch( 'https://example.com/wp-json/contact/v1/send', {
method: 'PUT',
body: JSON.stringify( formData ),
headers: {
'Content-Type': 'application/json'
}
} )
.then( res => res.json() )
.then( data => console.log( data ) )
.catch( error => console.log( error ) );
```
So I hope that helps, and you don't have to use `fetch()` or even JavaScript, but the point in my answer is, make sure your request uses the **proper body/content and content type header**.
UPDATE
======
How to access the request parameters
------------------------------------
Please check the [Extending the REST API → Adding Custom Endpoints → Arguments](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments) section in the [REST API handbook](https://developer.wordpress.org/rest-api/) for more details, but here are two of the most common ways in accessing the parameters:
* Use `$request->get_params()` to get all the parameters (URL-encoded POST body, JSON payload, URL query string, etc.). So in your case:
```php
// Instead of this:
$parameters = $request->get_json_params();
if (count($_POST) > 0) {
$parameters = $_POST;
}
// You could simply do:
$parameters = $request->get_params();
```
* Use direct array access on the object passed as the first parameter to your endpoint callback, i.e. the `$request` variable above. E.g.
```php
$contactName = $request['contact_name'];
$contactEmail = $request['contact_email'];
$contactMessage = $request['contact_message'];
```
And in your case, you should probably just use the second option above.
Have you tested your `send_email()` function via direct function calls (i.e. not through the REST API)?
-------------------------------------------------------------------------------------------------------
Although I don't know what's the code in your `send_email()` function, you should test the function by passing test data and see if the function actually works, e.g. does it return true, false, null, is there any errors/notices, etc. And if it's the function that doesn't work, then the problem is not with the REST API, i.e. even on normal requests like the homepage, that function would not work.
So test your *email sending function*, confirm that it receives all the necessary parameters and that it actually properly sends the email (e.g. use the correct headers like "From" and "Content-Type").
Always set `permission_callback`, and utilize `validate_callback` and `sanitize_callback` for validating/sanitizing the request parameters
------------------------------------------------------------------------------------------------------------------------------------------
So basically, except for the `send_email()` function, your code does work in that the endpoint gets registered and it returns a good response. But here are some things that you should bear in mind when adding custom endpoints:
1. Make sure to always set a [`permission_callback`](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback) for your endpoint, because if you don't set it, then the following would happen (but by default, only if [debugging](https://wordpress.org/support/article/debugging-in-wordpress/) is enabled on your site):
>
> As of WordPress
> 5.5, if a `permission_callback` is not provided, the REST API will issue a `_doing_it_wrong` notice.
>
>
>
Sample notice that would be issued:
>
> The REST API route definition for `contact/v1/send` is missing the
> required `permission_callback` argument. For REST API routes that are
> intended to be public, use `__return_true` as the permission callback.
>
>
>
2. The third parameter for [`register_rest_route()`](https://developer.wordpress.org/reference/functions/register_rest_route/) accepts an argument named `args` which is an array of parameters for your endpoint, and for each parameter, you can set a validation callback (`validate_callback`) and a sanitization callback (`sanitize_callback`), so you should use that instead of doing the validation/sanitization in your endpoint's main callback. And here's one of the good reasons why would you want to use those callbacks:
>
> Using `sanitize_callback` and `validate_callback` allows the main
> callback to act only to process the request, and prepare data to be
> returned using the `WP_REST_Response` class. By using these two
> callbacks, you will be able to *safely assume your inputs are valid
> and safe when processing*.
>
>
>
That was a (slightly reformatted) excerpt taken from the API handbook, BTW.
Try my code
-----------
**Note:** I originally tested your code with a *dummy* `send_email()` function, but here, I'm using [`wp_mail()`](https://developer.wordpress.org/reference/functions/wp_mail/) directly in the main callback.
```php
// The code is basically based on yours.
function sendContactMail( WP_REST_Request $request ) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
$siteName = wp_strip_all_tags( trim( get_option( 'blogname' ) ) );
$contactName = $request['contact_name'];
$contactEmail = $request['contact_email'];
$contactMessage = $request['contact_message'];
$subject = "[$siteName] (testing) New message from $contactName";
// $body = "<h3>$subject</h3><br/>";
$body = "<p><b>Name:</b> $contactName</p>";
$body .= "<p><b>Email:</b> $contactEmail</p>";
$body .= "<p><b>Message:</b> $contactMessage</p>";
$to = get_option( 'admin_email' );
$headers = array(
'Content-Type: text/html; charset=UTF-8',
"Reply-To: $contactName <$contactEmail>",
);
if ( wp_mail( $to, $subject, $body, $headers ) ) {
$response['status'] = 200;
$response['message'] = 'Form sent successfully.';
$response['test'] = $body;
}
return new WP_REST_Response( $response );
}
add_action( 'rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', array(
'methods' => 'POST',
'callback' => 'sendContactMail',
'permission_callback' => '__return_true',
'args' => array(
'contact_name' => array(
'required' => true,
'validate_callback' => function ( $value ) {
return preg_match( '/[a-z0-9]{2,}/i', $value ) ? true :
new WP_Error( 'invalid_contact_name', 'Your custom error.' );
},
'sanitize_callback' => 'sanitize_text_field',
),
'contact_email' => array(
'required' => true,
'validate_callback' => 'is_email',
'sanitize_callback' => 'sanitize_email',
),
'contact_message' => array(
'required' => true,
'sanitize_callback' => 'sanitize_textarea_field',
),
),
) );
} );
``` |
380,760 | <p>How can I make my page url to be like this in wordpress?</p>
<p>Normal link: <a href="http://www.google.com/about" rel="nofollow noreferrer">www.google.com/about</a></p>
<p>What I want: <a href="http://www.google.com/any-slug/about" rel="nofollow noreferrer">www.google.com/any-slug/about</a></p>
<p>How can I do that?</p>
| [
{
"answer_id": 380783,
"author": "Zoltan Febert",
"author_id": 110887,
"author_profile": "https://wordpress.stackexchange.com/users/110887",
"pm_score": 0,
"selected": false,
"text": "<p>I tried to simulate what you did in my test environment.</p>\n<p>When I made the AJAX call like this, it worked.</p>\n<pre><code>$.ajax({\n type: "PUT", //HTTP VERB\n url: "${this.baseUrl}/wp-json/contact/v1/send", //URL\n dataType: 'json', //What type of response you expect back from the server\n contentType: 'text/plain', //What type of data you are trying to send\n data: fromData,\n success: function (response, request) {\n alert(response)\n this.success = true\n this.ApiResponse = respone\n },\n error: function (response, request) {\n alert(response)\n this.success = false\n this.ApiResponse = respone\n }\n\n})\n</code></pre>\n<p>My callback function was very simple:</p>\n<pre><code>function sendContactMail(WP_REST_Request $request) {\n return 'OK';\n}\n</code></pre>\n<p>Once you get the response in Javascript, you can start debug the callback function.</p>\n"
},
{
"answer_id": 381627,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>You didn't include the code for your <code>send_email()</code> function, but I looked at the original <a href=\"https://wordpress.stackexchange.com/revisions/380757/1\">source</a> (revision 1) of your question, and it seems to me that your <code>send_email()</code> function is good, but if this answer doesn't help solve the issue, then add the function code into your question body.</em></p>\n<p>So I don't know why are you setting your (REST) API endpoint's (HTTP) methods to POST <em>and PUT</em>, i.e. <code>'methods' => ['POST','PUT']</code>, because I think POST is enough (i.e. <code>'methods' => 'POST'</code>), but it seems to me that you are not properly sending your form data to the API endpoint.</p>\n<p>And note that, when you use <code>FormData</code> (in JavaScript) with the PUT method, both <code>$request->get_json_params()</code> and the superglobal <code>$_POST</code> are empty, so if you must use the PUT method, then you would want to send your form data as a JSON-encoded string.</p>\n<p>Secondly, regardless the (HTTP) method you use, <em>if you send the data as JSON, then make sure the <code>Content-Type</code> header is set with <code>application/json</code> being the value</em>.</p>\n<p>So here are two examples using JavaScript, one for each HTTP method, and these examples worked fine for me on WordPress 5.6.0:</p>\n<h2>Using <code>fetch()</code>, <code>FormData</code> and the POST method</h2>\n<pre class=\"lang-js prettyprint-override\"><code>const formData = new FormData();\n\nformData.append( 'contact_name', 'John Doe' );\nformData.append( 'contact_email', '[email protected]' );\nformData.append( 'contact_message', 'Just testing' );\n\nfetch( 'https://example.com/wp-json/contact/v1/send', {\n method: 'POST',\n body: formData\n} )\n .then( res => res.json() )\n .then( data => console.log( data ) )\n .catch( error => console.log( error ) );\n</code></pre>\n<h2>Using <code>fetch()</code>, <code>JSON.stringify()</code> and the PUT method</h2>\n<pre class=\"lang-js prettyprint-override\"><code>const formData = {\n contact_name: 'John Doe',\n contact_email: '[email protected]',\n contact_message: 'Just testing'\n};\n\nfetch( 'https://example.com/wp-json/contact/v1/send', {\n method: 'PUT',\n body: JSON.stringify( formData ),\n headers: {\n 'Content-Type': 'application/json'\n }\n} )\n .then( res => res.json() )\n .then( data => console.log( data ) )\n .catch( error => console.log( error ) );\n</code></pre>\n<p>So I hope that helps, and you don't have to use <code>fetch()</code> or even JavaScript, but the point in my answer is, make sure your request uses the <strong>proper body/content and content type header</strong>.</p>\n<h1>UPDATE</h1>\n<h2>How to access the request parameters</h2>\n<p>Please check the <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments\" rel=\"nofollow noreferrer\">Extending the REST API → Adding Custom Endpoints → Arguments</a> section in the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">REST API handbook</a> for more details, but here are two of the most common ways in accessing the parameters:</p>\n<ul>\n<li><p>Use <code>$request->get_params()</code> to get all the parameters (URL-encoded POST body, JSON payload, URL query string, etc.). So in your case:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Instead of this:\n$parameters = $request->get_json_params();\nif (count($_POST) > 0) {\n $parameters = $_POST;\n}\n\n// You could simply do:\n$parameters = $request->get_params();\n</code></pre>\n</li>\n<li><p>Use direct array access on the object passed as the first parameter to your endpoint callback, i.e. the <code>$request</code> variable above. E.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$contactName = $request['contact_name'];\n$contactEmail = $request['contact_email'];\n$contactMessage = $request['contact_message'];\n</code></pre>\n</li>\n</ul>\n<p>And in your case, you should probably just use the second option above.</p>\n<h2>Have you tested your <code>send_email()</code> function via direct function calls (i.e. not through the REST API)?</h2>\n<p>Although I don't know what's the code in your <code>send_email()</code> function, you should test the function by passing test data and see if the function actually works, e.g. does it return true, false, null, is there any errors/notices, etc. And if it's the function that doesn't work, then the problem is not with the REST API, i.e. even on normal requests like the homepage, that function would not work.</p>\n<p>So test your <em>email sending function</em>, confirm that it receives all the necessary parameters and that it actually properly sends the email (e.g. use the correct headers like "From" and "Content-Type").</p>\n<h2>Always set <code>permission_callback</code>, and utilize <code>validate_callback</code> and <code>sanitize_callback</code> for validating/sanitizing the request parameters</h2>\n<p>So basically, except for the <code>send_email()</code> function, your code does work in that the endpoint gets registered and it returns a good response. But here are some things that you should bear in mind when adding custom endpoints:</p>\n<ol>\n<li><p>Make sure to always set a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\"><code>permission_callback</code></a> for your endpoint, because if you don't set it, then the following would happen (but by default, only if <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">debugging</a> is enabled on your site):</p>\n<blockquote>\n<p>As of WordPress\n5.5, if a <code>permission_callback</code> is not provided, the REST API will issue a <code>_doing_it_wrong</code> notice.</p>\n</blockquote>\n<p>Sample notice that would be issued:</p>\n<blockquote>\n<p>The REST API route definition for <code>contact/v1/send</code> is missing the\nrequired <code>permission_callback</code> argument. For REST API routes that are\nintended to be public, use <code>__return_true</code> as the permission callback.</p>\n</blockquote>\n</li>\n<li><p>The third parameter for <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\"><code>register_rest_route()</code></a> accepts an argument named <code>args</code> which is an array of parameters for your endpoint, and for each parameter, you can set a validation callback (<code>validate_callback</code>) and a sanitization callback (<code>sanitize_callback</code>), so you should use that instead of doing the validation/sanitization in your endpoint's main callback. And here's one of the good reasons why would you want to use those callbacks:</p>\n<blockquote>\n<p>Using <code>sanitize_callback</code> and <code>validate_callback</code> allows the main\ncallback to act only to process the request, and prepare data to be\nreturned using the <code>WP_REST_Response</code> class. By using these two\ncallbacks, you will be able to <em>safely assume your inputs are valid\nand safe when processing</em>.</p>\n</blockquote>\n<p>That was a (slightly reformatted) excerpt taken from the API handbook, BTW.</p>\n</li>\n</ol>\n<h2>Try my code</h2>\n<p><strong>Note:</strong> I originally tested your code with a <em>dummy</em> <code>send_email()</code> function, but here, I'm using <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\"><code>wp_mail()</code></a> directly in the main callback.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// The code is basically based on yours.\n\nfunction sendContactMail( WP_REST_Request $request ) {\n $response = array(\n 'status' => 304,\n 'message' => 'There was an error sending the form.'\n );\n\n $siteName = wp_strip_all_tags( trim( get_option( 'blogname' ) ) );\n $contactName = $request['contact_name'];\n $contactEmail = $request['contact_email'];\n $contactMessage = $request['contact_message'];\n\n $subject = "[$siteName] (testing) New message from $contactName";\n// $body = "<h3>$subject</h3><br/>";\n $body = "<p><b>Name:</b> $contactName</p>";\n $body .= "<p><b>Email:</b> $contactEmail</p>";\n $body .= "<p><b>Message:</b> $contactMessage</p>";\n\n $to = get_option( 'admin_email' );\n $headers = array(\n 'Content-Type: text/html; charset=UTF-8',\n "Reply-To: $contactName <$contactEmail>",\n );\n\n if ( wp_mail( $to, $subject, $body, $headers ) ) {\n $response['status'] = 200;\n $response['message'] = 'Form sent successfully.';\n $response['test'] = $body;\n }\n\n return new WP_REST_Response( $response );\n}\n\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'contact/v1', 'send', array(\n 'methods' => 'POST',\n 'callback' => 'sendContactMail',\n 'permission_callback' => '__return_true',\n 'args' => array(\n 'contact_name' => array(\n 'required' => true,\n 'validate_callback' => function ( $value ) {\n return preg_match( '/[a-z0-9]{2,}/i', $value ) ? true :\n new WP_Error( 'invalid_contact_name', 'Your custom error.' );\n },\n 'sanitize_callback' => 'sanitize_text_field',\n ),\n 'contact_email' => array(\n 'required' => true,\n 'validate_callback' => 'is_email',\n 'sanitize_callback' => 'sanitize_email',\n ),\n 'contact_message' => array(\n 'required' => true,\n 'sanitize_callback' => 'sanitize_textarea_field',\n ),\n ),\n ) );\n} );\n</code></pre>\n"
}
] | 2021/01/01 | [
"https://wordpress.stackexchange.com/questions/380760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199728/"
] | How can I make my page url to be like this in wordpress?
Normal link: [www.google.com/about](http://www.google.com/about)
What I want: [www.google.com/any-slug/about](http://www.google.com/any-slug/about)
How can I do that? | *You didn't include the code for your `send_email()` function, but I looked at the original [source](https://wordpress.stackexchange.com/revisions/380757/1) (revision 1) of your question, and it seems to me that your `send_email()` function is good, but if this answer doesn't help solve the issue, then add the function code into your question body.*
So I don't know why are you setting your (REST) API endpoint's (HTTP) methods to POST *and PUT*, i.e. `'methods' => ['POST','PUT']`, because I think POST is enough (i.e. `'methods' => 'POST'`), but it seems to me that you are not properly sending your form data to the API endpoint.
And note that, when you use `FormData` (in JavaScript) with the PUT method, both `$request->get_json_params()` and the superglobal `$_POST` are empty, so if you must use the PUT method, then you would want to send your form data as a JSON-encoded string.
Secondly, regardless the (HTTP) method you use, *if you send the data as JSON, then make sure the `Content-Type` header is set with `application/json` being the value*.
So here are two examples using JavaScript, one for each HTTP method, and these examples worked fine for me on WordPress 5.6.0:
Using `fetch()`, `FormData` and the POST method
-----------------------------------------------
```js
const formData = new FormData();
formData.append( 'contact_name', 'John Doe' );
formData.append( 'contact_email', '[email protected]' );
formData.append( 'contact_message', 'Just testing' );
fetch( 'https://example.com/wp-json/contact/v1/send', {
method: 'POST',
body: formData
} )
.then( res => res.json() )
.then( data => console.log( data ) )
.catch( error => console.log( error ) );
```
Using `fetch()`, `JSON.stringify()` and the PUT method
------------------------------------------------------
```js
const formData = {
contact_name: 'John Doe',
contact_email: '[email protected]',
contact_message: 'Just testing'
};
fetch( 'https://example.com/wp-json/contact/v1/send', {
method: 'PUT',
body: JSON.stringify( formData ),
headers: {
'Content-Type': 'application/json'
}
} )
.then( res => res.json() )
.then( data => console.log( data ) )
.catch( error => console.log( error ) );
```
So I hope that helps, and you don't have to use `fetch()` or even JavaScript, but the point in my answer is, make sure your request uses the **proper body/content and content type header**.
UPDATE
======
How to access the request parameters
------------------------------------
Please check the [Extending the REST API → Adding Custom Endpoints → Arguments](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments) section in the [REST API handbook](https://developer.wordpress.org/rest-api/) for more details, but here are two of the most common ways in accessing the parameters:
* Use `$request->get_params()` to get all the parameters (URL-encoded POST body, JSON payload, URL query string, etc.). So in your case:
```php
// Instead of this:
$parameters = $request->get_json_params();
if (count($_POST) > 0) {
$parameters = $_POST;
}
// You could simply do:
$parameters = $request->get_params();
```
* Use direct array access on the object passed as the first parameter to your endpoint callback, i.e. the `$request` variable above. E.g.
```php
$contactName = $request['contact_name'];
$contactEmail = $request['contact_email'];
$contactMessage = $request['contact_message'];
```
And in your case, you should probably just use the second option above.
Have you tested your `send_email()` function via direct function calls (i.e. not through the REST API)?
-------------------------------------------------------------------------------------------------------
Although I don't know what's the code in your `send_email()` function, you should test the function by passing test data and see if the function actually works, e.g. does it return true, false, null, is there any errors/notices, etc. And if it's the function that doesn't work, then the problem is not with the REST API, i.e. even on normal requests like the homepage, that function would not work.
So test your *email sending function*, confirm that it receives all the necessary parameters and that it actually properly sends the email (e.g. use the correct headers like "From" and "Content-Type").
Always set `permission_callback`, and utilize `validate_callback` and `sanitize_callback` for validating/sanitizing the request parameters
------------------------------------------------------------------------------------------------------------------------------------------
So basically, except for the `send_email()` function, your code does work in that the endpoint gets registered and it returns a good response. But here are some things that you should bear in mind when adding custom endpoints:
1. Make sure to always set a [`permission_callback`](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback) for your endpoint, because if you don't set it, then the following would happen (but by default, only if [debugging](https://wordpress.org/support/article/debugging-in-wordpress/) is enabled on your site):
>
> As of WordPress
> 5.5, if a `permission_callback` is not provided, the REST API will issue a `_doing_it_wrong` notice.
>
>
>
Sample notice that would be issued:
>
> The REST API route definition for `contact/v1/send` is missing the
> required `permission_callback` argument. For REST API routes that are
> intended to be public, use `__return_true` as the permission callback.
>
>
>
2. The third parameter for [`register_rest_route()`](https://developer.wordpress.org/reference/functions/register_rest_route/) accepts an argument named `args` which is an array of parameters for your endpoint, and for each parameter, you can set a validation callback (`validate_callback`) and a sanitization callback (`sanitize_callback`), so you should use that instead of doing the validation/sanitization in your endpoint's main callback. And here's one of the good reasons why would you want to use those callbacks:
>
> Using `sanitize_callback` and `validate_callback` allows the main
> callback to act only to process the request, and prepare data to be
> returned using the `WP_REST_Response` class. By using these two
> callbacks, you will be able to *safely assume your inputs are valid
> and safe when processing*.
>
>
>
That was a (slightly reformatted) excerpt taken from the API handbook, BTW.
Try my code
-----------
**Note:** I originally tested your code with a *dummy* `send_email()` function, but here, I'm using [`wp_mail()`](https://developer.wordpress.org/reference/functions/wp_mail/) directly in the main callback.
```php
// The code is basically based on yours.
function sendContactMail( WP_REST_Request $request ) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
$siteName = wp_strip_all_tags( trim( get_option( 'blogname' ) ) );
$contactName = $request['contact_name'];
$contactEmail = $request['contact_email'];
$contactMessage = $request['contact_message'];
$subject = "[$siteName] (testing) New message from $contactName";
// $body = "<h3>$subject</h3><br/>";
$body = "<p><b>Name:</b> $contactName</p>";
$body .= "<p><b>Email:</b> $contactEmail</p>";
$body .= "<p><b>Message:</b> $contactMessage</p>";
$to = get_option( 'admin_email' );
$headers = array(
'Content-Type: text/html; charset=UTF-8',
"Reply-To: $contactName <$contactEmail>",
);
if ( wp_mail( $to, $subject, $body, $headers ) ) {
$response['status'] = 200;
$response['message'] = 'Form sent successfully.';
$response['test'] = $body;
}
return new WP_REST_Response( $response );
}
add_action( 'rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', array(
'methods' => 'POST',
'callback' => 'sendContactMail',
'permission_callback' => '__return_true',
'args' => array(
'contact_name' => array(
'required' => true,
'validate_callback' => function ( $value ) {
return preg_match( '/[a-z0-9]{2,}/i', $value ) ? true :
new WP_Error( 'invalid_contact_name', 'Your custom error.' );
},
'sanitize_callback' => 'sanitize_text_field',
),
'contact_email' => array(
'required' => true,
'validate_callback' => 'is_email',
'sanitize_callback' => 'sanitize_email',
),
'contact_message' => array(
'required' => true,
'sanitize_callback' => 'sanitize_textarea_field',
),
),
) );
} );
``` |
380,871 | <p>I am currently developing a theme which provides more customization in Customizer. I am trying to add color control option and it is not working. This is my code.</p>
<pre><code>/* Color Section */
$wp_customize -> add_setting( 'navbar_color', array(
'default' => '#45ace0',
) );
$wp_customize -> add_control( new WP_Customize_Color_Control( $wp_customize, 'navbar_color', array(
'label' => __( 'Navbar Color', 'text_domain' ),
'section' => 'color_section',
'settings' => 'navbar_color',
)
) );
$wp_customize -> add_section( 'color_section', array(
'title' => __( 'Color Section', 'text_domain' ),
) );
</code></pre>
<p>I can't see anything wrong here. Without this customizer is working. But when i add this code, customizer is not loading without any PHP error. Also when i replace to WP_Customize_Color_Control to WP_Customize_Image_Control it working without any problem. This problem only happens with Color Control.</p>
<p>Also, I am getting following JS errors in the console.</p>
<p><a href="https://i.stack.imgur.com/peUWc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peUWc.png" alt="enter image description here" /></a></p>
<p>any solution would be really appreciated.</p>
| [
{
"answer_id": 380879,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 0,
"selected": false,
"text": "<p>According to your needs :</p>\n<p>Register Your Customizer setting , Add Below Code in your functions.php</p>\n<pre><code>function themename_customize_register($wp_customize){\n\n$wp_customize->add_section('themename_color_scheme', array(\n 'title' => __('Color Scheme', 'themename'),\n 'priority' => 120,\n));\n\n// =============================\n// = Color Picker =\n// =============================\n\n$wp_customize->add_setting('themename_theme_options[navbar_color]', array(\n 'default' => '#000',\n 'sanitize_callback' => 'sanitize_hex_color',\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n\n));\n\n$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'navbar_color', array(\n 'label' => __('Link Color', 'themename'),\n 'section' => 'themename_color_scheme',\n 'settings' => 'themename_theme_options[navbar_color]',\n)));\n\n\n// =============================\n// = Text Input =\n// =============================\n$wp_customize->add_setting('themename_theme_options[text_test]', array(\n 'default' => 'Custom Text!',\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n\n));\n\n$wp_customize->add_control('themename_text_test', array(\n 'label' => __('Text Test', 'themename'),\n 'section' => 'themename_color_scheme',\n 'settings' => 'themename_theme_options[text_test]',\n));\n\n// =============================\n// = Image Upload =\n// =============================\n$wp_customize->add_setting('themename_theme_options[image_upload_test]', array(\n 'default' => 'image.jpg',\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n\n));\n\n$wp_customize->add_control( new WP_Customize_Image_Control($wp_customize, 'image_upload_test', array(\n 'label' => __('Image Upload Test', 'themename'),\n 'section' => 'themename_color_scheme',\n 'settings' => 'themename_theme_options[image_upload_test]',\n)));\n\n// =============================\n// = File Upload =\n// =============================\n$wp_customize->add_setting('themename_theme_options[upload_test]', array(\n 'default' => 'arse',\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n\n));\n\n$wp_customize->add_control( new WP_Customize_Upload_Control($wp_customize, 'upload_test', array(\n 'label' => __('Upload Test', 'themename'),\n 'section' => 'themename_color_scheme',\n 'settings' => 'themename_theme_options[upload_test]',\n)));\n\n }\n\nadd_action('customize_register', 'themename_customize_register');\n</code></pre>\n<p>Refer Link For Your Knowledge <a href=\"https://maddisondesigns.com/2017/05/the-wordpress-customizer-a-developers-guide-part-1\" rel=\"nofollow noreferrer\">Click</a></p>\n<p><a href=\"https://i.stack.imgur.com/v9hup.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v9hup.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 383382,
"author": "Álvaro García",
"author_id": 201928,
"author_profile": "https://wordpress.stackexchange.com/users/201928",
"pm_score": 1,
"selected": false,
"text": "<p>Try changing your ID name to another one. Maybe is an ID already in use:</p>\n<pre><code>navbar_color\n</code></pre>\n<p>To:</p>\n<pre><code>my_navbar_color\n</code></pre>\n"
},
{
"answer_id": 383430,
"author": "Sahan",
"author_id": 192486,
"author_profile": "https://wordpress.stackexchange.com/users/192486",
"pm_score": 1,
"selected": true,
"text": "<p>Finally found the reason. The reason was i enqueued JQuery to my options pages. When i remove JQuery enqueue everything is working fine. Thanks for all the replies.</p>\n"
}
] | 2021/01/04 | [
"https://wordpress.stackexchange.com/questions/380871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192486/"
] | I am currently developing a theme which provides more customization in Customizer. I am trying to add color control option and it is not working. This is my code.
```
/* Color Section */
$wp_customize -> add_setting( 'navbar_color', array(
'default' => '#45ace0',
) );
$wp_customize -> add_control( new WP_Customize_Color_Control( $wp_customize, 'navbar_color', array(
'label' => __( 'Navbar Color', 'text_domain' ),
'section' => 'color_section',
'settings' => 'navbar_color',
)
) );
$wp_customize -> add_section( 'color_section', array(
'title' => __( 'Color Section', 'text_domain' ),
) );
```
I can't see anything wrong here. Without this customizer is working. But when i add this code, customizer is not loading without any PHP error. Also when i replace to WP\_Customize\_Color\_Control to WP\_Customize\_Image\_Control it working without any problem. This problem only happens with Color Control.
Also, I am getting following JS errors in the console.
[](https://i.stack.imgur.com/peUWc.png)
any solution would be really appreciated. | Finally found the reason. The reason was i enqueued JQuery to my options pages. When i remove JQuery enqueue everything is working fine. Thanks for all the replies. |
380,881 | <p>I am working on SEO for a website.
So, I wanted to append "-coupon-codes" to all category URLs.</p>
<p>My Category Base Slug is : stores</p>
<p>Example what I wanted to achieve redirection :</p>
<pre><code>/stores/walmart to /stores/walmart-coupon-codes
</code></pre>
<p>as stores/walmart is indexed in google, I want to 301 redirect to new url</p>
<p>I tried this htaccess :</p>
<pre><code>RewriteRule ^stores/(.*)/$ /stores/$1-coupon-codes [R=301,NC,L]
</code></pre>
<p>This was redirecting all store links to /stores-coupon-code
but its 404 as original category URL doesn't contain -coupon-codes,</p>
<p>and if I change any permalink to include -coupon-codes,
Then, the original store URL becomes 404, and redirection isn't working.</p>
| [
{
"answer_id": 380885,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 0,
"selected": false,
"text": "<p>Put Below Code On .htaccess File ,</p>\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^stores/(.*)/$ /stores/$1-coupon-codes [R=301,NC,L]\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n"
},
{
"answer_id": 380891,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<pre><code>RewriteRule ^stores/(.*)/$ /stores/$1-coupon-codes [R=301,NC,L]\n</code></pre>\n</blockquote>\n<p>You can perhaps use a <em>negative lookahead assertion</em> to exclude URLs that already contain <code>-coupon-codes</code> from being redirected <em>again</em>, thus preventing a redirect-loop (which I assume is what's happening here).</p>\n<p>For example:</p>\n<pre><code>RewriteRule ^stores/(?!.*-coupon-codes)(.+)/$ /stores/$1-coupon-codes [R=301,NC,L]\n</code></pre>\n<p>The negative lookahead <code>(?!</code>...<code>)</code> causes the pattern match to fail when the URL already contains <code>-coupon-codes</code>.</p>\n<p>You'll need to clear your browser cache and I'd recommend testing first with a 302 (temporary) redirect to avoid potential caching issues.</p>\n<p>However, there are some inconsistencies here... you gave the example <code>/stores/walmart</code> (no trailing slash). But the rule you stated (which you say <em>does</em> redirect) would only redirect a URL that includes a trailing slash. If the original URL included a trailing slash then there would be no redirect loop here (since the URL you are redirecting to does not include a trailing slash), unless... <em>something else</em> is appending a trailing slash?</p>\n<blockquote>\n<p><strong>UPDATE:</strong> Its working only for URL with slash at the end . Is there any fix for that ? Like appending slash to all URLs of the site if they doesn't have it already .</p>\n</blockquote>\n<p>Yes, you can make the trailing slash <em>optional</em> in the above regex. However, you also need to make the preceding capturing group (ie. <code>(.+)</code>) non-greedy, ie. <code>(.+?)</code> so that it doesn't consume the <em>optional</em> trailing slash. For example:</p>\n<pre><code>RewriteRule ^stores/(?!.*-coupon-codes)(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]\n</code></pre>\n<p>I wouldn't "append a slash" to all URLs <em>before</em> this redirect, since that would incur another redirect. You could naturally append a slash to the resulting <em>substitution</em> string if that is what you want. ie. <code>/stores/$1-coupon-codes/</code>.</p>\n<blockquote>\n<p>One more issue I figured out while pagination, the URLs are broken : <code>stores/walmart/page/2-coupon-codes</code>, as its appending it like this</p>\n</blockquote>\n<p>You could add a <em>condition</em> to exclude URLs that end with a number in the last path segment. eg. <code>/stores/walmart/page/2</code> or <code>/<anything>/<number></code>. For example:</p>\n<pre><code>RewriteCond %{REQUEST_URI} !/\\d+$\nRewriteRule ^stores/(?!.*-coupon-codes)(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]\n</code></pre>\n<p>The <code>!</code> prefix on the <em>CondPattern</em> (2nd argument to the <code>RewriteCond</code> directive) negates the comparison, so it is successful when the regex does not match. In this case, it is successful when the URL-path does not end with a path segment consisting only of digits.</p>\n<blockquote>\n<p>but couldn't add a valid regex for negative look ahead.</p>\n</blockquote>\n<p>You don't <em>need</em> to use a negative lookahead, you could use an additional <em>condition</em> (<code>RewriteCond</code> directive) instead. For example:</p>\n<pre><code>RewriteCond %{REQUEST_URI} !/\\d+$\nRewriteCond %{REQUEST_URI} !-coupon-codes/?$ [NC]\nRewriteRule ^stores/(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]\n</code></pre>\n<p>I didn't just mention this above, as you seem to already be putting the directives in the correct place, but these directives need to go near the top of the <code>.htaccess</code> file, <em>before</em> the WordPress front-controller.</p>\n"
},
{
"answer_id": 380919,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<p>You should flush the rewrite rules from the <code>function.php file</code>.</p>\n<pre><code><?php\n/**\n* flush_rewrite_rules\n* Remove rewrite rules and then recreate rewrite rules.\n* @link https://developer.wordpress.org/reference/functions/flush_rewrite_rules/\n*\n* flush_rewrite_rules(); Need to be removed before pushing to live.\n* Can be replaced before pushing to live by add_action( 'after_switch_theme', 'flush_rewrite_rules' );\n*/\nflush_rewrite_rules(); ?>\n</code></pre>\n<p>Now to update a default category slug, which would then affect the permalink, you should be able to do that from the admin console, on the category management page.</p>\n"
}
] | 2021/01/04 | [
"https://wordpress.stackexchange.com/questions/380881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199821/"
] | I am working on SEO for a website.
So, I wanted to append "-coupon-codes" to all category URLs.
My Category Base Slug is : stores
Example what I wanted to achieve redirection :
```
/stores/walmart to /stores/walmart-coupon-codes
```
as stores/walmart is indexed in google, I want to 301 redirect to new url
I tried this htaccess :
```
RewriteRule ^stores/(.*)/$ /stores/$1-coupon-codes [R=301,NC,L]
```
This was redirecting all store links to /stores-coupon-code
but its 404 as original category URL doesn't contain -coupon-codes,
and if I change any permalink to include -coupon-codes,
Then, the original store URL becomes 404, and redirection isn't working. | >
>
> ```
> RewriteRule ^stores/(.*)/$ /stores/$1-coupon-codes [R=301,NC,L]
>
> ```
>
>
You can perhaps use a *negative lookahead assertion* to exclude URLs that already contain `-coupon-codes` from being redirected *again*, thus preventing a redirect-loop (which I assume is what's happening here).
For example:
```
RewriteRule ^stores/(?!.*-coupon-codes)(.+)/$ /stores/$1-coupon-codes [R=301,NC,L]
```
The negative lookahead `(?!`...`)` causes the pattern match to fail when the URL already contains `-coupon-codes`.
You'll need to clear your browser cache and I'd recommend testing first with a 302 (temporary) redirect to avoid potential caching issues.
However, there are some inconsistencies here... you gave the example `/stores/walmart` (no trailing slash). But the rule you stated (which you say *does* redirect) would only redirect a URL that includes a trailing slash. If the original URL included a trailing slash then there would be no redirect loop here (since the URL you are redirecting to does not include a trailing slash), unless... *something else* is appending a trailing slash?
>
> **UPDATE:** Its working only for URL with slash at the end . Is there any fix for that ? Like appending slash to all URLs of the site if they doesn't have it already .
>
>
>
Yes, you can make the trailing slash *optional* in the above regex. However, you also need to make the preceding capturing group (ie. `(.+)`) non-greedy, ie. `(.+?)` so that it doesn't consume the *optional* trailing slash. For example:
```
RewriteRule ^stores/(?!.*-coupon-codes)(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]
```
I wouldn't "append a slash" to all URLs *before* this redirect, since that would incur another redirect. You could naturally append a slash to the resulting *substitution* string if that is what you want. ie. `/stores/$1-coupon-codes/`.
>
> One more issue I figured out while pagination, the URLs are broken : `stores/walmart/page/2-coupon-codes`, as its appending it like this
>
>
>
You could add a *condition* to exclude URLs that end with a number in the last path segment. eg. `/stores/walmart/page/2` or `/<anything>/<number>`. For example:
```
RewriteCond %{REQUEST_URI} !/\d+$
RewriteRule ^stores/(?!.*-coupon-codes)(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]
```
The `!` prefix on the *CondPattern* (2nd argument to the `RewriteCond` directive) negates the comparison, so it is successful when the regex does not match. In this case, it is successful when the URL-path does not end with a path segment consisting only of digits.
>
> but couldn't add a valid regex for negative look ahead.
>
>
>
You don't *need* to use a negative lookahead, you could use an additional *condition* (`RewriteCond` directive) instead. For example:
```
RewriteCond %{REQUEST_URI} !/\d+$
RewriteCond %{REQUEST_URI} !-coupon-codes/?$ [NC]
RewriteRule ^stores/(.+?)/?$ /stores/$1-coupon-codes [R=301,NC,L]
```
I didn't just mention this above, as you seem to already be putting the directives in the correct place, but these directives need to go near the top of the `.htaccess` file, *before* the WordPress front-controller. |
380,938 | <p>In wordpress I am getting error SMTP Error: Could not authenticate.</p>
<p>Here is the log file:</p>
<pre><code>Versions:
WordPress: 5.6
WordPress MS: No
PHP: 7.4.3
WP Mail SMTP: 2.5.1
Params:
Mailer: smtp
Constants: Yes
ErrorInfo: SMTP Error: Could not authenticate.
Host: mail.vitalticks.com
Port: 587
SMTPSecure: tls
SMTPAutoTLS: bool(true)
SMTPAuth: bool(true)
Server:
OpenSSL: OpenSSL 1.1.1f 31 Mar 2020
Apache.mod_security: No
Debug:
Mailer: Other SMTP
SMTP Error: Could not authenticate.
SMTP Debug:
2021-01-05 05:42:43 Connection: opening to mail.vitalticks.com:587, timeout=300, options=array()
2021-01-05 05:42:43 Connection: opened
2021-01-05 05:42:44 SERVER -> CLIENT: 220-server.vitalticks.com ESMTP Exim 4.93 #2 Mon, 04 Jan 2021 22:42:44 -0700 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2021-01-05 05:42:44 CLIENT -> SERVER: EHLO jasdental.in
2021-01-05 05:42:44 SERVER -> CLIENT: 250-server.vitalticks.com Hello ec2-3-6-131-50.ap-south-1.compute.amazonaws.com [3.6.131.50]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
2021-01-05 05:42:44 CLIENT -> SERVER: STARTTLS
2021-01-05 05:42:44 SERVER -> CLIENT: 220 TLS go ahead
2021-01-05 05:42:45 CLIENT -> SERVER: EHLO jasdental.in
2021-01-05 05:42:45 SERVER -> CLIENT: 250-server.vitalticks.com Hello ec2-3-6-131-50.ap-south-1.compute.amazonaws.com [3.6.131.50]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250 HELP
2021-01-05 05:42:45 CLIENT -> SERVER: AUTH LOGIN
2021-01-05 05:42:45 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2021-01-05 05:42:45 CLIENT -> SERVER: [credentials hidden]
2021-01-05 05:42:46 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2021-01-05 05:42:46 CLIENT -> SERVER: [credentials hidden]
2021-01-05 05:42:48 SERVER -> CLIENT: 535 Incorrect authentication data
2021-01-05 05:42:48 SMTP ERROR: Password command failed: 535 Incorrect authentication data
SMTP Error: Could not authenticate.
2021-01-05 05:42:48 CLIENT -> SERVER: QUIT
2021-01-05 05:42:48 SERVER -> CLIENT: 221 server.vitalticks.com closing connection
2021-01-05 05:42:48 Connection: closed
SMTP Error: Could not authenticate.
</code></pre>
| [
{
"answer_id": 380943,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Password command failed: 535 Incorrect authentication data\n</code></pre>\n<p>The password is wrong.</p>\n"
},
{
"answer_id": 380955,
"author": "somutesting",
"author_id": 190787,
"author_profile": "https://wordpress.stackexchange.com/users/190787",
"pm_score": 1,
"selected": false,
"text": "<p>our team had enabled two factor authentication for mail so for this reason i am getting error.\nafter disabling the two factor authentication SMTP is working.</p>\n"
}
] | 2021/01/05 | [
"https://wordpress.stackexchange.com/questions/380938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190787/"
] | In wordpress I am getting error SMTP Error: Could not authenticate.
Here is the log file:
```
Versions:
WordPress: 5.6
WordPress MS: No
PHP: 7.4.3
WP Mail SMTP: 2.5.1
Params:
Mailer: smtp
Constants: Yes
ErrorInfo: SMTP Error: Could not authenticate.
Host: mail.vitalticks.com
Port: 587
SMTPSecure: tls
SMTPAutoTLS: bool(true)
SMTPAuth: bool(true)
Server:
OpenSSL: OpenSSL 1.1.1f 31 Mar 2020
Apache.mod_security: No
Debug:
Mailer: Other SMTP
SMTP Error: Could not authenticate.
SMTP Debug:
2021-01-05 05:42:43 Connection: opening to mail.vitalticks.com:587, timeout=300, options=array()
2021-01-05 05:42:43 Connection: opened
2021-01-05 05:42:44 SERVER -> CLIENT: 220-server.vitalticks.com ESMTP Exim 4.93 #2 Mon, 04 Jan 2021 22:42:44 -0700 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2021-01-05 05:42:44 CLIENT -> SERVER: EHLO jasdental.in
2021-01-05 05:42:44 SERVER -> CLIENT: 250-server.vitalticks.com Hello ec2-3-6-131-50.ap-south-1.compute.amazonaws.com [3.6.131.50]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
2021-01-05 05:42:44 CLIENT -> SERVER: STARTTLS
2021-01-05 05:42:44 SERVER -> CLIENT: 220 TLS go ahead
2021-01-05 05:42:45 CLIENT -> SERVER: EHLO jasdental.in
2021-01-05 05:42:45 SERVER -> CLIENT: 250-server.vitalticks.com Hello ec2-3-6-131-50.ap-south-1.compute.amazonaws.com [3.6.131.50]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250 HELP
2021-01-05 05:42:45 CLIENT -> SERVER: AUTH LOGIN
2021-01-05 05:42:45 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2021-01-05 05:42:45 CLIENT -> SERVER: [credentials hidden]
2021-01-05 05:42:46 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2021-01-05 05:42:46 CLIENT -> SERVER: [credentials hidden]
2021-01-05 05:42:48 SERVER -> CLIENT: 535 Incorrect authentication data
2021-01-05 05:42:48 SMTP ERROR: Password command failed: 535 Incorrect authentication data
SMTP Error: Could not authenticate.
2021-01-05 05:42:48 CLIENT -> SERVER: QUIT
2021-01-05 05:42:48 SERVER -> CLIENT: 221 server.vitalticks.com closing connection
2021-01-05 05:42:48 Connection: closed
SMTP Error: Could not authenticate.
``` | our team had enabled two factor authentication for mail so for this reason i am getting error.
after disabling the two factor authentication SMTP is working. |
380,940 | <p><strong>The problem:</strong> whenever I type something in <strong>Advanced->Additional Classes</strong> in Gutenberg editor and save the page/post and refresh, those classes disappear. I logged <strong>props.className</strong> in <code>edit</code> function. It logs the value as expected when I type the class name in the <strong>Advanced->Additional Classes</strong> field. The problem occurs when I save the post after inputting the class name and refresh the page. I followed the exact same method in other blocks I created and they work just fine.</p>
<p><strong>The Code:</strong></p>
<pre class="lang-js prettyprint-override"><code> edit: (props) => {
const {attributes, setAttributes} = props;
const headingBgOverlay = Util.getBgOverlay(attributes, 'heading');
const bodyBgOverlay = Util.getBgOverlay(attributes, 'body');
useEffect(() => {
setAttributes({blockId: Util.guidGenerator()});
}, []);
useEffect(() => {
console.log(props)
console.log(props.className)
console.log(attributes.className)
setAttributes({headingBgOverlay});
setAttributes({bodyBgOverlay});
}, [attributes]);
return (
<Fragment>
<Fragment>
<style>
{listIconCss(attributes)}
</style>
<div className={"atbs atbs-pricing-table " + props.className}
id={'atbs-pricing-table-' + attributes.blockId}>
<div className="plan"
style={{...planCss(attributes)}}>
<div className="head" style={{...titleCss(attributes)}}>
<RichText style={{...titleTypographyCss(attributes)}} tagName="h2" className={'m-0'}
value={attributes.title}
onChange={(title) => setAttributes({title})}
placeholder={__('Plan name', 'attire-blocks')}/>
</div>
<div className='atbs_pricing_table_body'>
<RichText
style={{...descrCss(attributes)}}
className={'description'} tagName="p" value={attributes.description}
onChange={(description) => setAttributes({description})}
placeholder={__('Description...', 'attire-blocks')}/>
<div className="price" style={{...priceCss(attributes)}}>
<RichText style={{fontSize: (attributes.priceFontSize / 2) + 'px'}}
className={'symbol'}
tagName="span" value={attributes.symbol}
onChange={(symbol) => setAttributes({symbol})}
placeholder={__('$')}/>
<RichText className={'amount'}
tagName="span" value={attributes.price}
onChange={(price) => setAttributes({price})}
placeholder={__('99.99')}/>
{attributes.recurring && <RichText
style={{fontSize: `${attributes.descrFontSize}${attributes.descrFontSizeUnit}`}}
tagName="span" value={attributes.recurringTime}
className="recurring"
onChange={(value) => setAttributes({recurringTime: value})}
placeholder={__('/month', 'attire-blocks')}/>}
</div>
{attributes.showFeatures && <RichText
style={{...listCss(attributes)}}
multiline="li"
tagName="ul"
className="features"
onChange={(nextValues) => setAttributes({features: nextValues})}
value={attributes.features}
placeholder={__('Write list…', 'attire-blocks')}
/>}
<InnerBlocks allowedBlocks={['attire-blocks/buttons']}
template={[['attire-blocks/buttons', {
buttonAlignment: 'center'
}]]}
templateLock="all"/>
</div>
</div>
</div>
</Fragment>
</Fragment>
);
},
save: ({attributes, className}) => {
//const {attributes} = props;
return (
<Fragment>
<style>
{listIconCss(attributes)}
</style>
<div className={"atbs atbs-pricing-table " + className}
id={'atbs-pricing-table-' + attributes.blockId}>
<div className="plan"
style={{...planCss(attributes)}}>
{attributes.title &&
<div className="head" style={{...titleCss(attributes)}}>
<RichText.Content style={{...titleTypographyCss(attributes)}} tagName="h2" className={'m-0'}
value={attributes.title}/>
</div>}
<div className='atbs_pricing_table_body'>
{attributes.description &&
<RichText.Content
style={{...descrCss(attributes)}}
className={'description'} tagName="p" value={attributes.description}/>}
<div className="price" style={{...priceCss(attributes)}}>
<RichText.Content style={{fontSize: (attributes.priceFontSize / 2) + 'px'}}
className={'symbol'} tagName="span" value={attributes.symbol}/>
<RichText.Content
style={{
color: attributes.bodyTextColor,
fontSize: (attributes.priceFontSize) + 'px'
}}
className={'amount'}
tagName="span" value={attributes.price}/>
{attributes.recurring && <RichText.Content
style={{fontSize: `${attributes.descrFontSize}${attributes.descrFontSizeUnit}`}}
className="recurring"
tagName="span" value={attributes.recurringTime}/>}
</div>
</div>
{attributes.showFeatures && <RichText.Content
style={{...listCss(attributes)}}
className={'features'}
tagName="ul" value={attributes.features}/>}
<InnerBlocks.Content/>
</div>
</div>
</Fragment>
);
}
});
</code></pre>
| [
{
"answer_id": 380943,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Password command failed: 535 Incorrect authentication data\n</code></pre>\n<p>The password is wrong.</p>\n"
},
{
"answer_id": 380955,
"author": "somutesting",
"author_id": 190787,
"author_profile": "https://wordpress.stackexchange.com/users/190787",
"pm_score": 1,
"selected": false,
"text": "<p>our team had enabled two factor authentication for mail so for this reason i am getting error.\nafter disabling the two factor authentication SMTP is working.</p>\n"
}
] | 2021/01/05 | [
"https://wordpress.stackexchange.com/questions/380940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124360/"
] | **The problem:** whenever I type something in **Advanced->Additional Classes** in Gutenberg editor and save the page/post and refresh, those classes disappear. I logged **props.className** in `edit` function. It logs the value as expected when I type the class name in the **Advanced->Additional Classes** field. The problem occurs when I save the post after inputting the class name and refresh the page. I followed the exact same method in other blocks I created and they work just fine.
**The Code:**
```js
edit: (props) => {
const {attributes, setAttributes} = props;
const headingBgOverlay = Util.getBgOverlay(attributes, 'heading');
const bodyBgOverlay = Util.getBgOverlay(attributes, 'body');
useEffect(() => {
setAttributes({blockId: Util.guidGenerator()});
}, []);
useEffect(() => {
console.log(props)
console.log(props.className)
console.log(attributes.className)
setAttributes({headingBgOverlay});
setAttributes({bodyBgOverlay});
}, [attributes]);
return (
<Fragment>
<Fragment>
<style>
{listIconCss(attributes)}
</style>
<div className={"atbs atbs-pricing-table " + props.className}
id={'atbs-pricing-table-' + attributes.blockId}>
<div className="plan"
style={{...planCss(attributes)}}>
<div className="head" style={{...titleCss(attributes)}}>
<RichText style={{...titleTypographyCss(attributes)}} tagName="h2" className={'m-0'}
value={attributes.title}
onChange={(title) => setAttributes({title})}
placeholder={__('Plan name', 'attire-blocks')}/>
</div>
<div className='atbs_pricing_table_body'>
<RichText
style={{...descrCss(attributes)}}
className={'description'} tagName="p" value={attributes.description}
onChange={(description) => setAttributes({description})}
placeholder={__('Description...', 'attire-blocks')}/>
<div className="price" style={{...priceCss(attributes)}}>
<RichText style={{fontSize: (attributes.priceFontSize / 2) + 'px'}}
className={'symbol'}
tagName="span" value={attributes.symbol}
onChange={(symbol) => setAttributes({symbol})}
placeholder={__('$')}/>
<RichText className={'amount'}
tagName="span" value={attributes.price}
onChange={(price) => setAttributes({price})}
placeholder={__('99.99')}/>
{attributes.recurring && <RichText
style={{fontSize: `${attributes.descrFontSize}${attributes.descrFontSizeUnit}`}}
tagName="span" value={attributes.recurringTime}
className="recurring"
onChange={(value) => setAttributes({recurringTime: value})}
placeholder={__('/month', 'attire-blocks')}/>}
</div>
{attributes.showFeatures && <RichText
style={{...listCss(attributes)}}
multiline="li"
tagName="ul"
className="features"
onChange={(nextValues) => setAttributes({features: nextValues})}
value={attributes.features}
placeholder={__('Write list…', 'attire-blocks')}
/>}
<InnerBlocks allowedBlocks={['attire-blocks/buttons']}
template={[['attire-blocks/buttons', {
buttonAlignment: 'center'
}]]}
templateLock="all"/>
</div>
</div>
</div>
</Fragment>
</Fragment>
);
},
save: ({attributes, className}) => {
//const {attributes} = props;
return (
<Fragment>
<style>
{listIconCss(attributes)}
</style>
<div className={"atbs atbs-pricing-table " + className}
id={'atbs-pricing-table-' + attributes.blockId}>
<div className="plan"
style={{...planCss(attributes)}}>
{attributes.title &&
<div className="head" style={{...titleCss(attributes)}}>
<RichText.Content style={{...titleTypographyCss(attributes)}} tagName="h2" className={'m-0'}
value={attributes.title}/>
</div>}
<div className='atbs_pricing_table_body'>
{attributes.description &&
<RichText.Content
style={{...descrCss(attributes)}}
className={'description'} tagName="p" value={attributes.description}/>}
<div className="price" style={{...priceCss(attributes)}}>
<RichText.Content style={{fontSize: (attributes.priceFontSize / 2) + 'px'}}
className={'symbol'} tagName="span" value={attributes.symbol}/>
<RichText.Content
style={{
color: attributes.bodyTextColor,
fontSize: (attributes.priceFontSize) + 'px'
}}
className={'amount'}
tagName="span" value={attributes.price}/>
{attributes.recurring && <RichText.Content
style={{fontSize: `${attributes.descrFontSize}${attributes.descrFontSizeUnit}`}}
className="recurring"
tagName="span" value={attributes.recurringTime}/>}
</div>
</div>
{attributes.showFeatures && <RichText.Content
style={{...listCss(attributes)}}
className={'features'}
tagName="ul" value={attributes.features}/>}
<InnerBlocks.Content/>
</div>
</div>
</Fragment>
);
}
});
``` | our team had enabled two factor authentication for mail so for this reason i am getting error.
after disabling the two factor authentication SMTP is working. |
381,168 | <p>I am trying to get Pages, Posts and Custom Post Types In WordPress website but it is showing some other things in the list.</p>
<p><strong>My Code:</strong></p>
<pre><code><?php $types = get_post_types( ['public' => true ], 'objects' );
foreach ( $types as $type ) {
if ( isset( $type->labels->name) ) { ?>
<?php echo $type->labels->name ?>
<br>
<?php }
} ?>
</code></pre>
<p>In this, I am getting:</p>
<pre><code>Posts
Pages
Media
My Templates
Locations
</code></pre>
<p>But I only want Pages, Posts and Locations (Locations is the Custom Post Type).</p>
<p>Any help is much appreciated.</p>
| [
{
"answer_id": 381175,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 4,
"selected": true,
"text": "<p>You can make an array of the post types you don't want and then check <code>in_array()</code> to see if they match before you output anything with them.</p>\n<pre><code><?php\n //You'll want to get at the actual name for My Templates.\n //My attempt is just a guess.\n $types_array = array( 'attachment' , 'elementor_library' );\n $types = get_post_types( ['public' => true ], 'objects' );\n foreach ( $types as $type ) {\n if( !in_array( $type->name, $types_array )) {\n if ( isset( $type->labels->name) ) {\n echo $type->labels->name . '<br>';\n } \n }\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 381296,
"author": "Rahul Kumar",
"author_id": 172395,
"author_profile": "https://wordpress.stackexchange.com/users/172395",
"pm_score": 1,
"selected": false,
"text": "<p><strong>I tried this and got the solution:</strong></p>\n<pre><code><?php\n $types = get_post_types( ['public' => true ], 'objects' );\n $exclude = array( 'attachment' , 'elementor_library' );\n\n foreach ( $types as $type ) {\n if( !in_array( $type->name, $exclude )) {\n if ( isset( $type->labels->name) ) {\n echo $type->labels->name . '<br>';\n } \n }\n }\n?>\n</code></pre>\n<p>You are use this or the above one also.</p>\n<p><strong>In this, You will get:</strong></p>\n<pre><code>Pages\nPosts\nCustom Post Types\n</code></pre>\n"
}
] | 2021/01/08 | [
"https://wordpress.stackexchange.com/questions/381168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172395/"
] | I am trying to get Pages, Posts and Custom Post Types In WordPress website but it is showing some other things in the list.
**My Code:**
```
<?php $types = get_post_types( ['public' => true ], 'objects' );
foreach ( $types as $type ) {
if ( isset( $type->labels->name) ) { ?>
<?php echo $type->labels->name ?>
<br>
<?php }
} ?>
```
In this, I am getting:
```
Posts
Pages
Media
My Templates
Locations
```
But I only want Pages, Posts and Locations (Locations is the Custom Post Type).
Any help is much appreciated. | You can make an array of the post types you don't want and then check `in_array()` to see if they match before you output anything with them.
```
<?php
//You'll want to get at the actual name for My Templates.
//My attempt is just a guess.
$types_array = array( 'attachment' , 'elementor_library' );
$types = get_post_types( ['public' => true ], 'objects' );
foreach ( $types as $type ) {
if( !in_array( $type->name, $types_array )) {
if ( isset( $type->labels->name) ) {
echo $type->labels->name . '<br>';
}
}
}
?>
``` |
381,226 | <p>Using Astra theme, I cannot use jQuery on the frontend. It keeps logging <code>Uncaught ReferenceError: jQuery is not defined at VM105:23</code>. It is actually supposed that Wordpress is equipped with jQuery, but I cannot figure out why I get that 'undefined' error message in console.</p>
<p>So as to add jQuery, I just write the following code, yet to no effect:</p>
<pre><code> function addjq () {
wp_enqueue_script('jquery', plugin_dir_url(__FILE__) . '/in/jq.js', array('jquery'), null, false);
}
add_action('wp_enqueue_scripts', 'addjq');
</code></pre>
<p>I am using this piece inside a widget, and it is not including <code>jquery</code> to the frontend. It actually comes up with that <code>Uncaught ReferenceError</code>. Is the problem somehow related to my <code>jquery</code> file url, or is it a core problem that I need to address. Can you help me out of the problem, and let me know how I can use <code>jquery</code> inside a plugin <strong><code>widget</code></strong>. The following jQuery code throws that console error:</p>
<pre><code>jQuery(document).ready(function() {
// Some Code Goes Here...
})
</code></pre>
<p>PS: I also tried to add a <code>src</code> attribute to the script tag, and bring in the jQuery. <strong><code>RESULT</code></strong>: The error disappeared, yet no jQuery code was run. Even I could not do a simple <code>console.log()</code>.</p>
<p>Thanks in advance...</p>
| [
{
"answer_id": 381229,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p><code>'jquery'</code> is already a registered script in WordPress. Your attempt to enqueue it is failing because WordPress thinks you're trying to register <code>jquery</code> with a new URL, which it ignores. See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">the notes on <code>wp_enqueue_script()</code></a>.</p>\n<p>To load WordPress's existing jQuery library, do this:</p>\n<pre><code>function wpse_381226_load_jquery () {\n wp_enqueue_script( 'jquery');\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_381226_load_jquery' );\n</code></pre>\n"
},
{
"answer_id": 381230,
"author": "H. M..",
"author_id": 197920,
"author_profile": "https://wordpress.stackexchange.com/users/197920",
"pm_score": 1,
"selected": false,
"text": "<p>Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.</p>\n<pre><code> jQuery(document).ready(function() {\n // Some Code Goes Here...\n })\n</code></pre>\n<p>Just take a look at the complete segment:</p>\n<pre><code> public function doSomethingSpecific() {\n ?>\n <script type="text/javascript" >\n \n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n\n }\n\n </script>\n <?php\n }\n</code></pre>\n<p>Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that <code>Uncaught ReferenceError: jQuery is not defined at VM105:23</code> error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that <code>jQuery</code> segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue <code>'jQuery'</code>.</p>\n<pre><code> public function webcamcapchur() {\n ?>\n <script type="text/javascript" >\n window.onload = function doLoadThePage(event) {\n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n }\n\n </script>\n <?php\n }\n</code></pre>\n"
}
] | 2021/01/09 | [
"https://wordpress.stackexchange.com/questions/381226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/197920/"
] | Using Astra theme, I cannot use jQuery on the frontend. It keeps logging `Uncaught ReferenceError: jQuery is not defined at VM105:23`. It is actually supposed that Wordpress is equipped with jQuery, but I cannot figure out why I get that 'undefined' error message in console.
So as to add jQuery, I just write the following code, yet to no effect:
```
function addjq () {
wp_enqueue_script('jquery', plugin_dir_url(__FILE__) . '/in/jq.js', array('jquery'), null, false);
}
add_action('wp_enqueue_scripts', 'addjq');
```
I am using this piece inside a widget, and it is not including `jquery` to the frontend. It actually comes up with that `Uncaught ReferenceError`. Is the problem somehow related to my `jquery` file url, or is it a core problem that I need to address. Can you help me out of the problem, and let me know how I can use `jquery` inside a plugin **`widget`**. The following jQuery code throws that console error:
```
jQuery(document).ready(function() {
// Some Code Goes Here...
})
```
PS: I also tried to add a `src` attribute to the script tag, and bring in the jQuery. **`RESULT`**: The error disappeared, yet no jQuery code was run. Even I could not do a simple `console.log()`.
Thanks in advance... | Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.
```
jQuery(document).ready(function() {
// Some Code Goes Here...
})
```
Just take a look at the complete segment:
```
public function doSomethingSpecific() {
?>
<script type="text/javascript" >
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
```
Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that `Uncaught ReferenceError: jQuery is not defined at VM105:23` error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that `jQuery` segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue `'jQuery'`.
```
public function webcamcapchur() {
?>
<script type="text/javascript" >
window.onload = function doLoadThePage(event) {
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
``` |
381,258 | <p>I have added a custom post type and I want to expose the custom field value in the rest api. As per the docs register_meta can be used.</p>
<p>I have created a custom post meta box using the wordpress way. It works fine but not getting shown in the rest api. I belive that I have to pass array</p>
<p><a href="https://i.stack.imgur.com/3Rb2o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Rb2o.png" alt="enter image description here" /></a></p>
<pre><code>add_action( 'rest_api_init', 'qrcode_register_posts_meta_field' );
function qrcode_register_posts_meta_field(){
$meta_args = array( // Validate and sanitize the meta value.
'type' => 'array',
'description' => 'A meta key associated with a string meta value.',
'single' => true,
'show_in_rest' => array(
'schema'=> array(
'type'=> 'array',
'items'=> array(
'type'=> 'string',
),
),
),
);
register_meta( 'post', 'qrcode_qr-code-type', $meta_args );
}
</code></pre>
| [
{
"answer_id": 381229,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p><code>'jquery'</code> is already a registered script in WordPress. Your attempt to enqueue it is failing because WordPress thinks you're trying to register <code>jquery</code> with a new URL, which it ignores. See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">the notes on <code>wp_enqueue_script()</code></a>.</p>\n<p>To load WordPress's existing jQuery library, do this:</p>\n<pre><code>function wpse_381226_load_jquery () {\n wp_enqueue_script( 'jquery');\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_381226_load_jquery' );\n</code></pre>\n"
},
{
"answer_id": 381230,
"author": "H. M..",
"author_id": 197920,
"author_profile": "https://wordpress.stackexchange.com/users/197920",
"pm_score": 1,
"selected": false,
"text": "<p>Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.</p>\n<pre><code> jQuery(document).ready(function() {\n // Some Code Goes Here...\n })\n</code></pre>\n<p>Just take a look at the complete segment:</p>\n<pre><code> public function doSomethingSpecific() {\n ?>\n <script type="text/javascript" >\n \n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n\n }\n\n </script>\n <?php\n }\n</code></pre>\n<p>Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that <code>Uncaught ReferenceError: jQuery is not defined at VM105:23</code> error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that <code>jQuery</code> segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue <code>'jQuery'</code>.</p>\n<pre><code> public function webcamcapchur() {\n ?>\n <script type="text/javascript" >\n window.onload = function doLoadThePage(event) {\n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n }\n\n </script>\n <?php\n }\n</code></pre>\n"
}
] | 2021/01/10 | [
"https://wordpress.stackexchange.com/questions/381258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have added a custom post type and I want to expose the custom field value in the rest api. As per the docs register\_meta can be used.
I have created a custom post meta box using the wordpress way. It works fine but not getting shown in the rest api. I belive that I have to pass array
[](https://i.stack.imgur.com/3Rb2o.png)
```
add_action( 'rest_api_init', 'qrcode_register_posts_meta_field' );
function qrcode_register_posts_meta_field(){
$meta_args = array( // Validate and sanitize the meta value.
'type' => 'array',
'description' => 'A meta key associated with a string meta value.',
'single' => true,
'show_in_rest' => array(
'schema'=> array(
'type'=> 'array',
'items'=> array(
'type'=> 'string',
),
),
),
);
register_meta( 'post', 'qrcode_qr-code-type', $meta_args );
}
``` | Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.
```
jQuery(document).ready(function() {
// Some Code Goes Here...
})
```
Just take a look at the complete segment:
```
public function doSomethingSpecific() {
?>
<script type="text/javascript" >
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
```
Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that `Uncaught ReferenceError: jQuery is not defined at VM105:23` error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that `jQuery` segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue `'jQuery'`.
```
public function webcamcapchur() {
?>
<script type="text/javascript" >
window.onload = function doLoadThePage(event) {
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
``` |
381,292 | <p>I'm trying to output the current post categories for my 'portfolio' custom post type as a shortcode.</p>
<p>At the moment I have this snippet in the functions.php</p>
<pre><code> function shows_cats(){
$page_id = get_queried_object_id();
echo '<h6>Categories</h6>';
echo get_the_category_list('','',$page_id);
}
add_shortcode('showscats','shows_cats');
</code></pre>
<p>I've tried a few different combinations to call the CPT but have had no luck. I realise that this snippet is just outputting standard WP categories but was wondering if anyone knew a way to edit this to display the CTP instead.</p>
<p>Many thanks for your help</p>
| [
{
"answer_id": 381229,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p><code>'jquery'</code> is already a registered script in WordPress. Your attempt to enqueue it is failing because WordPress thinks you're trying to register <code>jquery</code> with a new URL, which it ignores. See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">the notes on <code>wp_enqueue_script()</code></a>.</p>\n<p>To load WordPress's existing jQuery library, do this:</p>\n<pre><code>function wpse_381226_load_jquery () {\n wp_enqueue_script( 'jquery');\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_381226_load_jquery' );\n</code></pre>\n"
},
{
"answer_id": 381230,
"author": "H. M..",
"author_id": 197920,
"author_profile": "https://wordpress.stackexchange.com/users/197920",
"pm_score": 1,
"selected": false,
"text": "<p>Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.</p>\n<pre><code> jQuery(document).ready(function() {\n // Some Code Goes Here...\n })\n</code></pre>\n<p>Just take a look at the complete segment:</p>\n<pre><code> public function doSomethingSpecific() {\n ?>\n <script type="text/javascript" >\n \n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n\n }\n\n </script>\n <?php\n }\n</code></pre>\n<p>Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that <code>Uncaught ReferenceError: jQuery is not defined at VM105:23</code> error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that <code>jQuery</code> segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue <code>'jQuery'</code>.</p>\n<pre><code> public function webcamcapchur() {\n ?>\n <script type="text/javascript" >\n window.onload = function doLoadThePage(event) {\n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n }\n\n </script>\n <?php\n }\n</code></pre>\n"
}
] | 2021/01/11 | [
"https://wordpress.stackexchange.com/questions/381292",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200177/"
] | I'm trying to output the current post categories for my 'portfolio' custom post type as a shortcode.
At the moment I have this snippet in the functions.php
```
function shows_cats(){
$page_id = get_queried_object_id();
echo '<h6>Categories</h6>';
echo get_the_category_list('','',$page_id);
}
add_shortcode('showscats','shows_cats');
```
I've tried a few different combinations to call the CPT but have had no luck. I realise that this snippet is just outputting standard WP categories but was wondering if anyone knew a way to edit this to display the CTP instead.
Many thanks for your help | Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.
```
jQuery(document).ready(function() {
// Some Code Goes Here...
})
```
Just take a look at the complete segment:
```
public function doSomethingSpecific() {
?>
<script type="text/javascript" >
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
```
Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that `Uncaught ReferenceError: jQuery is not defined at VM105:23` error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that `jQuery` segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue `'jQuery'`.
```
public function webcamcapchur() {
?>
<script type="text/javascript" >
window.onload = function doLoadThePage(event) {
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
``` |
381,345 | <p>I've installed Wordpress on a bare Ubuntu20-04 box following <a href="https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-20-04-with-a-lamp-stack" rel="nofollow noreferrer">Digital Ocean's guide</a>.
Now I want to password protect the entire site but as I can't find any plugins that protect uploaded files and images, I'm attempting to use basic auth.</p>
<p>So I've created a .htpasswd file</p>
<pre><code>-rw-r--r-- 1 root root 132 Jan 12 00:07 /etc/wordpress/.htpasswd
</code></pre>
<p>I've edited /var/www/mysite.com/.htaccess (substituting a real domain for mysite)
to read:</p>
<pre><code># The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/wordpress/.htpasswd
require valid-user
</code></pre>
<p>But the site still loads happily without my desired ugly login prompts.<br />
<strong>...what am I doing wrong?</strong></p>
<p>Alternative solutions to basic auth are welcome but I thought that appeared to be the simplest route to protecting uploaded content. (it's for hosting info about an apartment block for the block's inmates and some things eg meeting minutes are semi-confidential - if people have to log in once per session to access the site I don't mind)</p>
| [
{
"answer_id": 381229,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p><code>'jquery'</code> is already a registered script in WordPress. Your attempt to enqueue it is failing because WordPress thinks you're trying to register <code>jquery</code> with a new URL, which it ignores. See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">the notes on <code>wp_enqueue_script()</code></a>.</p>\n<p>To load WordPress's existing jQuery library, do this:</p>\n<pre><code>function wpse_381226_load_jquery () {\n wp_enqueue_script( 'jquery');\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_381226_load_jquery' );\n</code></pre>\n"
},
{
"answer_id": 381230,
"author": "H. M..",
"author_id": 197920,
"author_profile": "https://wordpress.stackexchange.com/users/197920",
"pm_score": 1,
"selected": false,
"text": "<p>Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.</p>\n<pre><code> jQuery(document).ready(function() {\n // Some Code Goes Here...\n })\n</code></pre>\n<p>Just take a look at the complete segment:</p>\n<pre><code> public function doSomethingSpecific() {\n ?>\n <script type="text/javascript" >\n \n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n\n }\n\n </script>\n <?php\n }\n</code></pre>\n<p>Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that <code>Uncaught ReferenceError: jQuery is not defined at VM105:23</code> error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that <code>jQuery</code> segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue <code>'jQuery'</code>.</p>\n<pre><code> public function webcamcapchur() {\n ?>\n <script type="text/javascript" >\n window.onload = function doLoadThePage(event) {\n jQuery(document).ready(function() {\n console.log('Hello World!');\n })\n }\n\n </script>\n <?php\n }\n</code></pre>\n"
}
] | 2021/01/12 | [
"https://wordpress.stackexchange.com/questions/381345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189230/"
] | I've installed Wordpress on a bare Ubuntu20-04 box following [Digital Ocean's guide](https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-20-04-with-a-lamp-stack).
Now I want to password protect the entire site but as I can't find any plugins that protect uploaded files and images, I'm attempting to use basic auth.
So I've created a .htpasswd file
```
-rw-r--r-- 1 root root 132 Jan 12 00:07 /etc/wordpress/.htpasswd
```
I've edited /var/www/mysite.com/.htaccess (substituting a real domain for mysite)
to read:
```
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/wordpress/.htpasswd
require valid-user
```
But the site still loads happily without my desired ugly login prompts.
**...what am I doing wrong?**
Alternative solutions to basic auth are welcome but I thought that appeared to be the simplest route to protecting uploaded content. (it's for hosting info about an apartment block for the block's inmates and some things eg meeting minutes are semi-confidential - if people have to log in once per session to access the site I don't mind) | Special thanks are offered to @Pat J. The problem was actually with the jQuery code I had written.
```
jQuery(document).ready(function() {
// Some Code Goes Here...
})
```
Just take a look at the complete segment:
```
public function doSomethingSpecific() {
?>
<script type="text/javascript" >
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
```
Since the above function was not correctly enqueued, and actually supposedly kept running before jQuery was loaded, I received that `Uncaught ReferenceError: jQuery is not defined at VM105:23` error. So what I did to solve the problem was to wait for the page to load fully and then call the code. Therefore I changed that `jQuery` segment shown above to the following and it was good to go. Problem Solved, and definitely there was no need to enqueue `'jQuery'`.
```
public function webcamcapchur() {
?>
<script type="text/javascript" >
window.onload = function doLoadThePage(event) {
jQuery(document).ready(function() {
console.log('Hello World!');
})
}
</script>
<?php
}
``` |
381,433 | <p>We have developed a Wordpress plugin to create a reservation engine. We use a shortcode to build the checkout process. This shortcode creates html. We would like to define a sidebar in this generated html so the plugin users can append some content regarding the reservation information.</p>
<p>Is it not a bad practice to add a sidebar to allow the plugin users to customize it?</p>
| [
{
"answer_id": 381434,
"author": "hrsetyono",
"author_id": 33361,
"author_profile": "https://wordpress.stackexchange.com/users/33361",
"pm_score": 2,
"selected": false,
"text": "<p>There's nothing wrong with registering a sidebar via plugin. You do it the same way as registering via theme:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'widgets_init', function() {\n register_sidebar([\n 'name' => 'Your Sidebar',\n 'id' => 'your-sidebar',\n ] );\n} );\n</code></pre>\n"
},
{
"answer_id": 381437,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": -1,
"selected": false,
"text": "<p>As @hrsetyono said, plugins can register anything themes can, including widget sidebars.</p>\n<p>However, we would not recommend using an anonymous closure function, as this cannot be removed by other plugins - instead make it using a public function ( of hooking to a public class method is also fine ).</p>\n<pre><code>add_action( 'widgets_init', 'wpse_381433_widget', 10 );\n\nfunction wpse_381433_widget(){\n register_sidebar([\n 'name' => 'Your Sidebar',\n 'id' => 'your-sidebar',\n ]);\n};\n</code></pre>\n<p>Also note that you should try to add filters to all values that others may want to manipulate using <code>apply_filters</code> - this gives other plugins a clean route in to change values without needed to change your plugin code.</p>\n<p>For example:</p>\n<pre><code>// assign variable value ##\n$number = 10;\n\n// allow value to be filtered ##\n$number = apply_filters( 'plugin/function/variable', $number );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/apply_filters/</a></p>\n"
}
] | 2021/01/13 | [
"https://wordpress.stackexchange.com/questions/381433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200295/"
] | We have developed a Wordpress plugin to create a reservation engine. We use a shortcode to build the checkout process. This shortcode creates html. We would like to define a sidebar in this generated html so the plugin users can append some content regarding the reservation information.
Is it not a bad practice to add a sidebar to allow the plugin users to customize it? | There's nothing wrong with registering a sidebar via plugin. You do it the same way as registering via theme:
```php
add_action( 'widgets_init', function() {
register_sidebar([
'name' => 'Your Sidebar',
'id' => 'your-sidebar',
] );
} );
``` |
381,452 | <p>I have two Custom Post Types and would like to display one of them sorted (by title) and the other one at random places in the same query.</p>
<p>So CPT A (sorted) en CPT B (random):</p>
<p>A1 A2 A3 <strong>B2</strong> A4 A5 <strong>B5</strong> A6 A7 A8 A9 <strong>B1</strong> ...<br>
or<br>
A1 <strong>B1</strong> A2 A3 <strong>B5</strong> A4 A5 A6 A7 A8 A9 <strong>B7</strong> ...<br>
or<br>
<strong>B4</strong> A1 A2 A3 A4 <strong>B3</strong> A5 A6 A7 A8 <strong>B1</strong> A9 ...</p>
<p>I tried merging the two CPT but that didn't work as expected.</p>
<pre><code>$projectposts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'project',
'order' => 'ASC'
));
//second query
$storieposts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'storie',
'order' => 'rand'
));
$mergedposts = array_merge( $projectposts, $storieposts ); //combined querie
</code></pre>
<p>@kero:<br>
I have this ↓ and it's almost working... It looks like this creates some empty entries in the array. (I'm 100% certain that there are no empty titles before merging.) <br>
The query results in A3 A2 A4 A6 B2 (empty) (empty) (empty) A1 (empty) (empty) B1 B3 ...</p>
<pre><code> $projectposts = get_posts([
'posts_per_page' => -1,
'post_type' => 'project',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'featured',
'value' => '"homepagina"',
'compare' => 'LIKE'
)
)
]);
$storieposts = get_posts([
'posts_per_page' => -1,
'post_type' => 'story',
'order' => 'ASC',// not rand!
'meta_query' => array(
array(
'key' => 'featured',
'value' => '"homepagina"',
'compare' => 'LIKE'
)
)
]);
function array_random_merge(array $a, array $b): array {
while (count($b) > 0) {
shuffle($b);
// get one entry of $b
$item = array_shift($b);
// find random position inside $a
$pos = mt_rand(0, count($a) - 1);
// insert $item into $a
array_splice($a, $pos, 0, $item);
}
return $a;
}
$mergedposts = array_random_merge($projectposts, $storieposts);
if( $mergedposts ) {
foreach( $mergedposts as $post ) {
echo '<h3>';
echo the_title();
echo '</h3>';
}
}
wp_reset_postdata();
</code></pre>
| [
{
"answer_id": 381458,
"author": "burlakvo",
"author_id": 198451,
"author_profile": "https://wordpress.stackexchange.com/users/198451",
"pm_score": 1,
"selected": false,
"text": "<p>Try to get two different arrays of posts and loop through array A. Before get post data of A element get random element from array B.</p>\n<p>For example:</p>\n<pre><code>$array_a = ['post_id_a1', 'post_id_a2', 'post_id_a3'];\n$array_b = ['post_id_b1', 'post_id_b2', 'post_id_b3'];\n\nforeach ( $array_a as $a_post_id ) {\n $is_b_should_displayed = mt_rand( 0, 1 );\n\n if ( $is_b_should_displayed && $b_length = count( $array_b ) ){\n $b_to_show = mt_rand( 0, $b_length - 1 );\n\n // show random B post\n\n unset( $array_b[ $b_to_show ] );\n $array_b = array_values( $array_b ); // to reorder array after unset\n }\n\n // show A post\n}\n</code></pre>\n<p>Or in same way create array C, and then loop through C to display posts.\nThere is no warranty all B will displayed, so, if you need it, you could loop through B (if at least 1 element exist) after main A loop</p>\n<p>Small note: <code>rand</code> using for key <code>orderby</code> not to <em>order</em> according to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">wp docs</a>.</p>\n<p>Hope it helps</p>\n"
},
{
"answer_id": 381468,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably do it like this:</p>\n<pre><code>$projects = get_posts([\n 'posts_per_page' => -1,\n 'post_type' => 'project',\n 'order' => 'ASC',\n]);\n\n$stories = get_posts([\n 'posts_per_page' => -1,\n 'post_type' => 'storie',\n 'order' => 'ASC',// not rand!\n]);\n\nfunction array_random_merge(array $a, array $b): array {\n while (count($b) > 0) {\n shuffle($b);\n // get one entry of $b\n $item = array_shift($b);\n\n // find random position inside $a\n $pos = mt_rand(0, count($a) - 1);\n // insert $item into $a\n array_splice($a, $pos, 0, $item);\n }\n return $a;\n}\n\n$merged = array_random_merge($projects, $stories);\n</code></pre>\n<p>The main idea here is the following:</p>\n<ol>\n<li>remove one <code>$item</code> from <code>$b</code></li>\n<li>insert that at a random position in <code>$a</code></li>\n<li>repeat 1 & 2 until <code>$b</code> is empty.</li>\n</ol>\n<p><a href=\"https://wordpress.stackexchange.com/questions/381452/combining-sorted-and-random-cpt/381468#comment553511_381452\">Per Tom's comment</a> I removed <code>rand</code> order in the query and simple <code>shuffle()</code> the array.</p>\n"
}
] | 2021/01/13 | [
"https://wordpress.stackexchange.com/questions/381452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127299/"
] | I have two Custom Post Types and would like to display one of them sorted (by title) and the other one at random places in the same query.
So CPT A (sorted) en CPT B (random):
A1 A2 A3 **B2** A4 A5 **B5** A6 A7 A8 A9 **B1** ...
or
A1 **B1** A2 A3 **B5** A4 A5 A6 A7 A8 A9 **B7** ...
or
**B4** A1 A2 A3 A4 **B3** A5 A6 A7 A8 **B1** A9 ...
I tried merging the two CPT but that didn't work as expected.
```
$projectposts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'project',
'order' => 'ASC'
));
//second query
$storieposts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'storie',
'order' => 'rand'
));
$mergedposts = array_merge( $projectposts, $storieposts ); //combined querie
```
@kero:
I have this ↓ and it's almost working... It looks like this creates some empty entries in the array. (I'm 100% certain that there are no empty titles before merging.)
The query results in A3 A2 A4 A6 B2 (empty) (empty) (empty) A1 (empty) (empty) B1 B3 ...
```
$projectposts = get_posts([
'posts_per_page' => -1,
'post_type' => 'project',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'featured',
'value' => '"homepagina"',
'compare' => 'LIKE'
)
)
]);
$storieposts = get_posts([
'posts_per_page' => -1,
'post_type' => 'story',
'order' => 'ASC',// not rand!
'meta_query' => array(
array(
'key' => 'featured',
'value' => '"homepagina"',
'compare' => 'LIKE'
)
)
]);
function array_random_merge(array $a, array $b): array {
while (count($b) > 0) {
shuffle($b);
// get one entry of $b
$item = array_shift($b);
// find random position inside $a
$pos = mt_rand(0, count($a) - 1);
// insert $item into $a
array_splice($a, $pos, 0, $item);
}
return $a;
}
$mergedposts = array_random_merge($projectposts, $storieposts);
if( $mergedposts ) {
foreach( $mergedposts as $post ) {
echo '<h3>';
echo the_title();
echo '</h3>';
}
}
wp_reset_postdata();
``` | Try to get two different arrays of posts and loop through array A. Before get post data of A element get random element from array B.
For example:
```
$array_a = ['post_id_a1', 'post_id_a2', 'post_id_a3'];
$array_b = ['post_id_b1', 'post_id_b2', 'post_id_b3'];
foreach ( $array_a as $a_post_id ) {
$is_b_should_displayed = mt_rand( 0, 1 );
if ( $is_b_should_displayed && $b_length = count( $array_b ) ){
$b_to_show = mt_rand( 0, $b_length - 1 );
// show random B post
unset( $array_b[ $b_to_show ] );
$array_b = array_values( $array_b ); // to reorder array after unset
}
// show A post
}
```
Or in same way create array C, and then loop through C to display posts.
There is no warranty all B will displayed, so, if you need it, you could loop through B (if at least 1 element exist) after main A loop
Small note: `rand` using for key `orderby` not to *order* according to [wp docs](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters).
Hope it helps |
381,520 | <p>When writting a description for a Woocoomerce Product and inserting a line break with <strong>br</strong> or <strong>p</strong> Tag, WordPress automatically removes it. This is really annoying because on some points, i want to have a little line break.</p>
<p>I often found the solution to install TinyMCE. After that now WordPress doesnt removes the <strong>p</strong> Tag anymore but inserts a <strong>&nbsp</strong> inside of it and so the line break is way to big.</p>
<p>So i want a line break like a <strong>p</strong> Tag, because <strong>npsb</strong> produces way too much space between two sentence.</p>
<p>I also tried following solutions:</p>
<ol>
<li><p>add some attributes to the p Tag like <code> <p data-x> </p></code></p>
</li>
<li><p>Wrap the p Tag with comments like</p>
</li>
</ol>
<pre><code><!-- wp:html --> <p class="beer"></p> <!-- /wp:html -->
</code></pre>
<ol start="3">
<li>Added some hooks in the functions.php like</li>
</ol>
<pre><code>add_shortcode("br", "br_tag"); function br_tag(){ return("<br/>"); }
</code></pre>
<p>or</p>
<pre><code>remove_filter('the_content', 'wpautop'); remove_filter('the_excerpt', 'wpautop');
</code></pre>
<p>and</p>
<pre><code>remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); function wpse_wpautop_nobr( $content ) { return wpautop( $content, false ); } add_filter( 'the_content', 'wpse_wpautop_nobr' ); add_filter( 'the_excerpt', 'wpse_wpautop_nobr' );
</code></pre>
<ol start="4">
<li>I tried following solution but it doesnt work <a href="https://wordpress.stackexchange.com/questions/29702/wordpress-automatically-adding-nbsp">Wordpress automatically adding "&nbsp;"?</a></li>
</ol>
<p>The "best" solution i found was to NOT using the visual AND the text editor, but for me thats such a temporary one.</p>
<p>Specs:</p>
<p>WordPress 5.6</p>
<p>Advanced Editor Tools (previously TinyMCE Advanced): 5.6</p>
<p>WooCommerce: 4.6.1 (but in my opinion, its not a WooCommerce problem)</p>
<p>Does anyone know a better solution or a reference for that problem?</p>
| [
{
"answer_id": 381491,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 2,
"selected": false,
"text": "<p>Your site appears to be pretty well structured in most ways and you're getting a good score. If you're seeing a huge swing day to day, test to test, etc, then it's probably a hosting related issue. What type of hosting are you on? Is it cloud, is it shared, is it WordPress specific?</p>\n<p><a href=\"https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.greenstuff.sk%2F&tab=desktop\" rel=\"nofollow noreferrer\">https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.greenstuff.sk%2F&tab=desktop</a></p>\n<p>Google's PageSpeed Insights rates you at 93 for desktop - that's good. In fact, the only place it even throws a complaint is <strong>Reduce Initial Server Response Time: 1.73s</strong>. So what that tells me is that the inconsistent performance scores you are sometimes seeing are probably down to your hosting.</p>\n<p>There's a few key things to remember when you're evaluating a site's performance, because there's really three different 'performance areas' that you need to consider.</p>\n<ol>\n<li><p>There's your 'user perceived' speed; when you open the site in a new browser on a new computer or a new device and visit the URL directly for the first time, what's it load like for the end user in terms of what they see and what their experience is. This experience is super important.</p>\n</li>\n<li><p>Your page speed 'rating' - this isn't necessarily a direct indication of how fast the page loads, but rather a diagnostic check of how everything involved in generating a page is optimized and yes, Search Engines do consider these values.</p>\n</li>\n<li><p>Theres your 'actual page load' speed; as in how quickly the entire contents, code and assets of the page load.</p>\n</li>\n</ol>\n<p>If your Page Speed Rating is good and your user is seeing a full screen of useful content almost instantly, then it's ok if your site is still loading future needed assets and content. Obviously we want this to be as quick as possible but if what's loading last is a script that validates a MailChimp Subscribe form that pops up when a user clicks a button and only after the user has typed out their info, then it's not a huge worry if that script loads a half second later than the page is visible to the user.</p>\n<p>You have to find a balance and ultimately test your site as a new user and measure the experience there first, then look at your Page Speed Rating and lastly look at your actual full load time, that's the order I address things in.</p>\n<p>My recommendation, if you want consistency in performance and you want a really smooth running site is to avoid those plugins that promise better performance, automated minification, etc... ...I have seen the mess that can occur when those things go wrong and it isn't pretty. And those plugins also aren't a 'fix' for a slow or broken site. Those plugins, IF used, should be used to take a well built site that functions very well and then simply optimize what's already working. If your theme or a plugin are running really slow, laborious queries over and over again, there's no amount of minification or caching that's going to fix that.</p>\n<p>So drop those plugins and get yourself onto a really good dedicated WordPress hosting platform, especially if you're running eCommerce. I like to use FlyWheel and then hook my site up to ManageWP for hourly back-ups when it comes to eCommerce sites so I always have all the sales data backed up. (Not linking to either one because that may be against the rules here.)</p>\n"
},
{
"answer_id": 404644,
"author": "O. Jones",
"author_id": 13596,
"author_profile": "https://wordpress.stackexchange.com/users/13596",
"pm_score": 1,
"selected": false,
"text": "<p>Two suggestions.</p>\n<p>First, install a persistent object cache like redis, and a plugin to use it. That makes a lot of difference in TTFB on most sites, especially busy and complex ones (like Woo sites). Read all about it. <a href=\"https://developer.wordpress.org/reference/classes/wp_object_cache/#persistent-caching\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_object_cache/#persistent-caching</a></p>\n<p>Second, change the keys on your database tables to be more efficient, especially for Woo product lookups. <a href=\"https://wordpress.org/plugins/index-wp-mysql-for-speed/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/index-wp-mysql-for-speed/</a></p>\n"
}
] | 2021/01/14 | [
"https://wordpress.stackexchange.com/questions/381520",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200368/"
] | When writting a description for a Woocoomerce Product and inserting a line break with **br** or **p** Tag, WordPress automatically removes it. This is really annoying because on some points, i want to have a little line break.
I often found the solution to install TinyMCE. After that now WordPress doesnt removes the **p** Tag anymore but inserts a ** ** inside of it and so the line break is way to big.
So i want a line break like a **p** Tag, because **npsb** produces way too much space between two sentence.
I also tried following solutions:
1. add some attributes to the p Tag like `<p data-x> </p>`
2. Wrap the p Tag with comments like
```
<!-- wp:html --> <p class="beer"></p> <!-- /wp:html -->
```
3. Added some hooks in the functions.php like
```
add_shortcode("br", "br_tag"); function br_tag(){ return("<br/>"); }
```
or
```
remove_filter('the_content', 'wpautop'); remove_filter('the_excerpt', 'wpautop');
```
and
```
remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); function wpse_wpautop_nobr( $content ) { return wpautop( $content, false ); } add_filter( 'the_content', 'wpse_wpautop_nobr' ); add_filter( 'the_excerpt', 'wpse_wpautop_nobr' );
```
4. I tried following solution but it doesnt work [Wordpress automatically adding " "?](https://wordpress.stackexchange.com/questions/29702/wordpress-automatically-adding-nbsp)
The "best" solution i found was to NOT using the visual AND the text editor, but for me thats such a temporary one.
Specs:
WordPress 5.6
Advanced Editor Tools (previously TinyMCE Advanced): 5.6
WooCommerce: 4.6.1 (but in my opinion, its not a WooCommerce problem)
Does anyone know a better solution or a reference for that problem? | Your site appears to be pretty well structured in most ways and you're getting a good score. If you're seeing a huge swing day to day, test to test, etc, then it's probably a hosting related issue. What type of hosting are you on? Is it cloud, is it shared, is it WordPress specific?
<https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.greenstuff.sk%2F&tab=desktop>
Google's PageSpeed Insights rates you at 93 for desktop - that's good. In fact, the only place it even throws a complaint is **Reduce Initial Server Response Time: 1.73s**. So what that tells me is that the inconsistent performance scores you are sometimes seeing are probably down to your hosting.
There's a few key things to remember when you're evaluating a site's performance, because there's really three different 'performance areas' that you need to consider.
1. There's your 'user perceived' speed; when you open the site in a new browser on a new computer or a new device and visit the URL directly for the first time, what's it load like for the end user in terms of what they see and what their experience is. This experience is super important.
2. Your page speed 'rating' - this isn't necessarily a direct indication of how fast the page loads, but rather a diagnostic check of how everything involved in generating a page is optimized and yes, Search Engines do consider these values.
3. Theres your 'actual page load' speed; as in how quickly the entire contents, code and assets of the page load.
If your Page Speed Rating is good and your user is seeing a full screen of useful content almost instantly, then it's ok if your site is still loading future needed assets and content. Obviously we want this to be as quick as possible but if what's loading last is a script that validates a MailChimp Subscribe form that pops up when a user clicks a button and only after the user has typed out their info, then it's not a huge worry if that script loads a half second later than the page is visible to the user.
You have to find a balance and ultimately test your site as a new user and measure the experience there first, then look at your Page Speed Rating and lastly look at your actual full load time, that's the order I address things in.
My recommendation, if you want consistency in performance and you want a really smooth running site is to avoid those plugins that promise better performance, automated minification, etc... ...I have seen the mess that can occur when those things go wrong and it isn't pretty. And those plugins also aren't a 'fix' for a slow or broken site. Those plugins, IF used, should be used to take a well built site that functions very well and then simply optimize what's already working. If your theme or a plugin are running really slow, laborious queries over and over again, there's no amount of minification or caching that's going to fix that.
So drop those plugins and get yourself onto a really good dedicated WordPress hosting platform, especially if you're running eCommerce. I like to use FlyWheel and then hook my site up to ManageWP for hourly back-ups when it comes to eCommerce sites so I always have all the sales data backed up. (Not linking to either one because that may be against the rules here.) |
381,544 | <p>I made custom plugin and done crud operation, display all data in admin page, used ajax and jquery. Data successfully deleted but not inserted or updated. Data successfully pass through ajax but not inserted.
Also What I saw if input block is empty and I put some data and updated it. It got first row data.<br>
Error- <a href="https://prnt.sc/wnzqjr" rel="nofollow noreferrer">https://prnt.sc/wnzqjr</a><br>
ajax for insert the data</p>
<pre><code>jQuery('.ins_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
// alert(id);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'insert_records',
insert_record : id,
insert_question: question,
insert_answer: answer
},
success: function( data ){
alert("Records are successfully insert");
location.reload();
}
});
});
</code></pre>
<p>insert query</p>
<pre><code> function insert_records(){
global $wpdb;
$id = $_POST['insert_record'];
$question = $_POST['insert_question'];
$answer = $_POST['insert_answer'];
$db_inserted = $wpdb->insert( $wpdb->prefix.'faqq',
array( 'ID' => $id,
'question' => $question,
'answer' => $answer)
);
}
add_action( "wp_ajax_insert_records", "insert_records" );
add_action( "wp_ajax_nopriv_insert_records", "insert_records" );
</code></pre>
<p>ajax for update the data</p>
<pre><code>jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
alert("Records are successfully updated");
location.reload();
}
});
});
</code></pre>
<p>update query</p>
<pre><code>function update_records(){
global $wpdb;
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer, array( 'ID' => $id ) )
);
}
</code></pre>
<p>this is html code</p>
<pre><code> <form method="POST" action="" >
<table>
<td><?php echo $print->id ?></td>
<td>
<input type="text" name="question" id="question" value="<?php echo $print->question ?>" ></td>
<td>
<input type="text" name="answer" id="answer" value="<?php echo $print->answer ?>" > </td>
<td>
<input type="button" value="Insert" id="insert" data-id = "<?php echo $print->id ?>" name="insert" class="ins_btn">
</td>
<td>
<input type="button" value="Update" id="update" data-id = "<?php echo $print->id ?>" name="update" class="upd_btn">
</td>
<td>
<input type="button" value="Delete" id="delete" data-id = "<?php echo $print->id ?>" name="delete" class="del_btn">
</td>
</table>
</form>
</code></pre>
<p>Here are some errors.
1)Getting error when update the data through ajax- <a href="https://prnt.sc/wnymkx" rel="nofollow noreferrer">https://prnt.sc/wnymkx</a>,
<a href="https://prnt.sc/wnyos5" rel="nofollow noreferrer">https://prnt.sc/wnyos5</a>, <a href="https://prnt.sc/wnyuhk" rel="nofollow noreferrer">https://prnt.sc/wnyuhk</a></p>
| [
{
"answer_id": 381554,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>I see that there's an <em>internal server error</em> (see <a href=\"https://prnt.sc/wnymkx\" rel=\"nofollow noreferrer\">screenshot</a>) when you tried to <em>update</em> a record in the database, and the error is likely because you <strong>incorrectly called <a href=\"https://developer.wordpress.org/reference/classes/wpdb/update/\" rel=\"nofollow noreferrer\"><code>$wpdb->update()</code></a></strong> which has the syntax of — and note that the first three parameters (<code>$table</code>, <code>$data</code> and <code>$where</code>) are <em>required</em>:</p>\n<p><code>wpdb::update( string $table, array $data, array $where, array|string $format = null, array|string $where_format = null )</code></p>\n<p>But in your code, you did not set the <strong>third parameter</strong> (<code>$where</code>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// In update_records():\n$db_updated = $wpdb->update( $wpdb->prefix.'faqq',\n array( 'question' => $question,\n 'answer' => $answer, array( 'ID' => $id ) )\n);\n</code></pre>\n<p>And I guess the <code>array( 'ID' => $id )</code> is the <code>$where</code> part, but you probably made a typo which resulted in that part being part of the second parameter instead.</p>\n<p>So fix that and your code would work properly. Example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$db_updated = $wpdb->update( $wpdb->prefix.'faqq',\n array( 'question' => $question,\n 'answer' => $answer,\n ),\n array( 'ID' => $id )\n);\n</code></pre>\n<p>As for your <code>insert_records()</code> function, it looks fine to me, so there shouldn't be an issue when inserting new records to your database table.</p>\n<p>Additionally, you should also (later) do things like data sanitization and call <code>wp_die()</code> to end the AJAX request, and fix the issue as seen <a href=\"https://prnt.sc/wnyuhk\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 381572,
"author": "vishal",
"author_id": 196459,
"author_profile": "https://wordpress.stackexchange.com/users/196459",
"pm_score": 0,
"selected": false,
"text": "<p>I did wrong code in ajax and jquery-\nfor update function in ajax and jQuery (Before)-</p>\n<pre><code>jQuery('.upd_btn').click(function(){\n var id = jQuery(this).attr('data-id');\n \n var question = jQuery('#question').val();\n var answer = jQuery('#answer').val();\n \n $.ajax({\n url: '<?php echo admin_url('admin-ajax.php');?>', \n type: 'POST',\n data:{ \n action: 'update_records', \n update_record : id,\n update_question : question,\n update_answer : answer\n\n },\n success: function( data ){\n // alert("Records are successfully updated");\n // location.reload();\n }\n });\n });\n</code></pre>\n<p>After<br>\nWhat I did wrong was I got the same id for question('#question') and answer('#answer') column. So I got the first row data for any row\nHere is the answer</p>\n<pre><code>jQuery('.upd_btn').click(function(){\n var id = jQuery(this).attr('data-id');\n \n var question = jQuery(this).closest('table').find('.question').val();\n var answer = jQuery(this).closest('table').find('.answer').val();\n \n $.ajax({\n url: '<?php echo admin_url('admin-ajax.php');?>', \n type: 'POST',\n data:{ \n action : 'update_records', \n update_record : id,\n update_question : question,\n update_answer : answer\n\n },\n success: function( data ){\n // alert("Records are successfully updated");\n \n }\n });\n });\n</code></pre>\n<p>So I changed id value and get class of each field and use closest function.</p>\n"
}
] | 2021/01/15 | [
"https://wordpress.stackexchange.com/questions/381544",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/196459/"
] | I made custom plugin and done crud operation, display all data in admin page, used ajax and jquery. Data successfully deleted but not inserted or updated. Data successfully pass through ajax but not inserted.
Also What I saw if input block is empty and I put some data and updated it. It got first row data.
Error- <https://prnt.sc/wnzqjr>
ajax for insert the data
```
jQuery('.ins_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
// alert(id);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'insert_records',
insert_record : id,
insert_question: question,
insert_answer: answer
},
success: function( data ){
alert("Records are successfully insert");
location.reload();
}
});
});
```
insert query
```
function insert_records(){
global $wpdb;
$id = $_POST['insert_record'];
$question = $_POST['insert_question'];
$answer = $_POST['insert_answer'];
$db_inserted = $wpdb->insert( $wpdb->prefix.'faqq',
array( 'ID' => $id,
'question' => $question,
'answer' => $answer)
);
}
add_action( "wp_ajax_insert_records", "insert_records" );
add_action( "wp_ajax_nopriv_insert_records", "insert_records" );
```
ajax for update the data
```
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
alert("Records are successfully updated");
location.reload();
}
});
});
```
update query
```
function update_records(){
global $wpdb;
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer, array( 'ID' => $id ) )
);
}
```
this is html code
```
<form method="POST" action="" >
<table>
<td><?php echo $print->id ?></td>
<td>
<input type="text" name="question" id="question" value="<?php echo $print->question ?>" ></td>
<td>
<input type="text" name="answer" id="answer" value="<?php echo $print->answer ?>" > </td>
<td>
<input type="button" value="Insert" id="insert" data-id = "<?php echo $print->id ?>" name="insert" class="ins_btn">
</td>
<td>
<input type="button" value="Update" id="update" data-id = "<?php echo $print->id ?>" name="update" class="upd_btn">
</td>
<td>
<input type="button" value="Delete" id="delete" data-id = "<?php echo $print->id ?>" name="delete" class="del_btn">
</td>
</table>
</form>
```
Here are some errors.
1)Getting error when update the data through ajax- <https://prnt.sc/wnymkx>,
<https://prnt.sc/wnyos5>, <https://prnt.sc/wnyuhk> | I see that there's an *internal server error* (see [screenshot](https://prnt.sc/wnymkx)) when you tried to *update* a record in the database, and the error is likely because you **incorrectly called [`$wpdb->update()`](https://developer.wordpress.org/reference/classes/wpdb/update/)** which has the syntax of — and note that the first three parameters (`$table`, `$data` and `$where`) are *required*:
`wpdb::update( string $table, array $data, array $where, array|string $format = null, array|string $where_format = null )`
But in your code, you did not set the **third parameter** (`$where`):
```php
// In update_records():
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array( 'question' => $question,
'answer' => $answer, array( 'ID' => $id ) )
);
```
And I guess the `array( 'ID' => $id )` is the `$where` part, but you probably made a typo which resulted in that part being part of the second parameter instead.
So fix that and your code would work properly. Example:
```php
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array( 'question' => $question,
'answer' => $answer,
),
array( 'ID' => $id )
);
```
As for your `insert_records()` function, it looks fine to me, so there shouldn't be an issue when inserting new records to your database table.
Additionally, you should also (later) do things like data sanitization and call `wp_die()` to end the AJAX request, and fix the issue as seen [here](https://prnt.sc/wnyuhk). |
381,553 | <p>how i can enable an specific css code for visitors and an specific user role</p>
<p>for example this code:</p>
<pre class="lang-css prettyprint-override"><code>input[type=radio] {
border: 1px solid !important;
}
</code></pre>
| [
{
"answer_id": 381566,
"author": "d3mi",
"author_id": 200408,
"author_profile": "https://wordpress.stackexchange.com/users/200408",
"pm_score": 0,
"selected": false,
"text": "<p>i tried this code in the functions.php for showing to the guests this css</p>\n<p>how is that possible</p>\n<pre><code>add_action('init', 'check_if_user_is_loggedin_function');\nfunction check_if_user_is_loggedin_function()\n{\n if ( is_user_logged_in() ) \n {\n} \n else {\n echo '<style>\n .woo-variation-swatches.wvs-style-squared .variable-items-wrapper .variable-item.button-variable-item-offen {\n display: none;\n }\n .woo-variation-swatches.wvs-style-squared .variable-items-wrapper .variable-item.color-variable-item-offen {\n display: none;\n }\n </style>';\n}\n}\n</code></pre>\n"
},
{
"answer_id": 381568,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>You can add custom css on your html header using wp_head hook action & checking your current User Role</p>\n<pre><code>add_action('wp_head', 'add_css_of_current_specific_user_role');\nfunction add_css_of_current_specific_user_role()\n{ \n /*Check Current User is Login*/\n if ( is_user_logged_in() ) \n { \n $user = wp_get_current_user();\n /*Check Current User Role*/\n if (in_array('visitor', $user->roles)) { ?>\n\n <style>\n // Some CSS\n </style>\n\n <?php } \n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 381571,
"author": "Yves Laurent",
"author_id": 200419,
"author_profile": "https://wordpress.stackexchange.com/users/200419",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to have specific CSS for visitors (aka not logged users) then you can take @HK89's code and tweak it a bit</p>\n<pre><code>add_action('wp_head', 'add_css_of_current_specific_user_role');\nfunction add_css_of_current_specific_user_role()\n{ \n /*Check if it's a visitor*/\n if ( !is_user_logged_in() ) \n { ?>\n <style>\n // Some CSS\n </style>\n <?php } \n\n }\n}\n</code></pre>\n"
}
] | 2021/01/15 | [
"https://wordpress.stackexchange.com/questions/381553",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200408/"
] | how i can enable an specific css code for visitors and an specific user role
for example this code:
```css
input[type=radio] {
border: 1px solid !important;
}
``` | You can add custom css on your html header using wp\_head hook action & checking your current User Role
```
add_action('wp_head', 'add_css_of_current_specific_user_role');
function add_css_of_current_specific_user_role()
{
/*Check Current User is Login*/
if ( is_user_logged_in() )
{
$user = wp_get_current_user();
/*Check Current User Role*/
if (in_array('visitor', $user->roles)) { ?>
<style>
// Some CSS
</style>
<?php }
}
}
``` |
381,855 | <p>I have migrated more than 50 websites from Live server to Localhost in my career but have not faced this issue till now.
I used ALL IN ONE WP MIGRATION to export the data from live server.
I replaced the url during export process.</p>
<pre><code>http://www.example.com/ to http://localhost/example/
</code></pre>
<p>I imported the data in my fresh wordpress installation in my localhost. Every thing went fine. My home page loads fine as well.
But when I click the home page logo which should redirect to http://localhost/example/ but redirects to http://localhost/dashboard of XAMPP.
When I click the menu item -> Services which should redirect to http://localhost/example/services but redirects to http://localhost/services.</p>
<p>I tried changing the Site Address Url and Wordpress Address Url to http://localhost/example/.</p>
<p>My .htaccess file.</p>
<pre><code># BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /example/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /example/index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 381671,
"author": "HenrijsS",
"author_id": 177555,
"author_profile": "https://wordpress.stackexchange.com/users/177555",
"pm_score": 1,
"selected": false,
"text": "<p>I just had a problem like this.</p>\n<p>Did you change the salts in wp-config by any chance?</p>\n<p>I changed them mid-production and the whole back-end just went haywire.</p>\n<p>If you have a snapshot of an older wp-config, try that!</p>\n"
},
{
"answer_id": 381698,
"author": "Eoin",
"author_id": 125706,
"author_profile": "https://wordpress.stackexchange.com/users/125706",
"pm_score": 0,
"selected": false,
"text": "<p>This was a file/folders permission problem</p>\n"
}
] | 2021/01/20 | [
"https://wordpress.stackexchange.com/questions/381855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102414/"
] | I have migrated more than 50 websites from Live server to Localhost in my career but have not faced this issue till now.
I used ALL IN ONE WP MIGRATION to export the data from live server.
I replaced the url during export process.
```
http://www.example.com/ to http://localhost/example/
```
I imported the data in my fresh wordpress installation in my localhost. Every thing went fine. My home page loads fine as well.
But when I click the home page logo which should redirect to http://localhost/example/ but redirects to http://localhost/dashboard of XAMPP.
When I click the menu item -> Services which should redirect to http://localhost/example/services but redirects to http://localhost/services.
I tried changing the Site Address Url and Wordpress Address Url to http://localhost/example/.
My .htaccess file.
```
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /example/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /example/index.php [L]
</IfModule>
# END WordPress
```
Any help is appreciated. | I just had a problem like this.
Did you change the salts in wp-config by any chance?
I changed them mid-production and the whole back-end just went haywire.
If you have a snapshot of an older wp-config, try that! |
381,872 | <p>I am trying to redirect users(subscribers) to a particular page based on the following conditions
<code>1. (subscriber) user is logged on 2. specific page id is matched 3. wp user role = subscriber</code> which is the default role set when a user is registered on the platform</p>
<p>The Challenge i am having is conditions 1 and 2 works but not 3.</p>
<p>Here is my code:</p>
<pre><code>function add_login_check()
{
if ( is_user_logged_in() && is_page(1865)) {
wp_redirect('http://destredirectedpage.php');
exit;
}
}
add_action('wp', 'add_login_check');
</code></pre>
<p>Interesting enough when i tested the above code using administrator role it works as expected but with subscriber role i get redirected automatically to the subscriber profile page upon logon.</p>
| [
{
"answer_id": 381873,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>We can check the <code>$request</code> which is passed to our <code>login_redirect</code> filter-function using <a href=\"https://developer.wordpress.org/reference/functions/url_to_postid/\" rel=\"nofollow noreferrer\">url_to_postid</a>.</p>\n<pre><code>// redirect subscribers if logging in from specific page\nfunction wpse381872_login_redirect( $redirect_to, $request, $user ) {\n\n // turn the request url into a post-id\n $request_id = url_to_postid( $request );\n\n if ( isset( $user->roles ) && is_array( $user->roles ) ) {\n // check for subscribers logging in via 1865\n if ( 1865 === request_id && in_array( 'subscriber', $user->roles ) ) {\n \n $redirect_to = 'http://destredirectedpage.php';\n \n }\n }\n\n return $redirect_to;\n}\n\nadd_filter( 'login_redirect', 'wpse381872_login_redirect', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 403194,
"author": "Gonçalo Peres",
"author_id": 117317,
"author_profile": "https://wordpress.stackexchange.com/users/117317",
"pm_score": 0,
"selected": false,
"text": "<p>Another work around is by using <a href=\"https://developer.wordpress.org/reference/functions/current_user_can/\" rel=\"nofollow noreferrer\"><code>current_user_can</code></a>, considering the permissions that a specific role has. Assuming that subscribers can edit posts, one can do the following</p>\n<pre><code>function add_login_check()\n{\n if (is_user_logged_in() && !current_user_can('edit_posts')) {\n if (is_page(1865)){\n wp_safe_redirect( get_permalink('447'));\n exit; \n }\n }\n}\n</code></pre>\n"
}
] | 2021/01/21 | [
"https://wordpress.stackexchange.com/questions/381872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180226/"
] | I am trying to redirect users(subscribers) to a particular page based on the following conditions
`1. (subscriber) user is logged on 2. specific page id is matched 3. wp user role = subscriber` which is the default role set when a user is registered on the platform
The Challenge i am having is conditions 1 and 2 works but not 3.
Here is my code:
```
function add_login_check()
{
if ( is_user_logged_in() && is_page(1865)) {
wp_redirect('http://destredirectedpage.php');
exit;
}
}
add_action('wp', 'add_login_check');
```
Interesting enough when i tested the above code using administrator role it works as expected but with subscriber role i get redirected automatically to the subscriber profile page upon logon. | We can check the `$request` which is passed to our `login_redirect` filter-function using [url\_to\_postid](https://developer.wordpress.org/reference/functions/url_to_postid/).
```
// redirect subscribers if logging in from specific page
function wpse381872_login_redirect( $redirect_to, $request, $user ) {
// turn the request url into a post-id
$request_id = url_to_postid( $request );
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
// check for subscribers logging in via 1865
if ( 1865 === request_id && in_array( 'subscriber', $user->roles ) ) {
$redirect_to = 'http://destredirectedpage.php';
}
}
return $redirect_to;
}
add_filter( 'login_redirect', 'wpse381872_login_redirect', 10, 3 );
``` |
381,875 | <p>WordPress end points default rules,</p>
<pre><code>GET ----> PUBLIC
POST, PUT, DELETE ----> AUTH
</code></pre>
<p>How can I force authentication the WordPress REST API <code>GET</code> method requests?</p>
| [
{
"answer_id": 381899,
"author": "Paul G.",
"author_id": 41288,
"author_profile": "https://wordpress.stackexchange.com/users/41288",
"pm_score": 2,
"selected": true,
"text": "<p>You can't really apply authentication based directly on whether the request is GET or otherwise, but can forcefully apply authentication requirements globally in that manner, if you like.</p>\n<p>I've been quite verbose with the code to illustrate what's happening:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_authentication_errors', function ( $error ) {\n\n /**\n * If it's a WP_Error, leave it as is. Authentication failed anyway\n *\n * If it's true, then authentication has already succeeded. Leave it as-is.\n */\n if ( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) === 'get' && !is_wp_error( $error ) && $error !== true ) {\n\n if ( !is_user_logged_in() ) {\n $error = new \\WP_Error( 'User not logged-in' );\n }\n \n }\n\n return $error;\n}, 11 );\n</code></pre>\n<p>Assumptions:</p>\n<ul>\n<li>PHP is at least version 5.3</li>\n<li>We're only testing <code>GET</code> requests</li>\n<li>If an authentication error has been met before this filter is executed, then we leave the error as-is.</li>\n<li>If there is no error, and in-fact it's set to <code>true</code>, then this means authentication has already succeeded and there's not need to block anything.</li>\n<li>We're only testing whether or not the user making the request is logged-in i.e. is authenticated with WordPress.</li>\n</ul>\n"
},
{
"answer_id": 391526,
"author": "Jürgen Fink",
"author_id": 208474,
"author_profile": "https://wordpress.stackexchange.com/users/208474",
"pm_score": 0,
"selected": false,
"text": "<p>Good Question and not that easy to do propperly (took me 1 week to figure that out).</p>\n<p>Then I found 2 good summaries in WordPress docs:<br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Routes and Endpoints</a><br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Adding Custom Endpoints</a></p>\n<p>There I found out how to use <strong>namespaces</strong>, <strong>routes</strong> and <strong>permission_callback</strong> correctly.</p>\n<p>Critical part was to add the <strong>Permission Callback</strong> into the <code>function.php</code> of your theme.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * This is our callback function to return (GET) our data.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction get_your_data($request) {\n global $wpdb;\n $yourdata = $wpdb->get_results("SELECT * FROM your_custom_table");\n\n return rest_ensure_response( $yourdata );\n};\n\n/**\n * This is our callback function to insert (POST) new data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction insert_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';\n\n if ($contentType === "application/json") {\n $content = trim(file_get_contents("php://input"));\n $decoded = json_decode($content, true);\n $newrecord = $wpdb->insert( 'your_custom_table', array( 'column_1' => $decoded['column_1'], 'column_2' => $decoded['column_2']));\n };\n if($newrecord){\n return rest_ensure_response($newrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header("Content-Type: application/json; charset=UTF-8");\n};\n/**\n * This is our callback function to update (PUT) a data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction update_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';\n\n if ($contentType === "application/json") {\n $content = trim(file_get_contents("php://input"));\n $decoded = json_decode($content, true);\n $updatedrecord = $wpdb->update( 'your_custom_table', array( 'column_1' => $decoded['column_1'], 'column_2' => $decoded['column_2']), array('id' => $decoded['id']), array( '%s' ));\n };\n\n if($updatedrecord){\n return rest_ensure_response($updatedrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header("Content-Type: application/json; charset=UTF-8");\n};\n\n// Permission Callback \n// 'ypp' is the Prefix I chose (ypp = Your Private Page)\n\nfunction ypp_get_private_data_permissions_check() {\n // Restrict endpoint to browsers that have the wp-postpass_ cookie.\n\n if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] )) {\n return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not create or edit private data.', 'my-text-domain' ), array( 'status' => 401 ) );\n };\n // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.\n return true;\n};\n\n// And then add the permission_callback to your POST and PUT routes:\n\nadd_action('rest_api_init', function() {\n /**\n * Register here your custom routes for your CRUD functions\n */\n register_rest_route( 'your_private_page/v1', '/data', array(\n array(\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => 'get_your_data',\n // Always allow.\n 'permission_callback' => '__return_true' // <-- you can protect GET as well if your like\n ),\n array(\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => 'insert_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' => 'ypp_get_private_data_permissions_check', // <-- that was the missing part\n ),\n array(\n 'methods' => WP_REST_Server::EDITABLE,\n 'callback' => 'update_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' => 'ypp_get_private_data_permissions_check', // <-- that was the missing part\n ),\n ));\n});\n</code></pre>\n<p>If you like, I posted a Question (similar issue to yours, but for custom routes) and then my findings in the answer.</p>\n<p><strong>Full story</strong> with complete code at:<br />\n<a href=\"https://wordpress.stackexchange.com/questions/391515/how-to-force-authentication-on-rest-api-for-password-protected-page-using-custom/391516#391516\">How to force Authentication on REST API for Password protected page using custom table and fetch() without Plugin</a></p>\n<p>Hope this helps a little.</p>\n"
}
] | 2021/01/21 | [
"https://wordpress.stackexchange.com/questions/381875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/198965/"
] | WordPress end points default rules,
```
GET ----> PUBLIC
POST, PUT, DELETE ----> AUTH
```
How can I force authentication the WordPress REST API `GET` method requests? | You can't really apply authentication based directly on whether the request is GET or otherwise, but can forcefully apply authentication requirements globally in that manner, if you like.
I've been quite verbose with the code to illustrate what's happening:
```php
add_filter( 'rest_authentication_errors', function ( $error ) {
/**
* If it's a WP_Error, leave it as is. Authentication failed anyway
*
* If it's true, then authentication has already succeeded. Leave it as-is.
*/
if ( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) === 'get' && !is_wp_error( $error ) && $error !== true ) {
if ( !is_user_logged_in() ) {
$error = new \WP_Error( 'User not logged-in' );
}
}
return $error;
}, 11 );
```
Assumptions:
* PHP is at least version 5.3
* We're only testing `GET` requests
* If an authentication error has been met before this filter is executed, then we leave the error as-is.
* If there is no error, and in-fact it's set to `true`, then this means authentication has already succeeded and there's not need to block anything.
* We're only testing whether or not the user making the request is logged-in i.e. is authenticated with WordPress. |
382,094 | <p>How can I print the taxonomy terms with links?? This code work but print the terms without link.. some advice??</p>
<pre class="lang-php prettyprint-override"><code>function show_all_terms($taxonomy){
$taxonomy_terms = get_terms($taxonomy);
foreach($taxonomy_terms as $term){
$terms[] = $term->name;
}
if(!empty($terms)) {
echo join(", ", $terms);
}
else{
echo "No ".$taxonomy."associated with this ".get_post_type();
}
}
</code></pre>
| [
{
"answer_id": 381899,
"author": "Paul G.",
"author_id": 41288,
"author_profile": "https://wordpress.stackexchange.com/users/41288",
"pm_score": 2,
"selected": true,
"text": "<p>You can't really apply authentication based directly on whether the request is GET or otherwise, but can forcefully apply authentication requirements globally in that manner, if you like.</p>\n<p>I've been quite verbose with the code to illustrate what's happening:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_authentication_errors', function ( $error ) {\n\n /**\n * If it's a WP_Error, leave it as is. Authentication failed anyway\n *\n * If it's true, then authentication has already succeeded. Leave it as-is.\n */\n if ( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) === 'get' && !is_wp_error( $error ) && $error !== true ) {\n\n if ( !is_user_logged_in() ) {\n $error = new \\WP_Error( 'User not logged-in' );\n }\n \n }\n\n return $error;\n}, 11 );\n</code></pre>\n<p>Assumptions:</p>\n<ul>\n<li>PHP is at least version 5.3</li>\n<li>We're only testing <code>GET</code> requests</li>\n<li>If an authentication error has been met before this filter is executed, then we leave the error as-is.</li>\n<li>If there is no error, and in-fact it's set to <code>true</code>, then this means authentication has already succeeded and there's not need to block anything.</li>\n<li>We're only testing whether or not the user making the request is logged-in i.e. is authenticated with WordPress.</li>\n</ul>\n"
},
{
"answer_id": 391526,
"author": "Jürgen Fink",
"author_id": 208474,
"author_profile": "https://wordpress.stackexchange.com/users/208474",
"pm_score": 0,
"selected": false,
"text": "<p>Good Question and not that easy to do propperly (took me 1 week to figure that out).</p>\n<p>Then I found 2 good summaries in WordPress docs:<br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Routes and Endpoints</a><br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Adding Custom Endpoints</a></p>\n<p>There I found out how to use <strong>namespaces</strong>, <strong>routes</strong> and <strong>permission_callback</strong> correctly.</p>\n<p>Critical part was to add the <strong>Permission Callback</strong> into the <code>function.php</code> of your theme.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * This is our callback function to return (GET) our data.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction get_your_data($request) {\n global $wpdb;\n $yourdata = $wpdb->get_results("SELECT * FROM your_custom_table");\n\n return rest_ensure_response( $yourdata );\n};\n\n/**\n * This is our callback function to insert (POST) new data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction insert_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';\n\n if ($contentType === "application/json") {\n $content = trim(file_get_contents("php://input"));\n $decoded = json_decode($content, true);\n $newrecord = $wpdb->insert( 'your_custom_table', array( 'column_1' => $decoded['column_1'], 'column_2' => $decoded['column_2']));\n };\n if($newrecord){\n return rest_ensure_response($newrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header("Content-Type: application/json; charset=UTF-8");\n};\n/**\n * This is our callback function to update (PUT) a data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction update_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';\n\n if ($contentType === "application/json") {\n $content = trim(file_get_contents("php://input"));\n $decoded = json_decode($content, true);\n $updatedrecord = $wpdb->update( 'your_custom_table', array( 'column_1' => $decoded['column_1'], 'column_2' => $decoded['column_2']), array('id' => $decoded['id']), array( '%s' ));\n };\n\n if($updatedrecord){\n return rest_ensure_response($updatedrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header("Content-Type: application/json; charset=UTF-8");\n};\n\n// Permission Callback \n// 'ypp' is the Prefix I chose (ypp = Your Private Page)\n\nfunction ypp_get_private_data_permissions_check() {\n // Restrict endpoint to browsers that have the wp-postpass_ cookie.\n\n if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] )) {\n return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not create or edit private data.', 'my-text-domain' ), array( 'status' => 401 ) );\n };\n // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.\n return true;\n};\n\n// And then add the permission_callback to your POST and PUT routes:\n\nadd_action('rest_api_init', function() {\n /**\n * Register here your custom routes for your CRUD functions\n */\n register_rest_route( 'your_private_page/v1', '/data', array(\n array(\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => 'get_your_data',\n // Always allow.\n 'permission_callback' => '__return_true' // <-- you can protect GET as well if your like\n ),\n array(\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => 'insert_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' => 'ypp_get_private_data_permissions_check', // <-- that was the missing part\n ),\n array(\n 'methods' => WP_REST_Server::EDITABLE,\n 'callback' => 'update_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' => 'ypp_get_private_data_permissions_check', // <-- that was the missing part\n ),\n ));\n});\n</code></pre>\n<p>If you like, I posted a Question (similar issue to yours, but for custom routes) and then my findings in the answer.</p>\n<p><strong>Full story</strong> with complete code at:<br />\n<a href=\"https://wordpress.stackexchange.com/questions/391515/how-to-force-authentication-on-rest-api-for-password-protected-page-using-custom/391516#391516\">How to force Authentication on REST API for Password protected page using custom table and fetch() without Plugin</a></p>\n<p>Hope this helps a little.</p>\n"
}
] | 2021/01/24 | [
"https://wordpress.stackexchange.com/questions/382094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200861/"
] | How can I print the taxonomy terms with links?? This code work but print the terms without link.. some advice??
```php
function show_all_terms($taxonomy){
$taxonomy_terms = get_terms($taxonomy);
foreach($taxonomy_terms as $term){
$terms[] = $term->name;
}
if(!empty($terms)) {
echo join(", ", $terms);
}
else{
echo "No ".$taxonomy."associated with this ".get_post_type();
}
}
``` | You can't really apply authentication based directly on whether the request is GET or otherwise, but can forcefully apply authentication requirements globally in that manner, if you like.
I've been quite verbose with the code to illustrate what's happening:
```php
add_filter( 'rest_authentication_errors', function ( $error ) {
/**
* If it's a WP_Error, leave it as is. Authentication failed anyway
*
* If it's true, then authentication has already succeeded. Leave it as-is.
*/
if ( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) === 'get' && !is_wp_error( $error ) && $error !== true ) {
if ( !is_user_logged_in() ) {
$error = new \WP_Error( 'User not logged-in' );
}
}
return $error;
}, 11 );
```
Assumptions:
* PHP is at least version 5.3
* We're only testing `GET` requests
* If an authentication error has been met before this filter is executed, then we leave the error as-is.
* If there is no error, and in-fact it's set to `true`, then this means authentication has already succeeded and there's not need to block anything.
* We're only testing whether or not the user making the request is logged-in i.e. is authenticated with WordPress. |
382,129 | <p>I'm trying to implement filter system in my website. I decided to make it via js. I created fetch function</p>
<pre><code>let filters = document.querySelectorAll('.filters-item');
let pageUrl = wp.page_url;
const postsContainer = document.querySelectorAll('.column.is-half.is-offset-1');
filters.forEach( (item) => {
item.addEventListener('change', (e) =>{
let url = pageUrl + '/wp-admin/admin-ajax.php';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=UTF-8',
},
body: JSON.stringify({
'test': "sampledatatest",
})
}).then( function (response) {
if(response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Error', error);
});
});
});
</code></pre>
<p>In my functions.php file I have simple function</p>
<pre><code>add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$t = $_POST['test'];
echo $t;
die();
}
</code></pre>
<p>When I click on <code>filter</code> item I'm getting error 400 in my dev console. What am I missing? Is it proper way to pass the data in the form like I did? I don't want to use jQuery.</p>
| [
{
"answer_id": 382140,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n<p>Is it proper way to pass the data in the form like I did?</p>\n</blockquote>\n<p>If you mean the <code>body</code> part (of your <code>fetch()</code> call), then yes, it is okay.</p>\n<p>However,</p>\n<ol>\n<li><p><strong>You must send a query named <code>action</code></strong> as part of the request (e.g. via the URL like <code>example.com/wp-admin/admin-ajax.php?action=test</code>), so that WordPress knows what AJAX action is it and then execute the callback(s) for that specific action.</p>\n<p>See <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#action\" rel=\"noreferrer\">here</a> for further information, but in your case, the AJAX action is <code>myfilter</code> as in <code>wp_ajax_myfilter</code> and the callback is <code>misha_filter_function()</code>.</p>\n</li>\n<li><p>The <code>Content-Type</code> header doesn't match the request body and you should've used <code>application/json</code> instead of <code>text/html</code>.</p>\n</li>\n</ol>\n<p>But then, even with the correct request body and headers, the <code>admin-ajax.php</code> doesn't actually support JSON request, so if you want to send JSON <em>request</em>, then you should use the WordPress REST API and you'd probably want to <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"noreferrer\">add a custom endpoint like <code>my-plugin/v1/myfilter</code></a>.</p>\n<p>Otherwise, and if you prefer using the <code>admin-ajax.php</code>, then for example, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData\" rel=\"noreferrer\"><code>FormData()</code> API in JavaScript</a> to properly build the form data to be sent to <code>admin-ajax.php</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var formData = new FormData();\n\nformData.append( 'action', 'myfilter' );\nformData.append( 'test', 'foo bar baz' );\n\nfetch( url, {\n method: 'POST',\n body: formData,\n} ) // wrapped\n .then( res => res.text() )\n .then( data => console.log( data ) )\n .catch( err => console.log( err ) );\n</code></pre>\n"
},
{
"answer_id": 412346,
"author": "javmah",
"author_id": 147579,
"author_profile": "https://wordpress.stackexchange.com/users/147579",
"pm_score": 0,
"selected": false,
"text": "<p>I think below is the most convenient way to initiate an ajax request via javascript fetch API. Creating WordPress ajax requests without jQuery.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// PHP WP ajax hook\nadd_action('wp_ajax_ajaxCallback', 'ajaxCallback'); \n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>// Creating data \nlet requestData = {\n action: "ajaxCallback",\n myData: "Your data",\n nonce: 'test nonce'\n};\n \n// Initiating AJAX request \nfetch('http://example.com/wp-admin/admin-ajax.php', {\n method:"post",\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(requestData).toString(),\n}).then(function(response) {\n // return response.json(); // if responce is in json.\n return response.text();\n}).then(function(response) {\n console.log(response);\n});\n</code></pre>\n"
}
] | 2021/01/25 | [
"https://wordpress.stackexchange.com/questions/382129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147198/"
] | I'm trying to implement filter system in my website. I decided to make it via js. I created fetch function
```
let filters = document.querySelectorAll('.filters-item');
let pageUrl = wp.page_url;
const postsContainer = document.querySelectorAll('.column.is-half.is-offset-1');
filters.forEach( (item) => {
item.addEventListener('change', (e) =>{
let url = pageUrl + '/wp-admin/admin-ajax.php';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=UTF-8',
},
body: JSON.stringify({
'test': "sampledatatest",
})
}).then( function (response) {
if(response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Error', error);
});
});
});
```
In my functions.php file I have simple function
```
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$t = $_POST['test'];
echo $t;
die();
}
```
When I click on `filter` item I'm getting error 400 in my dev console. What am I missing? Is it proper way to pass the data in the form like I did? I don't want to use jQuery. | >
> Is it proper way to pass the data in the form like I did?
>
>
>
If you mean the `body` part (of your `fetch()` call), then yes, it is okay.
However,
1. **You must send a query named `action`** as part of the request (e.g. via the URL like `example.com/wp-admin/admin-ajax.php?action=test`), so that WordPress knows what AJAX action is it and then execute the callback(s) for that specific action.
See [here](https://developer.wordpress.org/plugins/javascript/ajax/#action) for further information, but in your case, the AJAX action is `myfilter` as in `wp_ajax_myfilter` and the callback is `misha_filter_function()`.
2. The `Content-Type` header doesn't match the request body and you should've used `application/json` instead of `text/html`.
But then, even with the correct request body and headers, the `admin-ajax.php` doesn't actually support JSON request, so if you want to send JSON *request*, then you should use the WordPress REST API and you'd probably want to [add a custom endpoint like `my-plugin/v1/myfilter`](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).
Otherwise, and if you prefer using the `admin-ajax.php`, then for example, you can use the [`FormData()` API in JavaScript](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) to properly build the form data to be sent to `admin-ajax.php`:
```js
var formData = new FormData();
formData.append( 'action', 'myfilter' );
formData.append( 'test', 'foo bar baz' );
fetch( url, {
method: 'POST',
body: formData,
} ) // wrapped
.then( res => res.text() )
.then( data => console.log( data ) )
.catch( err => console.log( err ) );
``` |
382,130 | <p>I have this working statement for searching a single column in my database:</p>
<pre><code>$foods = $wpdb->get_results( $wpdb->prepare( "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %s", "%$search_text%"), ARRAY_A );
</code></pre>
<p>I would like to include another column in the search called "foodname" but I can't seem to figure out the correct syntax.</p>
<p>How should I formulate my prepare statement so that I'm searching "namevariations" OR "foodname" and a match in either column will select that row?</p>
| [
{
"answer_id": 383572,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>The part after <code>WHERE</code> decides which columns are searched.</p>\n<p>So you need to change it this way:</p>\n<pre><code>$foods = $wpdb->get_results(\n $wpdb->prepare(\n "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %1$s OR foodname like %1$s",\n '%' . $wpdb->esc_like( $search_text ) . '%'\n ),\n ARRAY_A\n);\n</code></pre>\n<p>Also you were using LIKE queries incorrectly. If the <code>$search_text</code> contained <code>%</code> character, it would be interpreted as wildcard and not as simple character. That's why I've added some escaping in your code. More on this topic here: <a href=\"https://wordpress.stackexchange.com/questions/8825/how-do-you-properly-prepare-a-like-sql-statement\">How do you properly prepare a %LIKE% SQL statement?</a></p>\n"
},
{
"answer_id": 386104,
"author": "Andy Bay",
"author_id": 200346,
"author_profile": "https://wordpress.stackexchange.com/users/200346",
"pm_score": 0,
"selected": false,
"text": "<p>Got it to work like this:</p>\n<pre><code>$recipes = $wpdb->get_results($wpdb->prepare("SELECT * FROM recipestable WHERE ( recipetags LIKE '%%%s%%' or recipename LIKE '%%%s%%' )", $like, $like ), ARRAY_A )\n</code></pre>\n"
}
] | 2021/01/25 | [
"https://wordpress.stackexchange.com/questions/382130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200346/"
] | I have this working statement for searching a single column in my database:
```
$foods = $wpdb->get_results( $wpdb->prepare( "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %s", "%$search_text%"), ARRAY_A );
```
I would like to include another column in the search called "foodname" but I can't seem to figure out the correct syntax.
How should I formulate my prepare statement so that I'm searching "namevariations" OR "foodname" and a match in either column will select that row? | The part after `WHERE` decides which columns are searched.
So you need to change it this way:
```
$foods = $wpdb->get_results(
$wpdb->prepare(
"SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %1$s OR foodname like %1$s",
'%' . $wpdb->esc_like( $search_text ) . '%'
),
ARRAY_A
);
```
Also you were using LIKE queries incorrectly. If the `$search_text` contained `%` character, it would be interpreted as wildcard and not as simple character. That's why I've added some escaping in your code. More on this topic here: [How do you properly prepare a %LIKE% SQL statement?](https://wordpress.stackexchange.com/questions/8825/how-do-you-properly-prepare-a-like-sql-statement) |
382,138 | <br>
I'm trying to reduce the overloading by not to load all style sheets on my website's homepage. <br>
Some of those sheets is coming and loading from external plugins like woo-commerce, <br>
I have tried to do that using `wp_dequeue_style` function, but it haven't worked, those style sheets still being loaded! <br><br>
For example, the first one is 100% not used: <br><br>
<p><a href="https://i.stack.imgur.com/wXUOl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wXUOl.png" alt="This style sheet coming from woo-commerce" /></a></p>
<p><br>When I use the code below: <br></p>
<pre><code>function disable_plugins_style()
{
global $wp_styles;
wp_dequeue_style('style-rtl');
wp_deregister_style('style-rtl');
unset($wp_styles->registered['style-rtl']);
}
add_action('wp_enqueue_scripts', 'disable_plugins_style', 9999);
add_action('wp_head', 'disable_plugins_style', 9999);
</code></pre>
<p>It didn't cause any affect, could I find someone can help me please.</p>
| [
{
"answer_id": 382157,
"author": "Celso Bessa",
"author_id": 22694,
"author_profile": "https://wordpress.stackexchange.com/users/22694",
"pm_score": 2,
"selected": false,
"text": "<p>Your basic strategy is correct. The problem is that, although there are some best practices, you can't never know for sure in a easy way, 100% of time:</p>\n<ol>\n<li>when a plugin or theme will enqueue scripts and styles;</li>\n<li>what priority is used to enqueue</li>\n<li>if a plugin or theme really used enqueue/register hooks or hard-coded.</li>\n</ol>\n<p>That said, you might want to a) <strong>hook your code to different actions when the scripts and styles are printed</strong> (<em>and not enqueued</em>) and test different priorities. Or b) you could check each plugin and theme code and see what hook and priority are used to each <code>wp_enqueue_script</code> or <code>wp_enqueue_style</code> call.</p>\n<p>I would suggest going with option a, something like this:</p>\n<pre><code> function wpse_382138_disable_plugins_style()\n {\n //these should use the same priority of later than the priority used by the plugin or theme when hooked\n wp_dequeue_style('stylesheet-handler-with-default-priority');\n wp_dequeue_style('stylesheet-handler-with-explicit-default-priorit', 10);\n wp_dequeue_style('stylesheet-handler-with-later-priority', 20);\n }\n function wpse_382138_disable_plugins_scripts()\n {\n // these should use the same priority of later than the priority used by the plugin or theme when hooked\n wp_dequeue_script('script-handler-with-default-priority');\n wp_dequeue_script('script-handler-with-explicit-default-priority', 10);\n wp_dequeue_script('script-handler-with-later-priority', 20);\n }\n\n // option A: hook your unhooking functions either to hooks later than wp_enqueue_scripts or wp_enqueue_style as wp_head or wp_footer.\n add_action('wp_head', 'wpse_382138_disable_plugins_style', 10);\n add_action('wp_footer', 'wpse_382138_disable_plugins_style', 10);\n add_action('wp_head', 'wpse_382138_disable_plugins_scripts', 10);\n add_action('wp_footer', 'wpse_382138_disable_plugins_scripts', 10);\n\n // option b: hook your unhooking functions to the printing actions with a priority lower than the before first scripts or styles are usuarlly written, so they will execute the dequeue before scripts and styles are printed.\n add_action('wp_print_scripts', 'wpse_382138_disable_plugins_style', 5);\n add_action('wp_print_footer_scripts', 'wpse_382138_disable_plugins_style', 5);\n add_action('wp_print_styles', 'wpse_382138_isable_plugins_scrips', 5);\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">This Codex page</a> has a list of almost all hooks triggered in a typical WordPress Request.</p>\n<p>Let me know if it helped you.</p>\n"
},
{
"answer_id": 382158,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 2,
"selected": false,
"text": "<p>You're on the right track, but you need to know the stylesheet's ID. It's not necessarily the same as the stylesheet's filename.</p>\n<p>Check the generated source of your page (ie, load the page up in a browser and View Source). Find the <code><link></code> tag that's loading the stylesheet. If it's been properly enqueued for WordPress, it should look something like:</p>\n<pre><code><link\n rel="stylesheet"\n id="your-stylesheet-id-css"\n href="https://example.com/path/to/your-stylesheet.css"\n/>\n</code></pre>\n<p>You need to take the value in the <code>id</code> attribute and trim the <code>-css</code> from the end.</p>\n<p>So, in my example, you'd need:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_382138_unload_css', 9999 );\nfunction wpse_382138_unload_css() {\n wp_dequeue_style( 'your-stylesheet-id' );\n}\n</code></pre>\n<p>...changing <code>your-stylesheet-id</code> to the value you find in your page's generated source code.</p>\n<h2>References</h2>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_style/\" rel=\"nofollow noreferrer\"><code>wp_dequeue_style()</code></a></li>\n</ul>\n"
},
{
"answer_id": 409135,
"author": "Serhat Ozaydin",
"author_id": 212581,
"author_profile": "https://wordpress.stackexchange.com/users/212581",
"pm_score": 0,
"selected": false,
"text": "<p>Adding wp_deregister_style to the function may also help: (<a href=\"https://wordpress.stackexchange.com/questions/382138/how-to-dequeue-styles-coming-from-plugins#answer-382158\">Tweak to Pat J's code</a>)</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_382138_unload_css', 9999 );\nfunction wpse_382138_unload_css() {\n wp_dequeue_style( 'your-stylesheet-id' );\n wp_deregister_style( 'your-stylesheet-id' );\n}\n</code></pre>\n"
}
] | 2021/01/25 | [
"https://wordpress.stackexchange.com/questions/382138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/199583/"
] | I'm trying to reduce the overloading by not to load all style sheets on my website's homepage.
Some of those sheets is coming and loading from external plugins like woo-commerce,
I have tried to do that using `wp\_dequeue\_style` function, but it haven't worked, those style sheets still being loaded!
For example, the first one is 100% not used:
[](https://i.stack.imgur.com/wXUOl.png)
When I use the code below:
```
function disable_plugins_style()
{
global $wp_styles;
wp_dequeue_style('style-rtl');
wp_deregister_style('style-rtl');
unset($wp_styles->registered['style-rtl']);
}
add_action('wp_enqueue_scripts', 'disable_plugins_style', 9999);
add_action('wp_head', 'disable_plugins_style', 9999);
```
It didn't cause any affect, could I find someone can help me please. | Your basic strategy is correct. The problem is that, although there are some best practices, you can't never know for sure in a easy way, 100% of time:
1. when a plugin or theme will enqueue scripts and styles;
2. what priority is used to enqueue
3. if a plugin or theme really used enqueue/register hooks or hard-coded.
That said, you might want to a) **hook your code to different actions when the scripts and styles are printed** (*and not enqueued*) and test different priorities. Or b) you could check each plugin and theme code and see what hook and priority are used to each `wp_enqueue_script` or `wp_enqueue_style` call.
I would suggest going with option a, something like this:
```
function wpse_382138_disable_plugins_style()
{
//these should use the same priority of later than the priority used by the plugin or theme when hooked
wp_dequeue_style('stylesheet-handler-with-default-priority');
wp_dequeue_style('stylesheet-handler-with-explicit-default-priorit', 10);
wp_dequeue_style('stylesheet-handler-with-later-priority', 20);
}
function wpse_382138_disable_plugins_scripts()
{
// these should use the same priority of later than the priority used by the plugin or theme when hooked
wp_dequeue_script('script-handler-with-default-priority');
wp_dequeue_script('script-handler-with-explicit-default-priority', 10);
wp_dequeue_script('script-handler-with-later-priority', 20);
}
// option A: hook your unhooking functions either to hooks later than wp_enqueue_scripts or wp_enqueue_style as wp_head or wp_footer.
add_action('wp_head', 'wpse_382138_disable_plugins_style', 10);
add_action('wp_footer', 'wpse_382138_disable_plugins_style', 10);
add_action('wp_head', 'wpse_382138_disable_plugins_scripts', 10);
add_action('wp_footer', 'wpse_382138_disable_plugins_scripts', 10);
// option b: hook your unhooking functions to the printing actions with a priority lower than the before first scripts or styles are usuarlly written, so they will execute the dequeue before scripts and styles are printed.
add_action('wp_print_scripts', 'wpse_382138_disable_plugins_style', 5);
add_action('wp_print_footer_scripts', 'wpse_382138_disable_plugins_style', 5);
add_action('wp_print_styles', 'wpse_382138_isable_plugins_scrips', 5);
```
[This Codex page](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) has a list of almost all hooks triggered in a typical WordPress Request.
Let me know if it helped you. |
382,173 | <p>For the purpose of transferring a very large number of user responses from non-WordPress to WordPress comments, I've been given a Google Sheet. Regardless of the method by which I turn the Sheet into a CSV file (direct download as CSV, download as xlsx then save as csv, copy-paste into Excel and save), I get some version of the same problem, though with marginally varying results.</p>
<ol>
<li><p>If processed as saved, comments with slanted apostrophes/curled single quotes - <code>’</code> - are simply not inserted - they do not appear either in backend comments.php or in the post output.</p>
</li>
<li><p>If I use esc_html() on the comment content, the comments will be processed - are will be listed in the backend and in post output - but the comment content <strong>will be emptied</strong>.</p>
</li>
<li><p>I've tried some other means to change the comment content programmatically, like str_replace-ing <code>’</code> with <code>'</code>, but I haven't had any luck with that: The affected comments are still rejected.</p>
</li>
<li><p>Other shots in the dark investigated so for, like disabling wp_texturize() via filter function, have no effect.</p>
</li>
</ol>
<p><strong>The one method that has worked so far has been to run a straight character replace - <code>’</code> with <code>'</code> - in the data files before saving as CSV and uploading</strong>. That's sub-optimal for large files that will in the future need to be updated continually, and I can't shake the feeling that there <em>should</em> be a possibly very simple programmatic solution.</p>
<p>First, here's the relevant portion of the code I'm using for the function, which I'm running via shortcode, up to the point where comment_data is initially set. FYI the post_id is added later. (Per request, I'll add more of the code - which also inserts posts and categories, at the end.)</p>
<pre><code> $new_array = array() ;
if ( ( $handle = fopen( __DIR__ . "/sample_data.csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle ) ) !== FALSE ) {
$new_array[] = $data ;
}
fclose( $handle ) ;
}
foreach( $new_array as $insert_array ) {
$comment_data = array(
'comment_author' => $insert_array[0] ,
'comment_content' => $insert_array[4] , //a string, see notes
'comment_date' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_date_gmt' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
) ;
}
</code></pre>
<p>To re-state the issue: If I don't make any other changes, then the implicated entries simply do not get added at all, while the rest of the file/rows are completed, and entries that use straight quotes are included in the output, as expected.</p>
<p>FOR CLARIFICATION, RE QUESTIONS/REQUESTS</p>
<p>Each row is extracted from the csv file as an array, with each cell as a value. The highlighted cells below are two typical comment content cells - extracted as successive <code>$insert_array[4]</code>'s. The first one transfers/outputs just fine. The second one, with a slanty single quote in the second sentence produces the issues I've described. Cells with straight quotes transfer fine.</p>
<p><a href="https://i.stack.imgur.com/JfMc1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JfMc1.png" alt="Leveriza Abu Dhabi NONE United Arab Emirates Abu Dhabi is one of the safest cities in the world. It is the capital of a developed country, which is the United Arab Emirates. The people/locals have a deep respect for their religion and culture herein. Abu Dhabi is a great place to visit or to reside for employment purposes. 8/5/2020 6:49:25 413912 Abu Dhabi, United Arab Emirates
Malak Abu Dhabi NONE United Arab Emirates Abu Dhabi is the capital of the UAE. It’s a very diverse city with a lot of beautiful places. It’s one of the wealthiest cities in the country, so it’s considered an expensive city. Compared to Dubai, it’s a more traditional city that has a lot to offer in terms of luxury. 8/8/2020 16:57:23 415450 Abu Dhabi, United Arab Emirates" /></a></p>
<p>Full code:</p>
<pre><code>
add_shortcode( 'insert_from_db_file', 'insert_from_db_file_handler' ) ;
function insert_from_db_file_handler( $atts ) {
require_once( ABSPATH . '/wp-admin/includes/taxonomy.php');
$a = shortcode_atts( array(
'test'=> 'on',
), $atts ) ;
$new_array = array() ;
if ( ( $handle = fopen( __DIR__ . "/sample_data.csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle ) ) !== FALSE ) {
$new_array[] = $data ;
}
fclose( $handle ) ;
}
$i = 0 ;
foreach( $new_array as $insert_array ) {
$cats = array() ;
$state_id = $country_id = $state = $country = $post_id = '' ;
$i++ ;
if ( 'on' == $a['test'] && $i > 300 ) {
break ;
}
$comment_data = array(
'comment_author' => $insert_array[0] ,
'comment_content' => $insert_array[4] ,
'comment_date' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_date_gmt' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_post_id' => '',
'comment_meta' => array(
'db_row' => $insert_array[6],
'standardized_location' => $insert_array[7],
),
) ;
if ( ! get_page_by_title( $insert_array[1], OBJECT, 'city' ) ) { // don't create new post if already exists
//create city categories
$country = 'NONE' == $insert_array[3] ? '' : ucfirst( $insert_array[3] ) ;
$state = 'NONE' == $insert_array[2] ? '' : ucfirst( $insert_array[2] ) ; //some lowercase in db
$country_id = wp_create_category( $country ) ;
$cats[] = $country_id ;
if ( $state ) {
$state_id = wp_create_category( $state, $country_id ) ;
$cats[] = $state_id ;
}
//create post
$post_arr = array(
'post_title' => ucfirst( $insert_array[1] ), //lowercase in some data
'post_content' => $insert_array[1],
'post_status' => 'publish',
'post_author' => 3,
'comment_status' => 'closed',
'post_category' => $cats,
'post_type' => 'city'
) ;
$post_id = wp_insert_post( $post_arr ) ;
$args = array(
'post_id' => $post_id,
'count' => true,
) ;
$previous_comment = get_comments( $args ) ;
$comment_data['comment_post_ID'] = $post_id ;
//add unique comments only
if ( ! $previous_comment ) {
$comment = wp_insert_comment( $comment_data ) ;
if ( ! $comment ) {
custom_logs( 'FALSE FOR ' . $i ) ;
custom_logs( print_r( $insert_array, true ) ) ;
}
}
$cities[] = $insert_array[1] ;
} else { //find city for comments
$db_rows = array() ; // don't accumulate gigantic db_rows?
$id = get_page_by_title( $insert_array[1], OBJECT, 'city' )->ID ;
$args = array(
'post_id' => $id,
) ;
$previous_comments = get_comments( $args ) ;
foreach ( $previous_comments as $previous_comment ) {
$db_rows[] = get_comment_meta( $previous_comment->comment_ID, 'db_row', true ) ;
}
if ( $previous_comments && ! in_array( $insert_array[6], $db_rows ) ) {
$comment_data['comment_post_ID'] = $id ;
$comment = wp_insert_comment( $comment_data ) ;
if ( ! $comment ) {
custom_logs( 'FALSE FOR ' . $i ) ; //"custom_logs( $message )" is a utility function for debugging
custom_logs( print_r( $insert_array, true ) ) ;
}
}
}
}
return $i . 'COMMENTS INSERTED' ;
}
</code></pre>
| [
{
"answer_id": 382157,
"author": "Celso Bessa",
"author_id": 22694,
"author_profile": "https://wordpress.stackexchange.com/users/22694",
"pm_score": 2,
"selected": false,
"text": "<p>Your basic strategy is correct. The problem is that, although there are some best practices, you can't never know for sure in a easy way, 100% of time:</p>\n<ol>\n<li>when a plugin or theme will enqueue scripts and styles;</li>\n<li>what priority is used to enqueue</li>\n<li>if a plugin or theme really used enqueue/register hooks or hard-coded.</li>\n</ol>\n<p>That said, you might want to a) <strong>hook your code to different actions when the scripts and styles are printed</strong> (<em>and not enqueued</em>) and test different priorities. Or b) you could check each plugin and theme code and see what hook and priority are used to each <code>wp_enqueue_script</code> or <code>wp_enqueue_style</code> call.</p>\n<p>I would suggest going with option a, something like this:</p>\n<pre><code> function wpse_382138_disable_plugins_style()\n {\n //these should use the same priority of later than the priority used by the plugin or theme when hooked\n wp_dequeue_style('stylesheet-handler-with-default-priority');\n wp_dequeue_style('stylesheet-handler-with-explicit-default-priorit', 10);\n wp_dequeue_style('stylesheet-handler-with-later-priority', 20);\n }\n function wpse_382138_disable_plugins_scripts()\n {\n // these should use the same priority of later than the priority used by the plugin or theme when hooked\n wp_dequeue_script('script-handler-with-default-priority');\n wp_dequeue_script('script-handler-with-explicit-default-priority', 10);\n wp_dequeue_script('script-handler-with-later-priority', 20);\n }\n\n // option A: hook your unhooking functions either to hooks later than wp_enqueue_scripts or wp_enqueue_style as wp_head or wp_footer.\n add_action('wp_head', 'wpse_382138_disable_plugins_style', 10);\n add_action('wp_footer', 'wpse_382138_disable_plugins_style', 10);\n add_action('wp_head', 'wpse_382138_disable_plugins_scripts', 10);\n add_action('wp_footer', 'wpse_382138_disable_plugins_scripts', 10);\n\n // option b: hook your unhooking functions to the printing actions with a priority lower than the before first scripts or styles are usuarlly written, so they will execute the dequeue before scripts and styles are printed.\n add_action('wp_print_scripts', 'wpse_382138_disable_plugins_style', 5);\n add_action('wp_print_footer_scripts', 'wpse_382138_disable_plugins_style', 5);\n add_action('wp_print_styles', 'wpse_382138_isable_plugins_scrips', 5);\n</code></pre>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">This Codex page</a> has a list of almost all hooks triggered in a typical WordPress Request.</p>\n<p>Let me know if it helped you.</p>\n"
},
{
"answer_id": 382158,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 2,
"selected": false,
"text": "<p>You're on the right track, but you need to know the stylesheet's ID. It's not necessarily the same as the stylesheet's filename.</p>\n<p>Check the generated source of your page (ie, load the page up in a browser and View Source). Find the <code><link></code> tag that's loading the stylesheet. If it's been properly enqueued for WordPress, it should look something like:</p>\n<pre><code><link\n rel="stylesheet"\n id="your-stylesheet-id-css"\n href="https://example.com/path/to/your-stylesheet.css"\n/>\n</code></pre>\n<p>You need to take the value in the <code>id</code> attribute and trim the <code>-css</code> from the end.</p>\n<p>So, in my example, you'd need:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_382138_unload_css', 9999 );\nfunction wpse_382138_unload_css() {\n wp_dequeue_style( 'your-stylesheet-id' );\n}\n</code></pre>\n<p>...changing <code>your-stylesheet-id</code> to the value you find in your page's generated source code.</p>\n<h2>References</h2>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_style/\" rel=\"nofollow noreferrer\"><code>wp_dequeue_style()</code></a></li>\n</ul>\n"
},
{
"answer_id": 409135,
"author": "Serhat Ozaydin",
"author_id": 212581,
"author_profile": "https://wordpress.stackexchange.com/users/212581",
"pm_score": 0,
"selected": false,
"text": "<p>Adding wp_deregister_style to the function may also help: (<a href=\"https://wordpress.stackexchange.com/questions/382138/how-to-dequeue-styles-coming-from-plugins#answer-382158\">Tweak to Pat J's code</a>)</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_382138_unload_css', 9999 );\nfunction wpse_382138_unload_css() {\n wp_dequeue_style( 'your-stylesheet-id' );\n wp_deregister_style( 'your-stylesheet-id' );\n}\n</code></pre>\n"
}
] | 2021/01/25 | [
"https://wordpress.stackexchange.com/questions/382173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35923/"
] | For the purpose of transferring a very large number of user responses from non-WordPress to WordPress comments, I've been given a Google Sheet. Regardless of the method by which I turn the Sheet into a CSV file (direct download as CSV, download as xlsx then save as csv, copy-paste into Excel and save), I get some version of the same problem, though with marginally varying results.
1. If processed as saved, comments with slanted apostrophes/curled single quotes - `’` - are simply not inserted - they do not appear either in backend comments.php or in the post output.
2. If I use esc\_html() on the comment content, the comments will be processed - are will be listed in the backend and in post output - but the comment content **will be emptied**.
3. I've tried some other means to change the comment content programmatically, like str\_replace-ing `’` with `'`, but I haven't had any luck with that: The affected comments are still rejected.
4. Other shots in the dark investigated so for, like disabling wp\_texturize() via filter function, have no effect.
**The one method that has worked so far has been to run a straight character replace - `’` with `'` - in the data files before saving as CSV and uploading**. That's sub-optimal for large files that will in the future need to be updated continually, and I can't shake the feeling that there *should* be a possibly very simple programmatic solution.
First, here's the relevant portion of the code I'm using for the function, which I'm running via shortcode, up to the point where comment\_data is initially set. FYI the post\_id is added later. (Per request, I'll add more of the code - which also inserts posts and categories, at the end.)
```
$new_array = array() ;
if ( ( $handle = fopen( __DIR__ . "/sample_data.csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle ) ) !== FALSE ) {
$new_array[] = $data ;
}
fclose( $handle ) ;
}
foreach( $new_array as $insert_array ) {
$comment_data = array(
'comment_author' => $insert_array[0] ,
'comment_content' => $insert_array[4] , //a string, see notes
'comment_date' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_date_gmt' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
) ;
}
```
To re-state the issue: If I don't make any other changes, then the implicated entries simply do not get added at all, while the rest of the file/rows are completed, and entries that use straight quotes are included in the output, as expected.
FOR CLARIFICATION, RE QUESTIONS/REQUESTS
Each row is extracted from the csv file as an array, with each cell as a value. The highlighted cells below are two typical comment content cells - extracted as successive `$insert_array[4]`'s. The first one transfers/outputs just fine. The second one, with a slanty single quote in the second sentence produces the issues I've described. Cells with straight quotes transfer fine.
[](https://i.stack.imgur.com/JfMc1.png)
Full code:
```
add_shortcode( 'insert_from_db_file', 'insert_from_db_file_handler' ) ;
function insert_from_db_file_handler( $atts ) {
require_once( ABSPATH . '/wp-admin/includes/taxonomy.php');
$a = shortcode_atts( array(
'test'=> 'on',
), $atts ) ;
$new_array = array() ;
if ( ( $handle = fopen( __DIR__ . "/sample_data.csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle ) ) !== FALSE ) {
$new_array[] = $data ;
}
fclose( $handle ) ;
}
$i = 0 ;
foreach( $new_array as $insert_array ) {
$cats = array() ;
$state_id = $country_id = $state = $country = $post_id = '' ;
$i++ ;
if ( 'on' == $a['test'] && $i > 300 ) {
break ;
}
$comment_data = array(
'comment_author' => $insert_array[0] ,
'comment_content' => $insert_array[4] ,
'comment_date' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_date_gmt' => date( 'Y-m-d H:i:s', strtotime( $insert_array[5] ) ),
'comment_post_id' => '',
'comment_meta' => array(
'db_row' => $insert_array[6],
'standardized_location' => $insert_array[7],
),
) ;
if ( ! get_page_by_title( $insert_array[1], OBJECT, 'city' ) ) { // don't create new post if already exists
//create city categories
$country = 'NONE' == $insert_array[3] ? '' : ucfirst( $insert_array[3] ) ;
$state = 'NONE' == $insert_array[2] ? '' : ucfirst( $insert_array[2] ) ; //some lowercase in db
$country_id = wp_create_category( $country ) ;
$cats[] = $country_id ;
if ( $state ) {
$state_id = wp_create_category( $state, $country_id ) ;
$cats[] = $state_id ;
}
//create post
$post_arr = array(
'post_title' => ucfirst( $insert_array[1] ), //lowercase in some data
'post_content' => $insert_array[1],
'post_status' => 'publish',
'post_author' => 3,
'comment_status' => 'closed',
'post_category' => $cats,
'post_type' => 'city'
) ;
$post_id = wp_insert_post( $post_arr ) ;
$args = array(
'post_id' => $post_id,
'count' => true,
) ;
$previous_comment = get_comments( $args ) ;
$comment_data['comment_post_ID'] = $post_id ;
//add unique comments only
if ( ! $previous_comment ) {
$comment = wp_insert_comment( $comment_data ) ;
if ( ! $comment ) {
custom_logs( 'FALSE FOR ' . $i ) ;
custom_logs( print_r( $insert_array, true ) ) ;
}
}
$cities[] = $insert_array[1] ;
} else { //find city for comments
$db_rows = array() ; // don't accumulate gigantic db_rows?
$id = get_page_by_title( $insert_array[1], OBJECT, 'city' )->ID ;
$args = array(
'post_id' => $id,
) ;
$previous_comments = get_comments( $args ) ;
foreach ( $previous_comments as $previous_comment ) {
$db_rows[] = get_comment_meta( $previous_comment->comment_ID, 'db_row', true ) ;
}
if ( $previous_comments && ! in_array( $insert_array[6], $db_rows ) ) {
$comment_data['comment_post_ID'] = $id ;
$comment = wp_insert_comment( $comment_data ) ;
if ( ! $comment ) {
custom_logs( 'FALSE FOR ' . $i ) ; //"custom_logs( $message )" is a utility function for debugging
custom_logs( print_r( $insert_array, true ) ) ;
}
}
}
}
return $i . 'COMMENTS INSERTED' ;
}
``` | Your basic strategy is correct. The problem is that, although there are some best practices, you can't never know for sure in a easy way, 100% of time:
1. when a plugin or theme will enqueue scripts and styles;
2. what priority is used to enqueue
3. if a plugin or theme really used enqueue/register hooks or hard-coded.
That said, you might want to a) **hook your code to different actions when the scripts and styles are printed** (*and not enqueued*) and test different priorities. Or b) you could check each plugin and theme code and see what hook and priority are used to each `wp_enqueue_script` or `wp_enqueue_style` call.
I would suggest going with option a, something like this:
```
function wpse_382138_disable_plugins_style()
{
//these should use the same priority of later than the priority used by the plugin or theme when hooked
wp_dequeue_style('stylesheet-handler-with-default-priority');
wp_dequeue_style('stylesheet-handler-with-explicit-default-priorit', 10);
wp_dequeue_style('stylesheet-handler-with-later-priority', 20);
}
function wpse_382138_disable_plugins_scripts()
{
// these should use the same priority of later than the priority used by the plugin or theme when hooked
wp_dequeue_script('script-handler-with-default-priority');
wp_dequeue_script('script-handler-with-explicit-default-priority', 10);
wp_dequeue_script('script-handler-with-later-priority', 20);
}
// option A: hook your unhooking functions either to hooks later than wp_enqueue_scripts or wp_enqueue_style as wp_head or wp_footer.
add_action('wp_head', 'wpse_382138_disable_plugins_style', 10);
add_action('wp_footer', 'wpse_382138_disable_plugins_style', 10);
add_action('wp_head', 'wpse_382138_disable_plugins_scripts', 10);
add_action('wp_footer', 'wpse_382138_disable_plugins_scripts', 10);
// option b: hook your unhooking functions to the printing actions with a priority lower than the before first scripts or styles are usuarlly written, so they will execute the dequeue before scripts and styles are printed.
add_action('wp_print_scripts', 'wpse_382138_disable_plugins_style', 5);
add_action('wp_print_footer_scripts', 'wpse_382138_disable_plugins_style', 5);
add_action('wp_print_styles', 'wpse_382138_isable_plugins_scrips', 5);
```
[This Codex page](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) has a list of almost all hooks triggered in a typical WordPress Request.
Let me know if it helped you. |
382,200 | <p>I am trying to write a shortcode to display the page title. I only got the archive title to work, but not custom post type category and single post. Can anyone shed light how to do this?</p>
<p>The reason for going this path is Elemenentor theme builder generating too much code for simple page title and subheading inside secondary header that is masked wrap around an image. I use the shortcode widget to insert the code and style it.</p>
<p>So far this is what I have written:</p>
<pre><code>// Page Title inside shortcode
function page_title_sc( ) {
$title = ('Page Title');
if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
}
elseif ( is_page() ) {
$title = single_post_title();
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' );
</code></pre>
| [
{
"answer_id": 382202,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not completely sure what you want to do but <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page</code></a> will check for a page and exclude (custom) posts. If you want the condition to work for posts you will need <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\"><code>is_single</code></a>. If you want the condition to work for both posts and pages you will need <a href=\"https://developer.wordpress.org/reference/functions/is_singular/\" rel=\"nofollow noreferrer\"><code>is_singular</code></a>.</p>\n<p>That said, going this path may not be the smartest thing to do, because you will be polluting your post content. It would be more logical to write a filter for the title that cancels what Elementor does to it that you don't like. If you write a filter with a high priority, you can achieve the same thing you are now doing with a shortcode without having to modify your post content.</p>\n"
},
{
"answer_id": 382206,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .</p>\n<p>According to your Needed.</p>\n<pre><code>function page_title_sc( ) {\n\n $title = ('Page Title');\n\n if ( is_page() || is_singular() ) {\n $title = single_post_title();\n } else if ( is_category() ) {\n $title = single_cat_title( '', false );\n } else if ( is_tag() ) {\n $title = single_tag_title( '', false );\n } else if ( is_author() ) {\n $title = '<span class="vcard">' . get_the_author() . '</span>';\n } else if ( is_post_type_archive() ) {\n $title = post_type_archive_title( '', false );\n } else if ( is_tax() ) {\n $title = single_term_title( '', false );\n }\n\n return apply_filters( 'page_title_sc', $title );\n}\n \nadd_shortcode( 'page_title', 'page_title_sc' );\n</code></pre>\n"
}
] | 2021/01/26 | [
"https://wordpress.stackexchange.com/questions/382200",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146914/"
] | I am trying to write a shortcode to display the page title. I only got the archive title to work, but not custom post type category and single post. Can anyone shed light how to do this?
The reason for going this path is Elemenentor theme builder generating too much code for simple page title and subheading inside secondary header that is masked wrap around an image. I use the shortcode widget to insert the code and style it.
So far this is what I have written:
```
// Page Title inside shortcode
function page_title_sc( ) {
$title = ('Page Title');
if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
}
elseif ( is_page() ) {
$title = single_post_title();
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' );
``` | Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .
According to your Needed.
```
function page_title_sc( ) {
$title = ('Page Title');
if ( is_page() || is_singular() ) {
$title = single_post_title();
} else if ( is_category() ) {
$title = single_cat_title( '', false );
} else if ( is_tag() ) {
$title = single_tag_title( '', false );
} else if ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} else if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
} else if ( is_tax() ) {
$title = single_term_title( '', false );
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' );
``` |
382,205 | <p>I had built a functionality plugin and hooked with actions to another plugin. I had also made a style.css in myplugin/stylesheets/ directory. I placed the code there. I would like to make the styling dependent on my plugin and not my theme.</p>
<p>So far I have been trying this:</p>
<pre><code>function epf_override_style() {
wp_register_style( 'epf-style', '/stylesheets/style.css' ); //Subdir in plugin directory.
wp_enqueue_style( 'epf-style' );
}
add_action( 'es_extra_bottom_info','epf_override_style' );
</code></pre>
<p>How can I use the stlye.css of my plugin instead of the theme's (child theme's) style.css?</p>
| [
{
"answer_id": 382202,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not completely sure what you want to do but <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page</code></a> will check for a page and exclude (custom) posts. If you want the condition to work for posts you will need <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\"><code>is_single</code></a>. If you want the condition to work for both posts and pages you will need <a href=\"https://developer.wordpress.org/reference/functions/is_singular/\" rel=\"nofollow noreferrer\"><code>is_singular</code></a>.</p>\n<p>That said, going this path may not be the smartest thing to do, because you will be polluting your post content. It would be more logical to write a filter for the title that cancels what Elementor does to it that you don't like. If you write a filter with a high priority, you can achieve the same thing you are now doing with a shortcode without having to modify your post content.</p>\n"
},
{
"answer_id": 382206,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .</p>\n<p>According to your Needed.</p>\n<pre><code>function page_title_sc( ) {\n\n $title = ('Page Title');\n\n if ( is_page() || is_singular() ) {\n $title = single_post_title();\n } else if ( is_category() ) {\n $title = single_cat_title( '', false );\n } else if ( is_tag() ) {\n $title = single_tag_title( '', false );\n } else if ( is_author() ) {\n $title = '<span class="vcard">' . get_the_author() . '</span>';\n } else if ( is_post_type_archive() ) {\n $title = post_type_archive_title( '', false );\n } else if ( is_tax() ) {\n $title = single_term_title( '', false );\n }\n\n return apply_filters( 'page_title_sc', $title );\n}\n \nadd_shortcode( 'page_title', 'page_title_sc' );\n</code></pre>\n"
}
] | 2021/01/26 | [
"https://wordpress.stackexchange.com/questions/382205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200692/"
] | I had built a functionality plugin and hooked with actions to another plugin. I had also made a style.css in myplugin/stylesheets/ directory. I placed the code there. I would like to make the styling dependent on my plugin and not my theme.
So far I have been trying this:
```
function epf_override_style() {
wp_register_style( 'epf-style', '/stylesheets/style.css' ); //Subdir in plugin directory.
wp_enqueue_style( 'epf-style' );
}
add_action( 'es_extra_bottom_info','epf_override_style' );
```
How can I use the stlye.css of my plugin instead of the theme's (child theme's) style.css? | Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .
According to your Needed.
```
function page_title_sc( ) {
$title = ('Page Title');
if ( is_page() || is_singular() ) {
$title = single_post_title();
} else if ( is_category() ) {
$title = single_cat_title( '', false );
} else if ( is_tag() ) {
$title = single_tag_title( '', false );
} else if ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} else if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
} else if ( is_tax() ) {
$title = single_term_title( '', false );
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' );
``` |
382,212 | <p>im trying to submit the following form but it just wont work:</p>
<p>HTML:</p>
<pre><code><div class= "container">
<div class="row">
<div class= "col-md-10 mx-auto text-center">
<div style="display:none;" id="success">
<p class="pb-1 pt-1" style="color:white;background-color:#008000;font-size:20px;font-family:poppins;border-radius:3px;border:3px solid #008000;">Your Request Has Been Sent!</p>
</div>
<form method="POST" id="request_quote" action="request_quote_ajax">
<div class="form-group ">
<input type="hidden" name="action" value="request_quote_ajax">
<select placeholder="Product Or Service Of
Interest" class="form-control form-control-lg" id="product" type="text" name="product" required>
<option value="">Product Or Service Of
Interest</option>
<option value="Solar PV System">Solar PV System</option>
<option value="Solar Water Heater">Solar Water Heater</option>
<option value="Solar Pool Heating">Solar Pool Heating</option>
<option value="Servicing">Servicing</option>
</select>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="fullname" name="fullname" placeholder="Full Name" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="email" name="email" placeholder="Email" required>
</div>
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" name="phonenumber1" id="phonenumber1" placeholder="Phonenumber 1" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" name="phonenumber2" id="phonenumber2" placeholder="Phonenumber 2" >
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg " id="exampleInputPassword1" placeholder="Street Address" name="address" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="parish" name="parish" placeholder="Parish" required>
</div>
</div>
</div>
<div class="form-group">
<textarea type="textarea" class="form-control form-control-lg" name="_usermessage" id="_usermessage" placeholder="Your Message" required></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary">GO SOLAR</button>
</div>
</div>
</form>
</code></pre>
<p>Javascript:</p>
<pre><code><script>
$(document).ready(
$('#request_quote').submit(function(e){
e.preventDefault();
jQuery.post({
url: ajaxurl,
data: { $(this).serialize() },
die();
})
})
</script>
</code></pre>
<p>I used the following script to make ajax url available:</p>
<pre><code> add_action('wp_head', 'myplugin_ajaxurl');
function myplugin_ajaxurl()
{
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
</code></pre>
<p>My php function is as follows:</p>
<pre><code> add_action('wp_ajax_nopriv_request_quote_ajax', 'request_quote_ajax');
add_action('wp_ajax_request_quote_ajax', 'request_quote_ajax');
function request_quote_ajax()
{
// if the submit button is clicked, send the email
if (isset($_POST['submit'])) {
//user posted variables
$name = sanitize_text_field($_POST['fullname']);
$email = sanitize_email($_POST['email']);
$product = sanitize_text_field($_POST['product']);
$phonenumber1 = sanitize_text_field($_POST['phonenumber1']);
$phonenumber2 = sanitize_text_field($_POST['phonenumber2']);
$address = sanitize_text_field($_POST['address']);
$parish = sanitize_text_field($_POST['parish']);
$_usermessage = esc_textarea($_POST['_usermessage']);
//combined all fields inputs
$message = "Request For Quote : {$name} \n {$product} \n {$phonenumber1} \n {$phonenumber2} \n {$address} \n {$parish} \n {$_usermessage} ";
//php mailer variables
$third_email = "[email protected]";
$to = $third_email;
$subject = "Quotation Request From {$name}";
wp_mail($to, $subject, strip_tags($message));
//$headers = 'From: <[email protected]>' . "\r\n" .'Reply-To: ' . $email . "\r\n";
}
else{ do_action( 'wp_mail_failed', WP_Error, $error ); }
wp_die();
}
</code></pre>
<p>Everytime i try submitting the form i get a 404 error. I have tried all solutions on similar posts but none have worked please help me</p>
| [
{
"answer_id": 382202,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not completely sure what you want to do but <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page</code></a> will check for a page and exclude (custom) posts. If you want the condition to work for posts you will need <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\"><code>is_single</code></a>. If you want the condition to work for both posts and pages you will need <a href=\"https://developer.wordpress.org/reference/functions/is_singular/\" rel=\"nofollow noreferrer\"><code>is_singular</code></a>.</p>\n<p>That said, going this path may not be the smartest thing to do, because you will be polluting your post content. It would be more logical to write a filter for the title that cancels what Elementor does to it that you don't like. If you write a filter with a high priority, you can achieve the same thing you are now doing with a shortcode without having to modify your post content.</p>\n"
},
{
"answer_id": 382206,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .</p>\n<p>According to your Needed.</p>\n<pre><code>function page_title_sc( ) {\n\n $title = ('Page Title');\n\n if ( is_page() || is_singular() ) {\n $title = single_post_title();\n } else if ( is_category() ) {\n $title = single_cat_title( '', false );\n } else if ( is_tag() ) {\n $title = single_tag_title( '', false );\n } else if ( is_author() ) {\n $title = '<span class="vcard">' . get_the_author() . '</span>';\n } else if ( is_post_type_archive() ) {\n $title = post_type_archive_title( '', false );\n } else if ( is_tax() ) {\n $title = single_term_title( '', false );\n }\n\n return apply_filters( 'page_title_sc', $title );\n}\n \nadd_shortcode( 'page_title', 'page_title_sc' );\n</code></pre>\n"
}
] | 2021/01/26 | [
"https://wordpress.stackexchange.com/questions/382212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/200961/"
] | im trying to submit the following form but it just wont work:
HTML:
```
<div class= "container">
<div class="row">
<div class= "col-md-10 mx-auto text-center">
<div style="display:none;" id="success">
<p class="pb-1 pt-1" style="color:white;background-color:#008000;font-size:20px;font-family:poppins;border-radius:3px;border:3px solid #008000;">Your Request Has Been Sent!</p>
</div>
<form method="POST" id="request_quote" action="request_quote_ajax">
<div class="form-group ">
<input type="hidden" name="action" value="request_quote_ajax">
<select placeholder="Product Or Service Of
Interest" class="form-control form-control-lg" id="product" type="text" name="product" required>
<option value="">Product Or Service Of
Interest</option>
<option value="Solar PV System">Solar PV System</option>
<option value="Solar Water Heater">Solar Water Heater</option>
<option value="Solar Pool Heating">Solar Pool Heating</option>
<option value="Servicing">Servicing</option>
</select>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="fullname" name="fullname" placeholder="Full Name" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="email" name="email" placeholder="Email" required>
</div>
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" name="phonenumber1" id="phonenumber1" placeholder="Phonenumber 1" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" name="phonenumber2" id="phonenumber2" placeholder="Phonenumber 2" >
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<input type="text" class="form-control form-control-lg " id="exampleInputPassword1" placeholder="Street Address" name="address" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-lg" id="parish" name="parish" placeholder="Parish" required>
</div>
</div>
</div>
<div class="form-group">
<textarea type="textarea" class="form-control form-control-lg" name="_usermessage" id="_usermessage" placeholder="Your Message" required></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary">GO SOLAR</button>
</div>
</div>
</form>
```
Javascript:
```
<script>
$(document).ready(
$('#request_quote').submit(function(e){
e.preventDefault();
jQuery.post({
url: ajaxurl,
data: { $(this).serialize() },
die();
})
})
</script>
```
I used the following script to make ajax url available:
```
add_action('wp_head', 'myplugin_ajaxurl');
function myplugin_ajaxurl()
{
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
```
My php function is as follows:
```
add_action('wp_ajax_nopriv_request_quote_ajax', 'request_quote_ajax');
add_action('wp_ajax_request_quote_ajax', 'request_quote_ajax');
function request_quote_ajax()
{
// if the submit button is clicked, send the email
if (isset($_POST['submit'])) {
//user posted variables
$name = sanitize_text_field($_POST['fullname']);
$email = sanitize_email($_POST['email']);
$product = sanitize_text_field($_POST['product']);
$phonenumber1 = sanitize_text_field($_POST['phonenumber1']);
$phonenumber2 = sanitize_text_field($_POST['phonenumber2']);
$address = sanitize_text_field($_POST['address']);
$parish = sanitize_text_field($_POST['parish']);
$_usermessage = esc_textarea($_POST['_usermessage']);
//combined all fields inputs
$message = "Request For Quote : {$name} \n {$product} \n {$phonenumber1} \n {$phonenumber2} \n {$address} \n {$parish} \n {$_usermessage} ";
//php mailer variables
$third_email = "[email protected]";
$to = $third_email;
$subject = "Quotation Request From {$name}";
wp_mail($to, $subject, strip_tags($message));
//$headers = 'From: <[email protected]>' . "\r\n" .'Reply-To: ' . $email . "\r\n";
}
else{ do_action( 'wp_mail_failed', WP_Error, $error ); }
wp_die();
}
```
Everytime i try submitting the form i get a 404 error. I have tried all solutions on similar posts but none have worked please help me | Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .
According to your Needed.
```
function page_title_sc( ) {
$title = ('Page Title');
if ( is_page() || is_singular() ) {
$title = single_post_title();
} else if ( is_category() ) {
$title = single_cat_title( '', false );
} else if ( is_tag() ) {
$title = single_tag_title( '', false );
} else if ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} else if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
} else if ( is_tax() ) {
$title = single_term_title( '', false );
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' );
``` |
382,306 | <p>If you click on the Text tab, you can see the content, but when you switch back to the Visual tab, it displays nothing. It's not white text on white background either... it just has no content. The functionality works otherwise. I can enter or change content via the Text tab, and that works. But it never shows the content in the Visual tab.</p>
<p>I have disabled all plugins and switched to the 2020 theme, running on Wordpress 5.6 on my local machine, same results. Here's my test code:</p>
<pre><code>add_action('admin_init', 'custom_editor_meta_box');
function custom_editor_meta_box () {
add_meta_box ( 'custom-editor', 'Custom Editor', 'custom_editor_callback', 'post',);
}
function custom_editor_callback ( $post ) {
$content = get_post_meta($post->ID, 'custom_editor', true);
wp_editor ( $content, 'custom_editor', array ( "media_buttons" => true ),);
}
add_action('save_post', 'custom_editor_save_postdata');
function custom_editor_save_postdata ( $post_id ) {
if( isset( $_POST['custom_editor_nonce'] ) && isset( $_POST['post'] ) ) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( !wp_verify_nonce ( $_POST['custom_editor_nonce'] ) ) {
return;
}
if( 'post' == $_POST['post'] && !current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
if ( !empty( $_POST['custom_editor'] ) ) {
$data = $_POST['custom_editor'];
update_post_meta($post_id, 'custom_editor', $data);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/uMhTH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uMhTH.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/iweIA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iweIA.png" alt="enter image description here" /></a></p>
<p>Updated test code (still same results):</p>
<pre><code>function custom_editor_meta_box () {
add_meta_box ( 'custom-editor', 'Custom Editor', 'custom_editor_callback', 'post',);
}
function custom_editor_callback ( $post ) {
$content = get_post_meta($post->ID, 'custom_editor', true);
wp_editor ( $content, 'custom_editor', array ( "media_buttons" => true ) );
}
add_action('save_post', 'custom_editor_save_postdata');
function custom_editor_save_postdata ( $post_id ) {
if ( !empty( $_POST['custom_editor'] ) ) {
$data = $_POST['custom_editor'];
update_post_meta($post_id, 'custom_editor', $data);
}
}
</code></pre>
| [
{
"answer_id": 382310,
"author": "Jeremy Caris",
"author_id": 115709,
"author_profile": "https://wordpress.stackexchange.com/users/115709",
"pm_score": 1,
"selected": true,
"text": "<p>The issue appears to be a bug with Wordpress 5.6. See <a href=\"https://github.com/CMB2/CMB2/issues/1397\" rel=\"nofollow noreferrer\">this thread of comments for the same issue</a> with the CMB2 "developer's toolkit for building metaboxes, custom fields, and forms," which I implemented as an alternative to try (it produced the same results I get with the original code I posted).</p>\n"
},
{
"answer_id": 382598,
"author": "timmyg",
"author_id": 54745,
"author_profile": "https://wordpress.stackexchange.com/users/54745",
"pm_score": 1,
"selected": false,
"text": "<p>Just want to add in case anyone needs a quick temporary patch before the next WP core release: I found installing the Enable jQuery Migrate Helper plugin solved it for several of my custom meta boxes. Obviously not a long term solution.</p>\n"
},
{
"answer_id": 390258,
"author": "StarSagar",
"author_id": 179286,
"author_profile": "https://wordpress.stackexchange.com/users/179286",
"pm_score": 0,
"selected": false,
"text": "<p>A temporary workaround that works for me is, make a 'text' mode default for wp-editor, like</p>\n<pre><code>// Set wp-editor in the 'Text' mode by default.\nadd_filter(\n 'wp_default_editor',\n function () {\n return 'html';\n }\n);\n</code></pre>\n<p>When we switch from text to visual, the wp-editor(tinyMCE) works fine, though its not a perfect fix but a quick win over adding a whole new plugin(Enable jQuery Migrate Helper).</p>\n"
}
] | 2021/01/27 | [
"https://wordpress.stackexchange.com/questions/382306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115709/"
] | If you click on the Text tab, you can see the content, but when you switch back to the Visual tab, it displays nothing. It's not white text on white background either... it just has no content. The functionality works otherwise. I can enter or change content via the Text tab, and that works. But it never shows the content in the Visual tab.
I have disabled all plugins and switched to the 2020 theme, running on Wordpress 5.6 on my local machine, same results. Here's my test code:
```
add_action('admin_init', 'custom_editor_meta_box');
function custom_editor_meta_box () {
add_meta_box ( 'custom-editor', 'Custom Editor', 'custom_editor_callback', 'post',);
}
function custom_editor_callback ( $post ) {
$content = get_post_meta($post->ID, 'custom_editor', true);
wp_editor ( $content, 'custom_editor', array ( "media_buttons" => true ),);
}
add_action('save_post', 'custom_editor_save_postdata');
function custom_editor_save_postdata ( $post_id ) {
if( isset( $_POST['custom_editor_nonce'] ) && isset( $_POST['post'] ) ) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( !wp_verify_nonce ( $_POST['custom_editor_nonce'] ) ) {
return;
}
if( 'post' == $_POST['post'] && !current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
if ( !empty( $_POST['custom_editor'] ) ) {
$data = $_POST['custom_editor'];
update_post_meta($post_id, 'custom_editor', $data);
}
}
```
[](https://i.stack.imgur.com/uMhTH.png)
[](https://i.stack.imgur.com/iweIA.png)
Updated test code (still same results):
```
function custom_editor_meta_box () {
add_meta_box ( 'custom-editor', 'Custom Editor', 'custom_editor_callback', 'post',);
}
function custom_editor_callback ( $post ) {
$content = get_post_meta($post->ID, 'custom_editor', true);
wp_editor ( $content, 'custom_editor', array ( "media_buttons" => true ) );
}
add_action('save_post', 'custom_editor_save_postdata');
function custom_editor_save_postdata ( $post_id ) {
if ( !empty( $_POST['custom_editor'] ) ) {
$data = $_POST['custom_editor'];
update_post_meta($post_id, 'custom_editor', $data);
}
}
``` | The issue appears to be a bug with Wordpress 5.6. See [this thread of comments for the same issue](https://github.com/CMB2/CMB2/issues/1397) with the CMB2 "developer's toolkit for building metaboxes, custom fields, and forms," which I implemented as an alternative to try (it produced the same results I get with the original code I posted). |
382,331 | <p>I want to display a Custom post Type "Companies" filtered by zipcode.</p>
<p>In my CPT I have an ACF field called 'companies_zip_code', their values looks like this :</p>
<pre><code>29200
29860
35000
22350
...
</code></pre>
<p><strong>I want to display only companies where their companies_zip_code begins with <code>29</code></strong></p>
<p>So I write this WP_QUery :</p>
<pre><code>$args = array(
'post_type' => 'companies',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'company_address_zip_code',
'value' => 29,
'compare' => 'LIKE',
)
)
);
$custom_query = new WP_Query($args);
</code></pre>
<p>With that I want to display only companies with zipcodes like this : <code>29200,29500,29860 etc..</code>
But it does not work</p>
<p>Thanks for your help !</p>
| [
{
"answer_id": 382310,
"author": "Jeremy Caris",
"author_id": 115709,
"author_profile": "https://wordpress.stackexchange.com/users/115709",
"pm_score": 1,
"selected": true,
"text": "<p>The issue appears to be a bug with Wordpress 5.6. See <a href=\"https://github.com/CMB2/CMB2/issues/1397\" rel=\"nofollow noreferrer\">this thread of comments for the same issue</a> with the CMB2 "developer's toolkit for building metaboxes, custom fields, and forms," which I implemented as an alternative to try (it produced the same results I get with the original code I posted).</p>\n"
},
{
"answer_id": 382598,
"author": "timmyg",
"author_id": 54745,
"author_profile": "https://wordpress.stackexchange.com/users/54745",
"pm_score": 1,
"selected": false,
"text": "<p>Just want to add in case anyone needs a quick temporary patch before the next WP core release: I found installing the Enable jQuery Migrate Helper plugin solved it for several of my custom meta boxes. Obviously not a long term solution.</p>\n"
},
{
"answer_id": 390258,
"author": "StarSagar",
"author_id": 179286,
"author_profile": "https://wordpress.stackexchange.com/users/179286",
"pm_score": 0,
"selected": false,
"text": "<p>A temporary workaround that works for me is, make a 'text' mode default for wp-editor, like</p>\n<pre><code>// Set wp-editor in the 'Text' mode by default.\nadd_filter(\n 'wp_default_editor',\n function () {\n return 'html';\n }\n);\n</code></pre>\n<p>When we switch from text to visual, the wp-editor(tinyMCE) works fine, though its not a perfect fix but a quick win over adding a whole new plugin(Enable jQuery Migrate Helper).</p>\n"
}
] | 2021/01/28 | [
"https://wordpress.stackexchange.com/questions/382331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201077/"
] | I want to display a Custom post Type "Companies" filtered by zipcode.
In my CPT I have an ACF field called 'companies\_zip\_code', their values looks like this :
```
29200
29860
35000
22350
...
```
**I want to display only companies where their companies\_zip\_code begins with `29`**
So I write this WP\_QUery :
```
$args = array(
'post_type' => 'companies',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'company_address_zip_code',
'value' => 29,
'compare' => 'LIKE',
)
)
);
$custom_query = new WP_Query($args);
```
With that I want to display only companies with zipcodes like this : `29200,29500,29860 etc..`
But it does not work
Thanks for your help ! | The issue appears to be a bug with Wordpress 5.6. See [this thread of comments for the same issue](https://github.com/CMB2/CMB2/issues/1397) with the CMB2 "developer's toolkit for building metaboxes, custom fields, and forms," which I implemented as an alternative to try (it produced the same results I get with the original code I posted). |
382,528 | <p>I have a thank you page on my website and I don't want anyone can access it directly so I use the below code and it working.</p>
<pre><code>add_action('template_redirect', function() {
// ID of the thank you page
if (!is_page(947)) { //id of page
return;
}
// coming from the form, so all is fine
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
});
</code></pre>
<p>Now, what I am doing, I have one more form on my single post and once the user submits the form then it will redirect to the thank you page but it's not going because I added the above code on my <code>function.php</code>.</p>
<p>So anyone knows how to access the thank you page from the single post?</p>
| [
{
"answer_id": 382534,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>It might be better to match the thanks page, then try to match the referer and if those conditions don't match, do nothing.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', function() {\n\n // match based on two condition:\n // current page is "thanks" - which I am guessing is "thanks"\n // and the referer is /contact-us/ - not this is unreliable, as referer might be empty\n if ( \n is_page('thanks') // is page "thanks"\n ) { \n \n // referer matches\n if( wp_get_referer() === get_site_url().'/contact-us/' ) {\n \n error_log( 'All good..' );\n return;\n\n } else {\n\n // redirect to home\n wp_redirect( get_home_url() );\n exit;\n\n }\n\n }\n\n // nothing to do here, as not thanks page\n\n});\n</code></pre>\n"
},
{
"answer_id": 383196,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><sup><strong>Note:</strong> WordPress deliberately misspelled the word 'referer', and thus, so did I..</sup></p>\n<p>If you just want to check if the referer is your <code>contact-us</code> Page or <em>any</em> single Post page, then you can first retrieve the current URL path (i.e. <code>example.com/<this part>/</code>) and then check if the path is exactly <code>contact-us</code> (or whatever is your contact Page's slug), and use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> to find a single post having that path as the slug.</p>\n<p>So try this, which worked for me (tested with WordPress 5.6.1):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Replace this:\nif (wp_get_referer() === get_site_url().'/contact-us/') {\n return;\n}\n\n// with this:\n$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );\n// If it's the contact page, don't redirect.\nif ( 'contact-us' === $path ) {\n return;\n} elseif ( $path ) {\n $posts = get_posts( array(\n 'name' => $path,\n 'posts_per_page' => 1,\n ) );\n // If a post with the slug in $path was found, don't redirect.\n if ( ! empty( $posts ) ) {\n return;\n }\n}\n</code></pre>\n<ul>\n<li>But note that the code would only work if your permalink structure (for the default <code>post</code> type) is <code>/%postname%/</code> — with or without the leading and/or trailing slashes.</li>\n</ul>\n<p>And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :)</p>\n"
}
] | 2021/01/31 | [
"https://wordpress.stackexchange.com/questions/382528",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177715/"
] | I have a thank you page on my website and I don't want anyone can access it directly so I use the below code and it working.
```
add_action('template_redirect', function() {
// ID of the thank you page
if (!is_page(947)) { //id of page
return;
}
// coming from the form, so all is fine
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
});
```
Now, what I am doing, I have one more form on my single post and once the user submits the form then it will redirect to the thank you page but it's not going because I added the above code on my `function.php`.
So anyone knows how to access the thank you page from the single post? | **Note:** WordPress deliberately misspelled the word 'referer', and thus, so did I..
If you just want to check if the referer is your `contact-us` Page or *any* single Post page, then you can first retrieve the current URL path (i.e. `example.com/<this part>/`) and then check if the path is exactly `contact-us` (or whatever is your contact Page's slug), and use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) to find a single post having that path as the slug.
So try this, which worked for me (tested with WordPress 5.6.1):
```php
// Replace this:
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// with this:
$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );
// If it's the contact page, don't redirect.
if ( 'contact-us' === $path ) {
return;
} elseif ( $path ) {
$posts = get_posts( array(
'name' => $path,
'posts_per_page' => 1,
) );
// If a post with the slug in $path was found, don't redirect.
if ( ! empty( $posts ) ) {
return;
}
}
```
* But note that the code would only work if your permalink structure (for the default `post` type) is `/%postname%/` — with or without the leading and/or trailing slashes.
And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :) |
382,701 | <pre><code>@media (max-width: 768px) {
.page-id-9334 .site-content {
display: flex;
flex-direction: column-reverse;
}
}
</code></pre>
<p>I am trying to load this CSS into Custom Taxonomy Pages...</p>
<p>My original question refers to a specific Page ID (and I edited my original question).</p>
<p>Anyways - based upon the replies below I thought that this would work but it throws an error, with or without the <code><style></code> CSS Opening Tags.</p>
<p>Can anyone else please shed some light on how I might be able to get this to work?</p>
<p>Thanks!</p>
<pre><code>add_action( 'wp_head', function () {
if ( is_tax(country) ) {
<style>
@media (max-width: 768px) {
.site-content {
display: flex;
flex-direction: column-reverse;
}
}
</style>
}
} );
</code></pre>
| [
{
"answer_id": 382534,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>It might be better to match the thanks page, then try to match the referer and if those conditions don't match, do nothing.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', function() {\n\n // match based on two condition:\n // current page is "thanks" - which I am guessing is "thanks"\n // and the referer is /contact-us/ - not this is unreliable, as referer might be empty\n if ( \n is_page('thanks') // is page "thanks"\n ) { \n \n // referer matches\n if( wp_get_referer() === get_site_url().'/contact-us/' ) {\n \n error_log( 'All good..' );\n return;\n\n } else {\n\n // redirect to home\n wp_redirect( get_home_url() );\n exit;\n\n }\n\n }\n\n // nothing to do here, as not thanks page\n\n});\n</code></pre>\n"
},
{
"answer_id": 383196,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><sup><strong>Note:</strong> WordPress deliberately misspelled the word 'referer', and thus, so did I..</sup></p>\n<p>If you just want to check if the referer is your <code>contact-us</code> Page or <em>any</em> single Post page, then you can first retrieve the current URL path (i.e. <code>example.com/<this part>/</code>) and then check if the path is exactly <code>contact-us</code> (or whatever is your contact Page's slug), and use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> to find a single post having that path as the slug.</p>\n<p>So try this, which worked for me (tested with WordPress 5.6.1):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Replace this:\nif (wp_get_referer() === get_site_url().'/contact-us/') {\n return;\n}\n\n// with this:\n$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );\n// If it's the contact page, don't redirect.\nif ( 'contact-us' === $path ) {\n return;\n} elseif ( $path ) {\n $posts = get_posts( array(\n 'name' => $path,\n 'posts_per_page' => 1,\n ) );\n // If a post with the slug in $path was found, don't redirect.\n if ( ! empty( $posts ) ) {\n return;\n }\n}\n</code></pre>\n<ul>\n<li>But note that the code would only work if your permalink structure (for the default <code>post</code> type) is <code>/%postname%/</code> — with or without the leading and/or trailing slashes.</li>\n</ul>\n<p>And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :)</p>\n"
}
] | 2021/02/03 | [
"https://wordpress.stackexchange.com/questions/382701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | ```
@media (max-width: 768px) {
.page-id-9334 .site-content {
display: flex;
flex-direction: column-reverse;
}
}
```
I am trying to load this CSS into Custom Taxonomy Pages...
My original question refers to a specific Page ID (and I edited my original question).
Anyways - based upon the replies below I thought that this would work but it throws an error, with or without the `<style>` CSS Opening Tags.
Can anyone else please shed some light on how I might be able to get this to work?
Thanks!
```
add_action( 'wp_head', function () {
if ( is_tax(country) ) {
<style>
@media (max-width: 768px) {
.site-content {
display: flex;
flex-direction: column-reverse;
}
}
</style>
}
} );
``` | **Note:** WordPress deliberately misspelled the word 'referer', and thus, so did I..
If you just want to check if the referer is your `contact-us` Page or *any* single Post page, then you can first retrieve the current URL path (i.e. `example.com/<this part>/`) and then check if the path is exactly `contact-us` (or whatever is your contact Page's slug), and use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) to find a single post having that path as the slug.
So try this, which worked for me (tested with WordPress 5.6.1):
```php
// Replace this:
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// with this:
$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );
// If it's the contact page, don't redirect.
if ( 'contact-us' === $path ) {
return;
} elseif ( $path ) {
$posts = get_posts( array(
'name' => $path,
'posts_per_page' => 1,
) );
// If a post with the slug in $path was found, don't redirect.
if ( ! empty( $posts ) ) {
return;
}
}
```
* But note that the code would only work if your permalink structure (for the default `post` type) is `/%postname%/` — with or without the leading and/or trailing slashes.
And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :) |
382,768 | <p>I would like to create a function that instead of hiding the products without thumbnails, would be ordered in such a way that the products with the highlighted image appear first on the shop page while those without the highlighted image appear at the end. I tried to modify an already <a href="https://stackoverflow.com/questions/44884498/hiding-products-without-thumbnail-in-woocommerce-shop-page">existing function</a>:</p>
<pre><code> function woocommerce_product_query( $q ) {
$q->set( 'meta_key', '_thumbnail_id' );
$q->set('orderby', 'meta_value_num');
$q->set('order', 'DESC');
}
add_action( 'woocommerce_product_query', 'woocommerce_product_query' );
</code></pre>
<p>I tried adding <code>orderby</code> to this already existing function too but nothing happens, keep hiding the products from me.</p>
<p><img src="https://i.stack.imgur.com/ctunV.png" alt="Shop page" />
In this photo the function only hides the products without thumbnail.
I don't know how to solve ...</p>
| [
{
"answer_id": 382534,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>It might be better to match the thanks page, then try to match the referer and if those conditions don't match, do nothing.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', function() {\n\n // match based on two condition:\n // current page is "thanks" - which I am guessing is "thanks"\n // and the referer is /contact-us/ - not this is unreliable, as referer might be empty\n if ( \n is_page('thanks') // is page "thanks"\n ) { \n \n // referer matches\n if( wp_get_referer() === get_site_url().'/contact-us/' ) {\n \n error_log( 'All good..' );\n return;\n\n } else {\n\n // redirect to home\n wp_redirect( get_home_url() );\n exit;\n\n }\n\n }\n\n // nothing to do here, as not thanks page\n\n});\n</code></pre>\n"
},
{
"answer_id": 383196,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><sup><strong>Note:</strong> WordPress deliberately misspelled the word 'referer', and thus, so did I..</sup></p>\n<p>If you just want to check if the referer is your <code>contact-us</code> Page or <em>any</em> single Post page, then you can first retrieve the current URL path (i.e. <code>example.com/<this part>/</code>) and then check if the path is exactly <code>contact-us</code> (or whatever is your contact Page's slug), and use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> to find a single post having that path as the slug.</p>\n<p>So try this, which worked for me (tested with WordPress 5.6.1):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Replace this:\nif (wp_get_referer() === get_site_url().'/contact-us/') {\n return;\n}\n\n// with this:\n$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );\n// If it's the contact page, don't redirect.\nif ( 'contact-us' === $path ) {\n return;\n} elseif ( $path ) {\n $posts = get_posts( array(\n 'name' => $path,\n 'posts_per_page' => 1,\n ) );\n // If a post with the slug in $path was found, don't redirect.\n if ( ! empty( $posts ) ) {\n return;\n }\n}\n</code></pre>\n<ul>\n<li>But note that the code would only work if your permalink structure (for the default <code>post</code> type) is <code>/%postname%/</code> — with or without the leading and/or trailing slashes.</li>\n</ul>\n<p>And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :)</p>\n"
}
] | 2021/02/04 | [
"https://wordpress.stackexchange.com/questions/382768",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201411/"
] | I would like to create a function that instead of hiding the products without thumbnails, would be ordered in such a way that the products with the highlighted image appear first on the shop page while those without the highlighted image appear at the end. I tried to modify an already [existing function](https://stackoverflow.com/questions/44884498/hiding-products-without-thumbnail-in-woocommerce-shop-page):
```
function woocommerce_product_query( $q ) {
$q->set( 'meta_key', '_thumbnail_id' );
$q->set('orderby', 'meta_value_num');
$q->set('order', 'DESC');
}
add_action( 'woocommerce_product_query', 'woocommerce_product_query' );
```
I tried adding `orderby` to this already existing function too but nothing happens, keep hiding the products from me.

In this photo the function only hides the products without thumbnail.
I don't know how to solve ... | **Note:** WordPress deliberately misspelled the word 'referer', and thus, so did I..
If you just want to check if the referer is your `contact-us` Page or *any* single Post page, then you can first retrieve the current URL path (i.e. `example.com/<this part>/`) and then check if the path is exactly `contact-us` (or whatever is your contact Page's slug), and use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) to find a single post having that path as the slug.
So try this, which worked for me (tested with WordPress 5.6.1):
```php
// Replace this:
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// with this:
$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );
// If it's the contact page, don't redirect.
if ( 'contact-us' === $path ) {
return;
} elseif ( $path ) {
$posts = get_posts( array(
'name' => $path,
'posts_per_page' => 1,
) );
// If a post with the slug in $path was found, don't redirect.
if ( ! empty( $posts ) ) {
return;
}
}
```
* But note that the code would only work if your permalink structure (for the default `post` type) is `/%postname%/` — with or without the leading and/or trailing slashes.
And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :) |
382,793 | <p>My home page uses ACF ("settings home") fields. These fields position the items in the footer. The problem is that they don't display on other sites. How to display fields from the home page on all subpages? So that you do not have to enter the same data on each subpage</p>
<p>To display in footer.php I'm using:</p>
<pre><code><?php the_field('contact_form_title'); ?>
</code></pre>
| [
{
"answer_id": 382534,
"author": "Q Studio",
"author_id": 7968,
"author_profile": "https://wordpress.stackexchange.com/users/7968",
"pm_score": 0,
"selected": false,
"text": "<p>It might be better to match the thanks page, then try to match the referer and if those conditions don't match, do nothing.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', function() {\n\n // match based on two condition:\n // current page is "thanks" - which I am guessing is "thanks"\n // and the referer is /contact-us/ - not this is unreliable, as referer might be empty\n if ( \n is_page('thanks') // is page "thanks"\n ) { \n \n // referer matches\n if( wp_get_referer() === get_site_url().'/contact-us/' ) {\n \n error_log( 'All good..' );\n return;\n\n } else {\n\n // redirect to home\n wp_redirect( get_home_url() );\n exit;\n\n }\n\n }\n\n // nothing to do here, as not thanks page\n\n});\n</code></pre>\n"
},
{
"answer_id": 383196,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p><sup><strong>Note:</strong> WordPress deliberately misspelled the word 'referer', and thus, so did I..</sup></p>\n<p>If you just want to check if the referer is your <code>contact-us</code> Page or <em>any</em> single Post page, then you can first retrieve the current URL path (i.e. <code>example.com/<this part>/</code>) and then check if the path is exactly <code>contact-us</code> (or whatever is your contact Page's slug), and use <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> to find a single post having that path as the slug.</p>\n<p>So try this, which worked for me (tested with WordPress 5.6.1):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Replace this:\nif (wp_get_referer() === get_site_url().'/contact-us/') {\n return;\n}\n\n// with this:\n$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );\n// If it's the contact page, don't redirect.\nif ( 'contact-us' === $path ) {\n return;\n} elseif ( $path ) {\n $posts = get_posts( array(\n 'name' => $path,\n 'posts_per_page' => 1,\n ) );\n // If a post with the slug in $path was found, don't redirect.\n if ( ! empty( $posts ) ) {\n return;\n }\n}\n</code></pre>\n<ul>\n<li>But note that the code would only work if your permalink structure (for the default <code>post</code> type) is <code>/%postname%/</code> — with or without the leading and/or trailing slashes.</li>\n</ul>\n<p>And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :)</p>\n"
}
] | 2021/02/04 | [
"https://wordpress.stackexchange.com/questions/382793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147411/"
] | My home page uses ACF ("settings home") fields. These fields position the items in the footer. The problem is that they don't display on other sites. How to display fields from the home page on all subpages? So that you do not have to enter the same data on each subpage
To display in footer.php I'm using:
```
<?php the_field('contact_form_title'); ?>
``` | **Note:** WordPress deliberately misspelled the word 'referer', and thus, so did I..
If you just want to check if the referer is your `contact-us` Page or *any* single Post page, then you can first retrieve the current URL path (i.e. `example.com/<this part>/`) and then check if the path is exactly `contact-us` (or whatever is your contact Page's slug), and use [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) to find a single post having that path as the slug.
So try this, which worked for me (tested with WordPress 5.6.1):
```php
// Replace this:
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// with this:
$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );
// If it's the contact page, don't redirect.
if ( 'contact-us' === $path ) {
return;
} elseif ( $path ) {
$posts = get_posts( array(
'name' => $path,
'posts_per_page' => 1,
) );
// If a post with the slug in $path was found, don't redirect.
if ( ! empty( $posts ) ) {
return;
}
}
```
* But note that the code would only work if your permalink structure (for the default `post` type) is `/%postname%/` — with or without the leading and/or trailing slashes.
And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :) |
382,892 | <p>I am using this function which works great in case anyone wants to bulk update custom fields for custom post types (just change parameters as necessary).</p>
<pre><code> $args=array(
'posts_per_page' => -1,
'post_type' => 'mycptype'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$testa = get_field('br_type');
$testb = get_field('br_category');
if ($testa === 'Apples') {
update_field('br_featured', '0', get_the_ID());
}
endwhile;
wp_reset_postdata();
endif;
</code></pre>
<p>How to use:</p>
<ol>
<li>Insert the code inside your functions.php and refresh your website ONCE</li>
<li>Then don't forget to delete the code.</li>
</ol>
<p>The problem I am having is that even if the function works as expected and updates the value of the custom field, I need to go inside each custom post type and click on the button "Update" for the changes to take effect.</p>
<p>This is because the ACF field has been registered after the custom post types were published.</p>
<p>Is there a workaround for not going inside each post and click update?</p>
| [
{
"answer_id": 406209,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>Why not save yourself a whole lot of hassle and add a handy admin menu item "Bulk Update" that you can just click whenever you need it.</p>\n<p>This method (using hooks) also ensures that WordPress (as well as ACF and your custom post types) are safely loaded and ready to go.</p>\n<pre><code>/**\n * Register "Bulk Update" menu item under the "mycptype" admin menu.\n *\n * Menu item links directly to admin-post.php?action=mycptype_bulk_update\n *\n * ...which is handled by {@see wpse_382892_bulk_update()}\n *\n * @see https://developer.wordpress.org/reference/functions/add_submenu_page/\n */\nfunction wpse_382892_menu_item() {\n add_submenu_page(\n 'edit.php?post_type=mycptype',\n 'Bulk Update',\n 'Bulk Update',\n 'edit_others_posts',\n // https://developer.wordpress.org/reference/files/wp-admin/admin-post.php/\n admin_url( 'admin-post.php?action=mycptype_bulk_update' ),\n );\n}\n\nadd_action( 'admin_menu', 'wpse_382892_menu_item' );\n\n/**\n * Handle the bulk update request.\n *\n * @see wpse_382892_menu_item()\n */\nfunction wpse_382892_bulk_update() {\n if ( ! current_user_can( 'edit_others_posts' ) ) {\n wp_die( 'You do not have permission to do this.' );\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n );\n\n $the_query = new WP_Query( $args );\n\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n\n $testa = get_field('br_type');\n $testb = get_field('br_category');\n\n if ($testa === 'Apples') {\n update_field('br_featured', '0', get_the_ID());\n }\n }\n\n wp_die( 'Bulk update completed!', 'Bulk Update', [\n 'back_link' => true,\n ]);\n}\n\n// This custom action is fired in wp-admin/admin-post.php\nadd_action( 'admin_post_mycptype_bulk_update', 'wpse_382892_bulk_update' );\n</code></pre>\n<p>Note that you don't actually need the menu item for the second function to still be usuable - you can trigger the action manually just by loading the action URL in your browser:</p>\n<p><code>https://example.com/wp-admin/admin-post.php?action=mycptype_bulk_update</code></p>\n"
},
{
"answer_id": 406234,
"author": "Irfan",
"author_id": 193019,
"author_profile": "https://wordpress.stackexchange.com/users/193019",
"pm_score": 1,
"selected": false,
"text": "<p>When you access <code>get_field()</code> from functions.php it will load before ACF has initialized. You can solve it by wrapping the code inside <code>acf/init</code> hook.\nUpdate the code as follows.</p>\n<p>Hope it helps @JoaMika</p>\n<pre><code>add_action('acf/init', 'custom_code');\n\nfunction custom_code() {\n $args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'mycptype'\n );\n $the_query = new WP_Query($args);\n if ($the_query->have_posts()) :\n while ($the_query->have_posts()) : $the_query->the_post();\n $testa = get_field('br_type');\n $testb = get_field('br_category');\n if ($testa === 'Apples') {\n update_field('br_featured', '0', get_the_ID());\n }\n endwhile;\n wp_reset_postdata();\n endif;\n}\n</code></pre>\n"
}
] | 2021/02/05 | [
"https://wordpress.stackexchange.com/questions/382892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this function which works great in case anyone wants to bulk update custom fields for custom post types (just change parameters as necessary).
```
$args=array(
'posts_per_page' => -1,
'post_type' => 'mycptype'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$testa = get_field('br_type');
$testb = get_field('br_category');
if ($testa === 'Apples') {
update_field('br_featured', '0', get_the_ID());
}
endwhile;
wp_reset_postdata();
endif;
```
How to use:
1. Insert the code inside your functions.php and refresh your website ONCE
2. Then don't forget to delete the code.
The problem I am having is that even if the function works as expected and updates the value of the custom field, I need to go inside each custom post type and click on the button "Update" for the changes to take effect.
This is because the ACF field has been registered after the custom post types were published.
Is there a workaround for not going inside each post and click update? | When you access `get_field()` from functions.php it will load before ACF has initialized. You can solve it by wrapping the code inside `acf/init` hook.
Update the code as follows.
Hope it helps @JoaMika
```
add_action('acf/init', 'custom_code');
function custom_code() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'mycptype'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
while ($the_query->have_posts()) : $the_query->the_post();
$testa = get_field('br_type');
$testb = get_field('br_category');
if ($testa === 'Apples') {
update_field('br_featured', '0', get_the_ID());
}
endwhile;
wp_reset_postdata();
endif;
}
``` |
382,898 | <p>I'm using the following loop to pull my posts, the a is wrapped around the div to make sure it links to the post when clicked.</p>
<pre><code> <?php $query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 6
));
while ($query->have_posts()) : $query->the_post(); ?>
<div class="carousel-cell" data-flickity-bg-lazyload="<?php the_field('banner_afbeelding'); ?>">
<a href="<?php the_permalink();?>">
<div class="inner-wrap">
<div class="box">
<div class="inner">
<h3><?php the_title(); ?></h3>
<h4><?php the_category(''); ?></h4>
</div>
</div>
</div>
</a>
</div>
</code></pre>
<p>This is the HTML output I'm getting:</p>
<pre><code><div class="carousel-cell is-selected flickity-bg-lazyloaded" style="position: absolute; left: 0%; background-image: url(&quot;https://puranenschilder-totaalonderhoud.nl/wp-content/uploads/2021/02/2-bas-H.jpg&quot;);">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="inner-wrap">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="box">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="inner"><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<h3><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/">Rozengracht</a></h3>
<h4>
<ul class="post-categories">
<li>
<a href="https://puranenschilder-totaalonderhoud.nl/category/buitenschilderwerk/" rel="category tag">Buitenschilderwerk</a>
</li>
</ul>
</h4>
</div>
</div>
</div>
</code></pre>
| [
{
"answer_id": 382906,
"author": "Akash Singh",
"author_id": 191397,
"author_profile": "https://wordpress.stackexchange.com/users/191397",
"pm_score": -1,
"selected": false,
"text": "<p>if you use <strong>get_permalink()</strong> then you need to user echo and <strong>the_permalink()</strong> you did not use to echo.</p>\n<pre><code><?php the_permalink(); ?>\n<?php echo get_permalink(); ?>\n</code></pre>\n<p>code:-</p>\n<pre><code><div class="carousel-cell" data-flickity-bg-lazyload="<?php the_field('banner_afbeelding'); ?>">\n <a href="<?php the_permalink();?>">\n <div class="inner-wrap">\n <div class="box">\n <div class="inner">\n <h3><?php the_title(); ?></h3>\n <h4><?php the_category(''); ?></h4>\n </div>\n </div>\n </div>\n </a>\n</div>\n</code></pre>\n"
},
{
"answer_id": 382946,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>This is happening because <code>the_category()</code> outputs a list of categories, <em>with links</em>. So it's outputting its own <code><a></code> tags, and you cannot put <code><a></code> tags inside other <code><a></code> tags. It's not valid HTML.</p>\n<p>What you're seeing is the browser's attempt to produce valid HTML based on invalid markup. HTML is very resilient, and invalid markup will not cause it to crash. THe browser just does things like this. If you look at the raw HTML returned for the page in the Network tabs of the browser's developer tools you will see what HTML your template actually created.</p>\n<p>If you want to output the list of a post's categories without links, you will need to do something like this:</p>\n"
}
] | 2021/02/05 | [
"https://wordpress.stackexchange.com/questions/382898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201499/"
] | I'm using the following loop to pull my posts, the a is wrapped around the div to make sure it links to the post when clicked.
```
<?php $query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 6
));
while ($query->have_posts()) : $query->the_post(); ?>
<div class="carousel-cell" data-flickity-bg-lazyload="<?php the_field('banner_afbeelding'); ?>">
<a href="<?php the_permalink();?>">
<div class="inner-wrap">
<div class="box">
<div class="inner">
<h3><?php the_title(); ?></h3>
<h4><?php the_category(''); ?></h4>
</div>
</div>
</div>
</a>
</div>
```
This is the HTML output I'm getting:
```
<div class="carousel-cell is-selected flickity-bg-lazyloaded" style="position: absolute; left: 0%; background-image: url("https://puranenschilder-totaalonderhoud.nl/wp-content/uploads/2021/02/2-bas-H.jpg");">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="inner-wrap">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="box">
<a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<div class="inner"><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a>
<h3><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/"></a><a href="https://puranenschilder-totaalonderhoud.nl/rozengracht/">Rozengracht</a></h3>
<h4>
<ul class="post-categories">
<li>
<a href="https://puranenschilder-totaalonderhoud.nl/category/buitenschilderwerk/" rel="category tag">Buitenschilderwerk</a>
</li>
</ul>
</h4>
</div>
</div>
</div>
``` | This is happening because `the_category()` outputs a list of categories, *with links*. So it's outputting its own `<a>` tags, and you cannot put `<a>` tags inside other `<a>` tags. It's not valid HTML.
What you're seeing is the browser's attempt to produce valid HTML based on invalid markup. HTML is very resilient, and invalid markup will not cause it to crash. THe browser just does things like this. If you look at the raw HTML returned for the page in the Network tabs of the browser's developer tools you will see what HTML your template actually created.
If you want to output the list of a post's categories without links, you will need to do something like this: |
382,942 | <p>I client of mine recently upgraded a very basic WordPress install to version 5.6.1. While the update seemed to go well, right at the very end the site died with an error that read something like this; identifying details altered for privacy:</p>
<pre><code>[Sat Feb 06 12:12:11.123456 2021] [fcgid:warn] [pid 128] [client 12.34.56.78:12345] mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Class 'WP_Site_Health' not found in /var/www/html/wp-includes/rest-api.php:321
</code></pre>
<p>I have fairly deep experience debugging WordPress and related PHP sites, but this was baffling. According to them they disabled all of the plug-ins and themes and even downloaded a clean archive of WordPress 5.6.1 and did the basic manual upgrade process of retaining the <code>wp-config.php</code>, <code>.htaccess</code> and related user specific uploads in the <code>wp-content</code> directory and the error still shows up.</p>
<p>I’ve read advice like <a href="https://wordpress.org/support/topic/wordpress-update-to-5-6-crashed-my-site/" rel="nofollow noreferrer">what was posted here on the WordPress forums</a> that basically state one should restore from a backup and try again, but find that advice to be a classic “<a href="https://en.wikipedia.org/wiki/Hail_Mary_pass" rel="nofollow noreferrer">Hail Mary</a>” play; sometimes it works and other times you are just left in the same exact position as before but with new file modification dates.</p>
<p>So given that the class <code>WP_Site_Health</code> and the file <code>wp-includes/rest-api.php</code> are both items that exist in core WordPress, what can be done to quickly patch the system to get it working again?</p>
<hr />
<p>P.S.: And to truly confirm the files were fine, I did the following:</p>
<ul>
<li>Created a Tar/Gzip archive of the whole WordPress install — including all <code>wp-content</code> items — and downloaded it to my desktop.</li>
<li>Then I decompressed the archive, went into that directory and ran <code>git init</code> inside of it to create a Git repo.</li>
<li>I left the site as-is as the <code>master</code> branch and then created a new branch called <code>test</code>.</li>
<li>In that test branch, I manually downloaded a 100% WordPress 5.6.1 install from WordPress directly, manually copied the clean files into the new branch and committed them.</li>
<li>Then I ran local <code>git diff master..test</code> to see what files were changed between the source <code>master</code> branch and the <code>test</code> branch. The diff said the files from the server versus clean WordPress 5.6.1 files were 100% the same; what was on the server is 100% the same as a clean WordPress install.</li>
</ul>
| [
{
"answer_id": 382944,
"author": "Giacomo1968",
"author_id": 52852,
"author_profile": "https://wordpress.stackexchange.com/users/52852",
"pm_score": -1,
"selected": true,
"text": "<h2>The solution is to add a PHP <code>class_exists</code> check around line 321 in <code>wp-includes/rest-api.php</code>.</h2>\n<p>While patching WordPress core like this makes me wince, the check I added just confirms if <code>WP_Site_Health</code> exists in the code WordPress loaded to render itself. Here is what exists around line 321 in core WordPress code for <code>wp-includes/rest-api.php</code>:</p>\n<pre><code>// Site Health.\n$site_health = WP_Site_Health::get_instance();\n$controller = new WP_REST_Site_Health_Controller( $site_health );\n$controller->register_routes();\n</code></pre>\n<p>Here is what I adjusted around there to get the site back up and running:</p>\n<pre><code>// Site Health.\nif ( ! class_exists( 'WP_Site_Health' ) ) {\n require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';\n}\n$site_health = WP_Site_Health::get_instance();\n$controller = new WP_REST_Site_Health_Controller( $site_health );\n$controller->register_routes();\n</code></pre>\n<p>The logic is pretty simple: Using the PHP function <a href=\"https://www.php.net/manual/en/function.class-exists.php\" rel=\"nofollow noreferrer\"><code>class_exists</code></a>, the code simply checks <code>WP_Site_Health</code> exists or not. If it doesn’t exist, then WordPress loads it using <code>require_once</code> and moves on. If it does exists? The condition fails that’s that.</p>\n<p>It still is baffling why — if you look at <a href=\"https://github.com/WordPress/WordPress/blob/dbfbf5501a2ced1bebaf47b4eebfb79a98e01f1b/wp-settings.php\" rel=\"nofollow noreferrer\"><code>wp-settings.php</code></a> which bootstraps all of the classes when WordPress is loaded — <code>rest-api.php</code> loads around line 240, but makes a call to <code>WP_Site_Health</code> around line 539. Why would <code>rest-api.php</code> — which is loaded first — making a call to <code>WP_Site_Health</code> which only loads waaay later on in the <code>require</code> list?</p>\n<p>Anyway, this is not pretty but it works and should be harmless to add to quickly get a site up and running again.</p>\n"
},
{
"answer_id": 391303,
"author": "Alexandre Schmidt",
"author_id": 133448,
"author_profile": "https://wordpress.stackexchange.com/users/133448",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at what point in your code you're making calls to the WordPress REST API or any other code which makes use of <code>WP_Site_Health</code>.</p>\n<p>If you're making calls in your <code><theme>/functions.php</code> file, for example, it won't work because <code>functions.php</code> is included before <code>class WP_Site_Health</code> in <code>wp-settings.php</code>.</p>\n<p>See <code>wp-settings.php</code> code (WordPress 5.7.2):</p>\n<pre><code>// Load the functions for the active theme, for both parent and child theme if applicable.\nforeach ( wp_get_active_and_valid_themes() as $theme ) {\n if ( file_exists( $theme . '/functions.php' ) ) {\n include $theme . '/functions.php';\n }\n}\nunset( $theme );\n\n/**\n * Fires after the theme is loaded.\n *\n * @since 3.0.0\n */\ndo_action( 'after_setup_theme' );\n\n// Create an instance of WP_Site_Health so that Cron events may fire.\nif ( ! class_exists( 'WP_Site_Health' ) ) {\n require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';\n}\nWP_Site_Health::get_instance();\n</code></pre>\n<p>Despite the lack of elegance, one thing you can do about it is to ensure the class is loaded by copying part of the code from <code>wp-settings.php</code> and pasting it before your code. For example, in your <code><theme>/functions.php</code>, you can do this:</p>\n<pre><code>if ( ! class_exists( 'WP_Site_Health' ) ) {\n require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';\n}\nWP_Site_Health::get_instance();\n\n---8<---\ncode depending on WP_Site_Health\n---8<---\n</code></pre>\n"
}
] | 2021/02/07 | [
"https://wordpress.stackexchange.com/questions/382942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52852/"
] | I client of mine recently upgraded a very basic WordPress install to version 5.6.1. While the update seemed to go well, right at the very end the site died with an error that read something like this; identifying details altered for privacy:
```
[Sat Feb 06 12:12:11.123456 2021] [fcgid:warn] [pid 128] [client 12.34.56.78:12345] mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Class 'WP_Site_Health' not found in /var/www/html/wp-includes/rest-api.php:321
```
I have fairly deep experience debugging WordPress and related PHP sites, but this was baffling. According to them they disabled all of the plug-ins and themes and even downloaded a clean archive of WordPress 5.6.1 and did the basic manual upgrade process of retaining the `wp-config.php`, `.htaccess` and related user specific uploads in the `wp-content` directory and the error still shows up.
I’ve read advice like [what was posted here on the WordPress forums](https://wordpress.org/support/topic/wordpress-update-to-5-6-crashed-my-site/) that basically state one should restore from a backup and try again, but find that advice to be a classic “[Hail Mary](https://en.wikipedia.org/wiki/Hail_Mary_pass)” play; sometimes it works and other times you are just left in the same exact position as before but with new file modification dates.
So given that the class `WP_Site_Health` and the file `wp-includes/rest-api.php` are both items that exist in core WordPress, what can be done to quickly patch the system to get it working again?
---
P.S.: And to truly confirm the files were fine, I did the following:
* Created a Tar/Gzip archive of the whole WordPress install — including all `wp-content` items — and downloaded it to my desktop.
* Then I decompressed the archive, went into that directory and ran `git init` inside of it to create a Git repo.
* I left the site as-is as the `master` branch and then created a new branch called `test`.
* In that test branch, I manually downloaded a 100% WordPress 5.6.1 install from WordPress directly, manually copied the clean files into the new branch and committed them.
* Then I ran local `git diff master..test` to see what files were changed between the source `master` branch and the `test` branch. The diff said the files from the server versus clean WordPress 5.6.1 files were 100% the same; what was on the server is 100% the same as a clean WordPress install. | The solution is to add a PHP `class_exists` check around line 321 in `wp-includes/rest-api.php`.
------------------------------------------------------------------------------------------------
While patching WordPress core like this makes me wince, the check I added just confirms if `WP_Site_Health` exists in the code WordPress loaded to render itself. Here is what exists around line 321 in core WordPress code for `wp-includes/rest-api.php`:
```
// Site Health.
$site_health = WP_Site_Health::get_instance();
$controller = new WP_REST_Site_Health_Controller( $site_health );
$controller->register_routes();
```
Here is what I adjusted around there to get the site back up and running:
```
// Site Health.
if ( ! class_exists( 'WP_Site_Health' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
}
$site_health = WP_Site_Health::get_instance();
$controller = new WP_REST_Site_Health_Controller( $site_health );
$controller->register_routes();
```
The logic is pretty simple: Using the PHP function [`class_exists`](https://www.php.net/manual/en/function.class-exists.php), the code simply checks `WP_Site_Health` exists or not. If it doesn’t exist, then WordPress loads it using `require_once` and moves on. If it does exists? The condition fails that’s that.
It still is baffling why — if you look at [`wp-settings.php`](https://github.com/WordPress/WordPress/blob/dbfbf5501a2ced1bebaf47b4eebfb79a98e01f1b/wp-settings.php) which bootstraps all of the classes when WordPress is loaded — `rest-api.php` loads around line 240, but makes a call to `WP_Site_Health` around line 539. Why would `rest-api.php` — which is loaded first — making a call to `WP_Site_Health` which only loads waaay later on in the `require` list?
Anyway, this is not pretty but it works and should be harmless to add to quickly get a site up and running again. |
382,957 | <p>In WordPress, is it possible to hide a HTML element by class or ID with php?</p>
<p>I've used css rule <code>display: none;</code> but this is easily worked around...</p>
<p>I have tried the following via <code>functions.php</code> but to no avail:</p>
<pre><code>function MyTestFunction() {
obj = document.getElementById("div-or-class-id");
obj.style.visibility = "hidden";
console.log(obj.id);
console.log(obj);
}
}
</code></pre>
<p>Basically I need to <strong>hide a HTML element for good</strong> without anyone being able to alter the code via browser inspector. I'd like to prevent having to create a child theme and mess with templates too.</p>
| [
{
"answer_id": 382977,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 2,
"selected": false,
"text": "<p>As per our discussion in the comments, all you really need to do is <code>.remove()</code> the element. The following is the approach I'd take. First I'd check to make sure the element exists before attempting to remove it. If it's there, then run jQuery's <code>.remove()</code>.</p>\n<pre><code>if( $( '#elementID' ).length > 0 ) {\n $( '#elementID' ).remove();\n}\n</code></pre>\n<p>This can't be reversed via developer tools because it will comprehensively remove the element from the DOM. Now, if someone wants to open the developer tools and add something back into the DOM manually they can do that, but that's kinda what developer tools are for right. To be able to identify this element, copy it and re-add it though, they'd have to be pretty quick.</p>\n<p>I know you don't want to add to a child theme or whatever so you'll have to get this script into the flow somehow, not sure how you want to go about doing that.</p>\n"
},
{
"answer_id": 393549,
"author": "Iwalewa Fawaz",
"author_id": 210433,
"author_profile": "https://wordpress.stackexchange.com/users/210433",
"pm_score": 0,
"selected": false,
"text": "<p>CSS won't work to hiding an element only if you are using the wrong selector or perhaps CSS can't locate the element using the selector you've chosen. What works for me in this type of situation is to inspect elements and copy the CSS selector.\nThis will help you copy the selector\n<a href=\"https://learn.akamai.com/en-us/webhelp/mpulse/mpulse-help/GUID-2CDEED41-3B26-45B1-9896-85B17F8E7901.html\" rel=\"nofollow noreferrer\">https://learn.akamai.com/en-us/webhelp/mpulse/mpulse-help/GUID-2CDEED41-3B26-45B1-9896-85B17F8E7901.html</a></p>\n"
}
] | 2021/02/07 | [
"https://wordpress.stackexchange.com/questions/382957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167038/"
] | In WordPress, is it possible to hide a HTML element by class or ID with php?
I've used css rule `display: none;` but this is easily worked around...
I have tried the following via `functions.php` but to no avail:
```
function MyTestFunction() {
obj = document.getElementById("div-or-class-id");
obj.style.visibility = "hidden";
console.log(obj.id);
console.log(obj);
}
}
```
Basically I need to **hide a HTML element for good** without anyone being able to alter the code via browser inspector. I'd like to prevent having to create a child theme and mess with templates too. | As per our discussion in the comments, all you really need to do is `.remove()` the element. The following is the approach I'd take. First I'd check to make sure the element exists before attempting to remove it. If it's there, then run jQuery's `.remove()`.
```
if( $( '#elementID' ).length > 0 ) {
$( '#elementID' ).remove();
}
```
This can't be reversed via developer tools because it will comprehensively remove the element from the DOM. Now, if someone wants to open the developer tools and add something back into the DOM manually they can do that, but that's kinda what developer tools are for right. To be able to identify this element, copy it and re-add it though, they'd have to be pretty quick.
I know you don't want to add to a child theme or whatever so you'll have to get this script into the flow somehow, not sure how you want to go about doing that. |
383,090 | <p><strong>HI</strong>
I use plugin: Advanced Custom Fields</p>
<p>How can I show only 5 posts from the relationship?</p>
<p>This is the code:</p>
<pre><code><?php $c_lists = get_field( 'c_lists' ); ?>
<?php if ( $c_lists ) : ?>
<?php foreach ( $c_lists as $post_ids ) : ?>
<a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
<?php endforeach; ?>
<?php endif; ?>
</code></pre>
<p>Any help, please</p>
| [
{
"answer_id": 383091,
"author": "km onur",
"author_id": 198965,
"author_profile": "https://wordpress.stackexchange.com/users/198965",
"pm_score": 0,
"selected": false,
"text": "<p>You can follow such a path</p>\n \n<pre><code><?php if ( $c_lists ) : ?>\n <?php $max = 5; $start = 0; foreach ( $c_lists as $post_ids ) : \n $start++; \n if( $start >= $max ) break;\n ?>\n <a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>\n <?php endforeach; ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 383092,
"author": "Buttered_Toast",
"author_id": 192133,
"author_profile": "https://wordpress.stackexchange.com/users/192133",
"pm_score": 2,
"selected": true,
"text": "<p>You could use the key from the foreach</p>\n<pre><code><?php\n$c_lists = get_field('c_lists');\nif ($c_lists) :\n foreach ($c_lists as $key => $post_ids) :\n if ($key > 4) break;\n?>\n<a href="<?= get_permalink($post_ids); ?>"><?= get_the_title($post_ids); ?></a>\n<?php\n endforeach;\nendif;\n?>\n</code></pre>\n"
},
{
"answer_id": 383122,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another option: you can <a href=\"https://www.php.net/manual/en/function.array-slice.php\" rel=\"nofollow noreferrer\">array_slice</a> the array you pass into the foreach</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php $c_lists = get_field( 'c_lists' ); ?>\n<?php if ( $c_lists ) : ?>\n <?php foreach ( $c_lists as array_slice( $post_ids, 0, 5 ) ) : ?>\n <a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>\n <?php endforeach; ?>\n<?php endif; ?>\n</code></pre>\n"
}
] | 2021/02/09 | [
"https://wordpress.stackexchange.com/questions/383090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201627/"
] | **HI**
I use plugin: Advanced Custom Fields
How can I show only 5 posts from the relationship?
This is the code:
```
<?php $c_lists = get_field( 'c_lists' ); ?>
<?php if ( $c_lists ) : ?>
<?php foreach ( $c_lists as $post_ids ) : ?>
<a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
<?php endforeach; ?>
<?php endif; ?>
```
Any help, please | You could use the key from the foreach
```
<?php
$c_lists = get_field('c_lists');
if ($c_lists) :
foreach ($c_lists as $key => $post_ids) :
if ($key > 4) break;
?>
<a href="<?= get_permalink($post_ids); ?>"><?= get_the_title($post_ids); ?></a>
<?php
endforeach;
endif;
?>
``` |
383,093 | <p>I have a block in which I'd like to display a link based on the site url. So for example, when the user enters "Futuristic", the link will display as <a href="https://my-site.com/futuristic/" rel="nofollow noreferrer">https://my-site.com/futuristic/</a></p>
<p>I've looked at <a href="https://developer.wordpress.org/rest-api/reference/settings/" rel="nofollow noreferrer">REST API <code>/settings/</code> endpoint</a>, which is supposed to include a <strong>url</strong> field, but it doesn't (at least on the two different sites I tried). Perhaps this is because I've got WP set up as multisite. There still should be a way to access the current site's url I'm sure.</p>
<p>I've looked into what <code>wp.data.select()</code> can provide in the various namespaces, but I don't see anything that would include the site url.</p>
<p>I tried looking at output of <code>wp.data.select('core').getSite()</code> (see <a href="https://wordpress.stackexchange.com/a/383114/2044">Hardeep's suggestion</a>), but mine has no url property and looks like this:</p>
<pre><code>{
date_format: "F j, Y"
default_category: 1
default_comment_status: "open"
default_ping_status: "open"
default_post_format: "0"
description: ""
language: ""
posts_per_page: 10
start_of_week: 0
time_format: "g:i a"
timezone: "America/New_York"
title: "The Name of My Site"
use_smilies: true
}
</code></pre>
<p>I suspect the difference has to do with Multisite being enabled, but not sure.</p>
| [
{
"answer_id": 383114,
"author": "Hardeep Asrani",
"author_id": 33233,
"author_profile": "https://wordpress.stackexchange.com/users/33233",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>wp_localize_script</code> to pass anything you want, including site URL, to the editor as a global variable:</p>\n<pre><code>wp_localize_script(\n 'script_name',\n 'my_data',\n [\n 'siteUrl' => get_site_url()\n ]\n);\n</code></pre>\n<p>And then you can get it in the editor from <code>window.my_data.siteUrl</code> variable. Here <code>script_name</code> will be the script that you're enqueuing to the editor.</p>\n<p>If you want to use the Data API, you can use <code>wp.data.select( 'core' ).getSite();</code> and once the promise has resolved, you can use the URL property.</p>\n<p><a href=\"https://i.stack.imgur.com/olIav.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/olIav.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 383170,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>Perhaps this is because I've got WP set up as multisite.</p>\n</blockquote>\n<p>Yes, that's right, WordPress disables the <code>siteurl</code> (and also <code>admin_email</code>) settings on a Multisite — see <a href=\"https://developer.wordpress.org/reference/functions/register_initial_settings/\" rel=\"nofollow noreferrer\"><code>register_initial_settings()</code></a> for the source.</p>\n<p>And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the <code>url</code>/<code>siteurl</code> setting, which for example, would go in the theme's <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// I copied this from the source..\nregister_setting(\n 'general',\n 'siteurl',\n array(\n 'show_in_rest' => array(\n 'name' => 'url',\n 'schema' => array(\n 'format' => 'uri',\n ),\n ),\n 'type' => 'string',\n 'description' => __( 'Site URL.' ),\n )\n);\n</code></pre>\n<p>Tried & tested working with WordPress 5.6.1 Multisite.</p>\n<p>And also, <code>wp.data.select( 'core' ).getSite()</code> uses the Settings endpoint, so it's normal that the <code>url</code> property is missing by default on a Multisite.</p>\n<p>Apart from that, <code>getSite()</code> caches the API results, so you'd need to <em>reload</em> the post editing screen/page in order for <code>getSite()</code> to give you the correct result, i.e. with the <code>url</code> property.</p>\n"
}
] | 2021/02/09 | [
"https://wordpress.stackexchange.com/questions/383093",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2044/"
] | I have a block in which I'd like to display a link based on the site url. So for example, when the user enters "Futuristic", the link will display as <https://my-site.com/futuristic/>
I've looked at [REST API `/settings/` endpoint](https://developer.wordpress.org/rest-api/reference/settings/), which is supposed to include a **url** field, but it doesn't (at least on the two different sites I tried). Perhaps this is because I've got WP set up as multisite. There still should be a way to access the current site's url I'm sure.
I've looked into what `wp.data.select()` can provide in the various namespaces, but I don't see anything that would include the site url.
I tried looking at output of `wp.data.select('core').getSite()` (see [Hardeep's suggestion](https://wordpress.stackexchange.com/a/383114/2044)), but mine has no url property and looks like this:
```
{
date_format: "F j, Y"
default_category: 1
default_comment_status: "open"
default_ping_status: "open"
default_post_format: "0"
description: ""
language: ""
posts_per_page: 10
start_of_week: 0
time_format: "g:i a"
timezone: "America/New_York"
title: "The Name of My Site"
use_smilies: true
}
```
I suspect the difference has to do with Multisite being enabled, but not sure. | >
> Perhaps this is because I've got WP set up as multisite.
>
>
>
Yes, that's right, WordPress disables the `siteurl` (and also `admin_email`) settings on a Multisite — see [`register_initial_settings()`](https://developer.wordpress.org/reference/functions/register_initial_settings/) for the source.
And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the `url`/`siteurl` setting, which for example, would go in the theme's `functions.php` file:
```php
// I copied this from the source..
register_setting(
'general',
'siteurl',
array(
'show_in_rest' => array(
'name' => 'url',
'schema' => array(
'format' => 'uri',
),
),
'type' => 'string',
'description' => __( 'Site URL.' ),
)
);
```
Tried & tested working with WordPress 5.6.1 Multisite.
And also, `wp.data.select( 'core' ).getSite()` uses the Settings endpoint, so it's normal that the `url` property is missing by default on a Multisite.
Apart from that, `getSite()` caches the API results, so you'd need to *reload* the post editing screen/page in order for `getSite()` to give you the correct result, i.e. with the `url` property. |
383,118 | <p>I am trying to run a function only on one page or other pages in the future if I so desire. But I dont want to run it site wide. I need help on how to put the if is_page or if is_single.</p>
<pre class="lang-php prettyprint-override"><code>// disable auto-formatting
function my_formatter($content) {
$new_content = '';
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$new_content .= $matches[1];
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);
</code></pre>
<p>Much appreciate the help.</p>
<p>Thanks</p>
| [
{
"answer_id": 383114,
"author": "Hardeep Asrani",
"author_id": 33233,
"author_profile": "https://wordpress.stackexchange.com/users/33233",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>wp_localize_script</code> to pass anything you want, including site URL, to the editor as a global variable:</p>\n<pre><code>wp_localize_script(\n 'script_name',\n 'my_data',\n [\n 'siteUrl' => get_site_url()\n ]\n);\n</code></pre>\n<p>And then you can get it in the editor from <code>window.my_data.siteUrl</code> variable. Here <code>script_name</code> will be the script that you're enqueuing to the editor.</p>\n<p>If you want to use the Data API, you can use <code>wp.data.select( 'core' ).getSite();</code> and once the promise has resolved, you can use the URL property.</p>\n<p><a href=\"https://i.stack.imgur.com/olIav.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/olIav.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 383170,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>Perhaps this is because I've got WP set up as multisite.</p>\n</blockquote>\n<p>Yes, that's right, WordPress disables the <code>siteurl</code> (and also <code>admin_email</code>) settings on a Multisite — see <a href=\"https://developer.wordpress.org/reference/functions/register_initial_settings/\" rel=\"nofollow noreferrer\"><code>register_initial_settings()</code></a> for the source.</p>\n<p>And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the <code>url</code>/<code>siteurl</code> setting, which for example, would go in the theme's <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// I copied this from the source..\nregister_setting(\n 'general',\n 'siteurl',\n array(\n 'show_in_rest' => array(\n 'name' => 'url',\n 'schema' => array(\n 'format' => 'uri',\n ),\n ),\n 'type' => 'string',\n 'description' => __( 'Site URL.' ),\n )\n);\n</code></pre>\n<p>Tried & tested working with WordPress 5.6.1 Multisite.</p>\n<p>And also, <code>wp.data.select( 'core' ).getSite()</code> uses the Settings endpoint, so it's normal that the <code>url</code> property is missing by default on a Multisite.</p>\n<p>Apart from that, <code>getSite()</code> caches the API results, so you'd need to <em>reload</em> the post editing screen/page in order for <code>getSite()</code> to give you the correct result, i.e. with the <code>url</code> property.</p>\n"
}
] | 2021/02/09 | [
"https://wordpress.stackexchange.com/questions/383118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201696/"
] | I am trying to run a function only on one page or other pages in the future if I so desire. But I dont want to run it site wide. I need help on how to put the if is\_page or if is\_single.
```php
// disable auto-formatting
function my_formatter($content) {
$new_content = '';
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$new_content .= $matches[1];
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);
```
Much appreciate the help.
Thanks | >
> Perhaps this is because I've got WP set up as multisite.
>
>
>
Yes, that's right, WordPress disables the `siteurl` (and also `admin_email`) settings on a Multisite — see [`register_initial_settings()`](https://developer.wordpress.org/reference/functions/register_initial_settings/) for the source.
And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the `url`/`siteurl` setting, which for example, would go in the theme's `functions.php` file:
```php
// I copied this from the source..
register_setting(
'general',
'siteurl',
array(
'show_in_rest' => array(
'name' => 'url',
'schema' => array(
'format' => 'uri',
),
),
'type' => 'string',
'description' => __( 'Site URL.' ),
)
);
```
Tried & tested working with WordPress 5.6.1 Multisite.
And also, `wp.data.select( 'core' ).getSite()` uses the Settings endpoint, so it's normal that the `url` property is missing by default on a Multisite.
Apart from that, `getSite()` caches the API results, so you'd need to *reload* the post editing screen/page in order for `getSite()` to give you the correct result, i.e. with the `url` property. |
383,125 | <p>I am creating a dedicated WordPress ecommerce website without using WooCommerce for myself. I created the custom post type called 'products' but now I am stuck on how to add specific terms like SKU, price, variations, short description, and related products section in it.</p>
<p>Can you please help me know. I don't know if I can specifically make sections to update such terms in the product post type.</p>
| [
{
"answer_id": 383114,
"author": "Hardeep Asrani",
"author_id": 33233,
"author_profile": "https://wordpress.stackexchange.com/users/33233",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>wp_localize_script</code> to pass anything you want, including site URL, to the editor as a global variable:</p>\n<pre><code>wp_localize_script(\n 'script_name',\n 'my_data',\n [\n 'siteUrl' => get_site_url()\n ]\n);\n</code></pre>\n<p>And then you can get it in the editor from <code>window.my_data.siteUrl</code> variable. Here <code>script_name</code> will be the script that you're enqueuing to the editor.</p>\n<p>If you want to use the Data API, you can use <code>wp.data.select( 'core' ).getSite();</code> and once the promise has resolved, you can use the URL property.</p>\n<p><a href=\"https://i.stack.imgur.com/olIav.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/olIav.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 383170,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>Perhaps this is because I've got WP set up as multisite.</p>\n</blockquote>\n<p>Yes, that's right, WordPress disables the <code>siteurl</code> (and also <code>admin_email</code>) settings on a Multisite — see <a href=\"https://developer.wordpress.org/reference/functions/register_initial_settings/\" rel=\"nofollow noreferrer\"><code>register_initial_settings()</code></a> for the source.</p>\n<p>And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the <code>url</code>/<code>siteurl</code> setting, which for example, would go in the theme's <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// I copied this from the source..\nregister_setting(\n 'general',\n 'siteurl',\n array(\n 'show_in_rest' => array(\n 'name' => 'url',\n 'schema' => array(\n 'format' => 'uri',\n ),\n ),\n 'type' => 'string',\n 'description' => __( 'Site URL.' ),\n )\n);\n</code></pre>\n<p>Tried & tested working with WordPress 5.6.1 Multisite.</p>\n<p>And also, <code>wp.data.select( 'core' ).getSite()</code> uses the Settings endpoint, so it's normal that the <code>url</code> property is missing by default on a Multisite.</p>\n<p>Apart from that, <code>getSite()</code> caches the API results, so you'd need to <em>reload</em> the post editing screen/page in order for <code>getSite()</code> to give you the correct result, i.e. with the <code>url</code> property.</p>\n"
}
] | 2021/02/10 | [
"https://wordpress.stackexchange.com/questions/383125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201713/"
] | I am creating a dedicated WordPress ecommerce website without using WooCommerce for myself. I created the custom post type called 'products' but now I am stuck on how to add specific terms like SKU, price, variations, short description, and related products section in it.
Can you please help me know. I don't know if I can specifically make sections to update such terms in the product post type. | >
> Perhaps this is because I've got WP set up as multisite.
>
>
>
Yes, that's right, WordPress disables the `siteurl` (and also `admin_email`) settings on a Multisite — see [`register_initial_settings()`](https://developer.wordpress.org/reference/functions/register_initial_settings/) for the source.
And I don't know why they disable those (two) settings, but you can explicitly enable them like so for the `url`/`siteurl` setting, which for example, would go in the theme's `functions.php` file:
```php
// I copied this from the source..
register_setting(
'general',
'siteurl',
array(
'show_in_rest' => array(
'name' => 'url',
'schema' => array(
'format' => 'uri',
),
),
'type' => 'string',
'description' => __( 'Site URL.' ),
)
);
```
Tried & tested working with WordPress 5.6.1 Multisite.
And also, `wp.data.select( 'core' ).getSite()` uses the Settings endpoint, so it's normal that the `url` property is missing by default on a Multisite.
Apart from that, `getSite()` caches the API results, so you'd need to *reload* the post editing screen/page in order for `getSite()` to give you the correct result, i.e. with the `url` property. |
383,176 | <p>I'm using React select so that I can create a block option that will give me the option of selecting post types and posts based on the selected post types. Basically, a query block that is in the works in Gutenberg plugin if I'm not mistaken.</p>
<p><a href="https://i.stack.imgur.com/INWlY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/INWlY.png" alt="enter image description here" /></a></p>
<p>Now the thing that's bothering me the most is the fact that I cannot find out the best way to fetch all the posts from the selected options.</p>
<p>For instance I can fetch all the allowed post types like this:</p>
<pre class="lang-js prettyprint-override"><code> const postTypeOptions = useSelect((select) => {
const { getPostTypes } = select('core');
const items = getPostTypes() ?? [];
const data = items.filter((element) => manifest.allowed.postTypes.find((item) => element.slug === item)) ?? [];
return data.map((item) => {
return {
label: item.labels.name,
value: item.slug,
taxonomies: item.taxonomies,
};
}) ?? [];
});
</code></pre>
<p>I'm inside the options part for my block, and I have a manifest.json, where I can filter allowed post types (I don't need all the post types available for me).</p>
<p>What the above code will do is, when I select my block, it will do an API fetch to get all the post types using <code>getPostTypes()</code>, which is in my case equivalent of <code>wp.data.select('core').getPostTypes()</code>.</p>
<p>Now, fetching things like posts can be done using <code>getEntityRecords()</code> like</p>
<pre class="lang-js prettyprint-override"><code>wp.data.select( 'core' ).getEntityRecords( 'postType', 'post' )
</code></pre>
<p>Which will give me posts in my WP. I can replace the <code>post</code> for any custom post type to fetch that custom post type posts.</p>
<p>But the problem is I cannot get all the posts from multiple post types.</p>
<p>The reason is that underneath this, the <code>getEntityRecords</code> is pinging the API endpoint, and there is no way to retrieve all the posts from one endpoint from multiple post types in one go.</p>
<p>So how do I solve this? Create a custom endpoint that will return all the posts based on what I pass as arguments of the endpoint? Doing fetch in the <code>useSelect</code> is not great, as that will trigger every time I touch the block. Using stuff from <code>wp.data.select</code> uses caching and React store to avoid that I guess.</p>
<p>Any pointers into how to achieve that would be super helpful.</p>
| [
{
"answer_id": 383209,
"author": "dingo_d",
"author_id": 58895,
"author_profile": "https://wordpress.stackexchange.com/users/58895",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, after some research I got the result I needed:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Fetch all posts based on the selected postType.\nconst postsOptions = useSelect((select) => {\n const { getEntityRecords } = select('core');\n const { isResolving } = select('core/data');\n\n const postTypeSlugs = [...postType].map((element) => element.value) ?? [];\n\n if (!postTypeSlugs.length) {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n }\n ]\n }\n\n const postList = [];\n\n postTypeSlugs.forEach((postType) => {\n const args = ['postType', postType, {per_page: -1}];\n\n if (!isResolving('core', 'getEntityRecords', args)) {\n const result = getEntityRecords('postType', postType, {per_page: -1});\n\n if (result !== null) {\n postList.push(result);\n }\n }\n });\n\n if (typeof(postList[0]) !== 'undefined') {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n },\n ...postList[0].map((item) => {\n if (isEmpty(item)) {\n return {};\n } else {\n return {\n label: item.title.rendered || '',\n value: item.id || '',\n };\n }\n }),\n ];\n }\n});\n</code></pre>\n<p>Plus a helper from <a href=\"https://stackoverflow.com/a/44586771/629127\">here</a>, that checks if the array is not empty</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isEmpty = a => Array.isArray(a) && a.every(isEmpty);\n</code></pre>\n<p>This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see).</p>\n"
},
{
"answer_id": 401892,
"author": "Kalle",
"author_id": 218476,
"author_profile": "https://wordpress.stackexchange.com/users/218476",
"pm_score": 2,
"selected": false,
"text": "<p>Since while I was doing research I stumbled accross this thread, but it didn't bring me to the result I wanted. So I decided to register here to point out my approach to aquire the need of fetching posts with multiple post types.</p>\n<p>One thing is that the restAPI just does not accept multiple post type natively. I assume thats why getEntityRecords also does not provide that capability.</p>\n<p>1st) I registered a new RestAPI Endpoint to get the ability to query multiple post types when using it:</p>\n<pre><code>//PHP\nadd_action( 'rest_post_query', function( $args, $request ){\n $post_types = $request->get_param( 'type' );\n if( ! empty( $post_types ) ){\n if( is_string( $post_types ) ){\n // filtering posttypes, seperated with comma into an array, ignoring square brackets\n $post_types = explode( ',', str_replace( array( '[', ']') , '', $post_types ) );\n foreach ( $post_types as $key => $post_type ){\n $object = get_post_type_object( $post_type );\n if( ! $object || ! $object->show_in_rest ){\n unset( $post_types[ $key ] );\n }\n }\n }\n $args[ 'post_type' ] = $post_types;\n } else {\n // fallback: no type defined, return post as default\n $args[ 'post_type' ] = 'post';\n }\n return $args;\n}, 10, 2 );\n</code></pre>\n<p>Check your new API endpoint easily by calling it with your browser</p>\n<pre><code>https://*yoururl.com*/wp-json/wp/v2/posts?per_page=10&categories=0&type=posts,page\n</code></pre>\n<p>I don't use the Gutenberg function getEntityRecords anymore to fetch posts. I choose that way performance wise to avoid multiple calls of getEntityRecords.</p>\n<p>2nd) In my Gutenberg block I created a hook to call:</p>\n<pre><code>export default function useFetchPosts( url ) {\n const [data, setData] = useState( null );\n useEffect(() => {\n async function loadData() {\n const response = await fetch( url );\n if(! response.ok ) {\n return false;\n }\n const posts = await response.json();\n setData(posts);\n }\n loadData();\n }, [url]);\n return data;\n}\n</code></pre>\n<p>3rd) to get the posts I just call it like this inside my edit block:</p>\n<pre><code>// parsedCategories and\n// parsedPostTypes have to set and parsed by you before ofcourse ;)\nconst numberposts = 10;\nconst postFields = '&_fields=id,author,link,title,_links';\nconst posts = useFetchPosts( 'https://'+window.location.host+'/wp-json/wp/v2/posts?per_page='+numberposts+'&categories='+parsedCategories+'&_embed=author&type='+parsedPostTypes+'&orderby=date&order=desc'+postFields );\n</code></pre>\n<p>Check out the restAPI reference for available args and parms:\n<a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/</a></p>\n<p>Cheers</p>\n"
}
] | 2021/02/10 | [
"https://wordpress.stackexchange.com/questions/383176",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I'm using React select so that I can create a block option that will give me the option of selecting post types and posts based on the selected post types. Basically, a query block that is in the works in Gutenberg plugin if I'm not mistaken.
[](https://i.stack.imgur.com/INWlY.png)
Now the thing that's bothering me the most is the fact that I cannot find out the best way to fetch all the posts from the selected options.
For instance I can fetch all the allowed post types like this:
```js
const postTypeOptions = useSelect((select) => {
const { getPostTypes } = select('core');
const items = getPostTypes() ?? [];
const data = items.filter((element) => manifest.allowed.postTypes.find((item) => element.slug === item)) ?? [];
return data.map((item) => {
return {
label: item.labels.name,
value: item.slug,
taxonomies: item.taxonomies,
};
}) ?? [];
});
```
I'm inside the options part for my block, and I have a manifest.json, where I can filter allowed post types (I don't need all the post types available for me).
What the above code will do is, when I select my block, it will do an API fetch to get all the post types using `getPostTypes()`, which is in my case equivalent of `wp.data.select('core').getPostTypes()`.
Now, fetching things like posts can be done using `getEntityRecords()` like
```js
wp.data.select( 'core' ).getEntityRecords( 'postType', 'post' )
```
Which will give me posts in my WP. I can replace the `post` for any custom post type to fetch that custom post type posts.
But the problem is I cannot get all the posts from multiple post types.
The reason is that underneath this, the `getEntityRecords` is pinging the API endpoint, and there is no way to retrieve all the posts from one endpoint from multiple post types in one go.
So how do I solve this? Create a custom endpoint that will return all the posts based on what I pass as arguments of the endpoint? Doing fetch in the `useSelect` is not great, as that will trigger every time I touch the block. Using stuff from `wp.data.select` uses caching and React store to avoid that I guess.
Any pointers into how to achieve that would be super helpful. | Ok, after some research I got the result I needed:
```js
// Fetch all posts based on the selected postType.
const postsOptions = useSelect((select) => {
const { getEntityRecords } = select('core');
const { isResolving } = select('core/data');
const postTypeSlugs = [...postType].map((element) => element.value) ?? [];
if (!postTypeSlugs.length) {
return [
{
label: __('No Filter used', 'slug'),
value: '',
}
]
}
const postList = [];
postTypeSlugs.forEach((postType) => {
const args = ['postType', postType, {per_page: -1}];
if (!isResolving('core', 'getEntityRecords', args)) {
const result = getEntityRecords('postType', postType, {per_page: -1});
if (result !== null) {
postList.push(result);
}
}
});
if (typeof(postList[0]) !== 'undefined') {
return [
{
label: __('No Filter used', 'slug'),
value: '',
},
...postList[0].map((item) => {
if (isEmpty(item)) {
return {};
} else {
return {
label: item.title.rendered || '',
value: item.id || '',
};
}
}),
];
}
});
```
Plus a helper from [here](https://stackoverflow.com/a/44586771/629127), that checks if the array is not empty
```js
const isEmpty = a => Array.isArray(a) && a.every(isEmpty);
```
This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see). |
383,179 | <p>I'm trying to show/hide two lines of text depending on whether a <code>WooCommerce</code> category is empty or has any products in it. Those lines are inserted in text blocks using <code>Elementor</code> and I've assigned a <code>CSS #ID</code> to each one, so I can control it.</p>
<p>Now, in a custom functions plugin I have, I want to add a function to control what phrase to hide using a <code>css</code> rule of the type: <code>display:none;</code>. The code I have now is:</p>
<pre class="lang-php prettyprint-override"><code>function show_outlet_msg($content){
$term = get_term( 40, 'product_cat' );
$total_products=$term->count;
if ($total_products>0){
//Have a products
} else {
//No products
}
}
add_filter('astra_entry_content_before','show_outlet_msg');
</code></pre>
<p>Now I would like to apply that if there are products in Outlet, the text that there are no products in Outlet should be hidden:</p>
<pre class="lang-css prettyprint-override"><code>#txt_outlet_zero{
display: none;
}
</code></pre>
<p>And in case there are no products, hide the one that says there are:</p>
<pre class="lang-css prettyprint-override"><code>#txt_outlet_head{
display: none;
}
</code></pre>
<p>How can I apply these CSS rules from the php code?</p>
| [
{
"answer_id": 383209,
"author": "dingo_d",
"author_id": 58895,
"author_profile": "https://wordpress.stackexchange.com/users/58895",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, after some research I got the result I needed:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Fetch all posts based on the selected postType.\nconst postsOptions = useSelect((select) => {\n const { getEntityRecords } = select('core');\n const { isResolving } = select('core/data');\n\n const postTypeSlugs = [...postType].map((element) => element.value) ?? [];\n\n if (!postTypeSlugs.length) {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n }\n ]\n }\n\n const postList = [];\n\n postTypeSlugs.forEach((postType) => {\n const args = ['postType', postType, {per_page: -1}];\n\n if (!isResolving('core', 'getEntityRecords', args)) {\n const result = getEntityRecords('postType', postType, {per_page: -1});\n\n if (result !== null) {\n postList.push(result);\n }\n }\n });\n\n if (typeof(postList[0]) !== 'undefined') {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n },\n ...postList[0].map((item) => {\n if (isEmpty(item)) {\n return {};\n } else {\n return {\n label: item.title.rendered || '',\n value: item.id || '',\n };\n }\n }),\n ];\n }\n});\n</code></pre>\n<p>Plus a helper from <a href=\"https://stackoverflow.com/a/44586771/629127\">here</a>, that checks if the array is not empty</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isEmpty = a => Array.isArray(a) && a.every(isEmpty);\n</code></pre>\n<p>This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see).</p>\n"
},
{
"answer_id": 401892,
"author": "Kalle",
"author_id": 218476,
"author_profile": "https://wordpress.stackexchange.com/users/218476",
"pm_score": 2,
"selected": false,
"text": "<p>Since while I was doing research I stumbled accross this thread, but it didn't bring me to the result I wanted. So I decided to register here to point out my approach to aquire the need of fetching posts with multiple post types.</p>\n<p>One thing is that the restAPI just does not accept multiple post type natively. I assume thats why getEntityRecords also does not provide that capability.</p>\n<p>1st) I registered a new RestAPI Endpoint to get the ability to query multiple post types when using it:</p>\n<pre><code>//PHP\nadd_action( 'rest_post_query', function( $args, $request ){\n $post_types = $request->get_param( 'type' );\n if( ! empty( $post_types ) ){\n if( is_string( $post_types ) ){\n // filtering posttypes, seperated with comma into an array, ignoring square brackets\n $post_types = explode( ',', str_replace( array( '[', ']') , '', $post_types ) );\n foreach ( $post_types as $key => $post_type ){\n $object = get_post_type_object( $post_type );\n if( ! $object || ! $object->show_in_rest ){\n unset( $post_types[ $key ] );\n }\n }\n }\n $args[ 'post_type' ] = $post_types;\n } else {\n // fallback: no type defined, return post as default\n $args[ 'post_type' ] = 'post';\n }\n return $args;\n}, 10, 2 );\n</code></pre>\n<p>Check your new API endpoint easily by calling it with your browser</p>\n<pre><code>https://*yoururl.com*/wp-json/wp/v2/posts?per_page=10&categories=0&type=posts,page\n</code></pre>\n<p>I don't use the Gutenberg function getEntityRecords anymore to fetch posts. I choose that way performance wise to avoid multiple calls of getEntityRecords.</p>\n<p>2nd) In my Gutenberg block I created a hook to call:</p>\n<pre><code>export default function useFetchPosts( url ) {\n const [data, setData] = useState( null );\n useEffect(() => {\n async function loadData() {\n const response = await fetch( url );\n if(! response.ok ) {\n return false;\n }\n const posts = await response.json();\n setData(posts);\n }\n loadData();\n }, [url]);\n return data;\n}\n</code></pre>\n<p>3rd) to get the posts I just call it like this inside my edit block:</p>\n<pre><code>// parsedCategories and\n// parsedPostTypes have to set and parsed by you before ofcourse ;)\nconst numberposts = 10;\nconst postFields = '&_fields=id,author,link,title,_links';\nconst posts = useFetchPosts( 'https://'+window.location.host+'/wp-json/wp/v2/posts?per_page='+numberposts+'&categories='+parsedCategories+'&_embed=author&type='+parsedPostTypes+'&orderby=date&order=desc'+postFields );\n</code></pre>\n<p>Check out the restAPI reference for available args and parms:\n<a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/</a></p>\n<p>Cheers</p>\n"
}
] | 2021/02/10 | [
"https://wordpress.stackexchange.com/questions/383179",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170286/"
] | I'm trying to show/hide two lines of text depending on whether a `WooCommerce` category is empty or has any products in it. Those lines are inserted in text blocks using `Elementor` and I've assigned a `CSS #ID` to each one, so I can control it.
Now, in a custom functions plugin I have, I want to add a function to control what phrase to hide using a `css` rule of the type: `display:none;`. The code I have now is:
```php
function show_outlet_msg($content){
$term = get_term( 40, 'product_cat' );
$total_products=$term->count;
if ($total_products>0){
//Have a products
} else {
//No products
}
}
add_filter('astra_entry_content_before','show_outlet_msg');
```
Now I would like to apply that if there are products in Outlet, the text that there are no products in Outlet should be hidden:
```css
#txt_outlet_zero{
display: none;
}
```
And in case there are no products, hide the one that says there are:
```css
#txt_outlet_head{
display: none;
}
```
How can I apply these CSS rules from the php code? | Ok, after some research I got the result I needed:
```js
// Fetch all posts based on the selected postType.
const postsOptions = useSelect((select) => {
const { getEntityRecords } = select('core');
const { isResolving } = select('core/data');
const postTypeSlugs = [...postType].map((element) => element.value) ?? [];
if (!postTypeSlugs.length) {
return [
{
label: __('No Filter used', 'slug'),
value: '',
}
]
}
const postList = [];
postTypeSlugs.forEach((postType) => {
const args = ['postType', postType, {per_page: -1}];
if (!isResolving('core', 'getEntityRecords', args)) {
const result = getEntityRecords('postType', postType, {per_page: -1});
if (result !== null) {
postList.push(result);
}
}
});
if (typeof(postList[0]) !== 'undefined') {
return [
{
label: __('No Filter used', 'slug'),
value: '',
},
...postList[0].map((item) => {
if (isEmpty(item)) {
return {};
} else {
return {
label: item.title.rendered || '',
value: item.id || '',
};
}
}),
];
}
});
```
Plus a helper from [here](https://stackoverflow.com/a/44586771/629127), that checks if the array is not empty
```js
const isEmpty = a => Array.isArray(a) && a.every(isEmpty);
```
This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see). |
383,286 | <p>I am trying to develop a bootstrap 5 theme for the latest WordPress. I am using Navwalker from here: <a href="https://github.com/wp-bootstrap/wp-bootstrap-navwalker" rel="nofollow noreferrer">https://github.com/wp-bootstrap/wp-bootstrap-navwalker</a>. My bootstrap Navbar does not dropdown on smaller screens.</p>
<p>Is it not working because I am using Bootstrap 5 and not bootstrap 4?</p>
<p>Here is my code from my header.php file:</p>
<pre><code><nav class="navbar navbar-expand-md navbar-dark bg-dark" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle navigation', 'your-theme-slug' ); ?>">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<?php
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
?>
</div>
</nav>
</code></pre>
<p>Here is my code from my functions.php file:</p>
<pre><code>function register_navwalker(){
require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';
}
add_action( 'after_setup_theme', 'register_navwalker' );
/*Navigation Menus*/
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'bootstrap' ),
'secondary' => __( 'Secondary Menu', 'bootstrap' )
) );
</code></pre>
<p>This is my error:</p>
<p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'register_navwalker' not found or invalid function name in C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-includes\class-wp-hook.php on line 292</p>
<p>Call Stack</p>
<pre><code>Time Memory Function Location
</code></pre>
<p>1 0.0003 413560 {main}( ) ...\index.php:0</p>
<p>2 0.0006 413832 require( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-blog-header.php' ) ...\index.php:17</p>
<p>3 0.0006 414376 require_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-load.php' ) ...\wp-blog-header.php:13</p>
<p>4 0.0007 414816 require_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-config.php' ) ...\wp-load.php:37</p>
<p>5 0.0007 419496 require_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-settings.php' ) ...\wp-config.php:79</p>
<p>6 0.0325 2624792 do_action( ) ...\wp-settings.php:538</p>
<p>7 0.0325 2625168 WP_Hook->do_action( ) ...\plugin.php:484</p>
<p>8 0.0325 2625168 WP_Hook->apply_filters( ) ...\class-wp-hook.php:316</p>
| [
{
"answer_id": 383209,
"author": "dingo_d",
"author_id": 58895,
"author_profile": "https://wordpress.stackexchange.com/users/58895",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, after some research I got the result I needed:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Fetch all posts based on the selected postType.\nconst postsOptions = useSelect((select) => {\n const { getEntityRecords } = select('core');\n const { isResolving } = select('core/data');\n\n const postTypeSlugs = [...postType].map((element) => element.value) ?? [];\n\n if (!postTypeSlugs.length) {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n }\n ]\n }\n\n const postList = [];\n\n postTypeSlugs.forEach((postType) => {\n const args = ['postType', postType, {per_page: -1}];\n\n if (!isResolving('core', 'getEntityRecords', args)) {\n const result = getEntityRecords('postType', postType, {per_page: -1});\n\n if (result !== null) {\n postList.push(result);\n }\n }\n });\n\n if (typeof(postList[0]) !== 'undefined') {\n return [\n {\n label: __('No Filter used', 'slug'),\n value: '',\n },\n ...postList[0].map((item) => {\n if (isEmpty(item)) {\n return {};\n } else {\n return {\n label: item.title.rendered || '',\n value: item.id || '',\n };\n }\n }),\n ];\n }\n});\n</code></pre>\n<p>Plus a helper from <a href=\"https://stackoverflow.com/a/44586771/629127\">here</a>, that checks if the array is not empty</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isEmpty = a => Array.isArray(a) && a.every(isEmpty);\n</code></pre>\n<p>This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see).</p>\n"
},
{
"answer_id": 401892,
"author": "Kalle",
"author_id": 218476,
"author_profile": "https://wordpress.stackexchange.com/users/218476",
"pm_score": 2,
"selected": false,
"text": "<p>Since while I was doing research I stumbled accross this thread, but it didn't bring me to the result I wanted. So I decided to register here to point out my approach to aquire the need of fetching posts with multiple post types.</p>\n<p>One thing is that the restAPI just does not accept multiple post type natively. I assume thats why getEntityRecords also does not provide that capability.</p>\n<p>1st) I registered a new RestAPI Endpoint to get the ability to query multiple post types when using it:</p>\n<pre><code>//PHP\nadd_action( 'rest_post_query', function( $args, $request ){\n $post_types = $request->get_param( 'type' );\n if( ! empty( $post_types ) ){\n if( is_string( $post_types ) ){\n // filtering posttypes, seperated with comma into an array, ignoring square brackets\n $post_types = explode( ',', str_replace( array( '[', ']') , '', $post_types ) );\n foreach ( $post_types as $key => $post_type ){\n $object = get_post_type_object( $post_type );\n if( ! $object || ! $object->show_in_rest ){\n unset( $post_types[ $key ] );\n }\n }\n }\n $args[ 'post_type' ] = $post_types;\n } else {\n // fallback: no type defined, return post as default\n $args[ 'post_type' ] = 'post';\n }\n return $args;\n}, 10, 2 );\n</code></pre>\n<p>Check your new API endpoint easily by calling it with your browser</p>\n<pre><code>https://*yoururl.com*/wp-json/wp/v2/posts?per_page=10&categories=0&type=posts,page\n</code></pre>\n<p>I don't use the Gutenberg function getEntityRecords anymore to fetch posts. I choose that way performance wise to avoid multiple calls of getEntityRecords.</p>\n<p>2nd) In my Gutenberg block I created a hook to call:</p>\n<pre><code>export default function useFetchPosts( url ) {\n const [data, setData] = useState( null );\n useEffect(() => {\n async function loadData() {\n const response = await fetch( url );\n if(! response.ok ) {\n return false;\n }\n const posts = await response.json();\n setData(posts);\n }\n loadData();\n }, [url]);\n return data;\n}\n</code></pre>\n<p>3rd) to get the posts I just call it like this inside my edit block:</p>\n<pre><code>// parsedCategories and\n// parsedPostTypes have to set and parsed by you before ofcourse ;)\nconst numberposts = 10;\nconst postFields = '&_fields=id,author,link,title,_links';\nconst posts = useFetchPosts( 'https://'+window.location.host+'/wp-json/wp/v2/posts?per_page='+numberposts+'&categories='+parsedCategories+'&_embed=author&type='+parsedPostTypes+'&orderby=date&order=desc'+postFields );\n</code></pre>\n<p>Check out the restAPI reference for available args and parms:\n<a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/</a></p>\n<p>Cheers</p>\n"
}
] | 2021/02/12 | [
"https://wordpress.stackexchange.com/questions/383286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182317/"
] | I am trying to develop a bootstrap 5 theme for the latest WordPress. I am using Navwalker from here: <https://github.com/wp-bootstrap/wp-bootstrap-navwalker>. My bootstrap Navbar does not dropdown on smaller screens.
Is it not working because I am using Bootstrap 5 and not bootstrap 4?
Here is my code from my header.php file:
```
<nav class="navbar navbar-expand-md navbar-dark bg-dark" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle navigation', 'your-theme-slug' ); ?>">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<?php
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
?>
</div>
</nav>
```
Here is my code from my functions.php file:
```
function register_navwalker(){
require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';
}
add_action( 'after_setup_theme', 'register_navwalker' );
/*Navigation Menus*/
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'bootstrap' ),
'secondary' => __( 'Secondary Menu', 'bootstrap' )
) );
```
This is my error:
Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'register\_navwalker' not found or invalid function name in C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-includes\class-wp-hook.php on line 292
Call Stack
```
Time Memory Function Location
```
1 0.0003 413560 {main}( ) ...\index.php:0
2 0.0006 413832 require( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-blog-header.php' ) ...\index.php:17
3 0.0006 414376 require\_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-load.php' ) ...\wp-blog-header.php:13
4 0.0007 414816 require\_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-config.php' ) ...\wp-load.php:37
5 0.0007 419496 require\_once( 'C:\Users\apiro\Local Sites\wordpressbootstraptheme\app\public\wp-settings.php' ) ...\wp-config.php:79
6 0.0325 2624792 do\_action( ) ...\wp-settings.php:538
7 0.0325 2625168 WP\_Hook->do\_action( ) ...\plugin.php:484
8 0.0325 2625168 WP\_Hook->apply\_filters( ) ...\class-wp-hook.php:316 | Ok, after some research I got the result I needed:
```js
// Fetch all posts based on the selected postType.
const postsOptions = useSelect((select) => {
const { getEntityRecords } = select('core');
const { isResolving } = select('core/data');
const postTypeSlugs = [...postType].map((element) => element.value) ?? [];
if (!postTypeSlugs.length) {
return [
{
label: __('No Filter used', 'slug'),
value: '',
}
]
}
const postList = [];
postTypeSlugs.forEach((postType) => {
const args = ['postType', postType, {per_page: -1}];
if (!isResolving('core', 'getEntityRecords', args)) {
const result = getEntityRecords('postType', postType, {per_page: -1});
if (result !== null) {
postList.push(result);
}
}
});
if (typeof(postList[0]) !== 'undefined') {
return [
{
label: __('No Filter used', 'slug'),
value: '',
},
...postList[0].map((item) => {
if (isEmpty(item)) {
return {};
} else {
return {
label: item.title.rendered || '',
value: item.id || '',
};
}
}),
];
}
});
```
Plus a helper from [here](https://stackoverflow.com/a/44586771/629127), that checks if the array is not empty
```js
const isEmpty = a => Array.isArray(a) && a.every(isEmpty);
```
This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see). |
383,303 | <p>Inside my <code>content-single</code> template, I have a conditional check that displays text based on how old the post is. The idea is to inform visitors that they might be reading "old" news.</p>
<p>Problem is; the <code>6+ months old</code> text is displayed on posts that are only days old, and I do not understand why.</p>
<p><strong>This is the code I am using:</strong></p>
<pre><code><?php
if ( strtotime( get_the_date() ) < strtotime( '-1 year' ) ) { ?>
<span class="old-post"> 6+ months old </span>&nbsp;/&nbsp;
<?php
}
?>
</code></pre>
<p>This is the format I am using in WP admin for date and time:</p>
<pre><code>l \t\h\e jS \of F @ H:i
</code></pre>
<p>Please help me understand how to fix this.</p>
| [
{
"answer_id": 383311,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>By using below code, you can check if Post Was published more than 6 Months ago using get_the_date.</p>\n<p>place below code inside content-single template, It inform visitors that they are reading "old" news which is plublished 6+ months old.</p>\n<pre><code># get last 6 month date from current date\n$last_sixth_month_date = strtotime("-6 month"); \n\n# publish date\n$post_poblish_date = strtotime( get_the_date() );\n\n# get difference from two dates\n$year1 = date('Y', $last_sixth_month_date);\n$year2 = date('Y', $post_poblish_date);\n$month1 = date('m', $last_sixth_month_date);\n$month2 = date('m', $post_poblish_date);\n$month_diffrence = (($year2 - $year1) * 12) + ($month2 - $month1);\n\nif($month_diffrence < 0 )\n{\n # check difference between date is 6 or more than 6\n if(abs($month_diffrence) >= 6 )\n {\n echo '<span class="old-post"> 6+ months old </span>&nbsp;/&nbsp';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 383314,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that your date format is not a standard format that <code>strtotime()</code> understands. Instead just use <code>get_the_date()</code> with the format set to <code>'U'</code>, which returns the timestamp, and compare that to <code>strtotime( '-1 year' )</code>:</p>\n<pre><code>if ( get_the_date( 'U' ) < strtotime( '-1 year' ) ) {\n\n}\n</code></pre>\n"
}
] | 2021/02/13 | [
"https://wordpress.stackexchange.com/questions/383303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/201877/"
] | Inside my `content-single` template, I have a conditional check that displays text based on how old the post is. The idea is to inform visitors that they might be reading "old" news.
Problem is; the `6+ months old` text is displayed on posts that are only days old, and I do not understand why.
**This is the code I am using:**
```
<?php
if ( strtotime( get_the_date() ) < strtotime( '-1 year' ) ) { ?>
<span class="old-post"> 6+ months old </span> /
<?php
}
?>
```
This is the format I am using in WP admin for date and time:
```
l \t\h\e jS \of F @ H:i
```
Please help me understand how to fix this. | The problem is that your date format is not a standard format that `strtotime()` understands. Instead just use `get_the_date()` with the format set to `'U'`, which returns the timestamp, and compare that to `strtotime( '-1 year' )`:
```
if ( get_the_date( 'U' ) < strtotime( '-1 year' ) ) {
}
``` |
Subsets and Splits