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
|
---|---|---|---|---|---|---|
364,959 | <p>I am trying to create a custom block for text input field.</p>
<p>I managed to create a simple block that produces the <code><p></code> tag. When I change it to produce the <code><input></code> tag and refresh I am getting <em>Block validation failed</em> and the only solution is to remove the block and re-insert it.</p>
<p>It is ok if you have few blocks on a page but I am wondering what if I want to update a whole theme with existing content. Seems like even changing a trivial property as colour results in validation error.</p>
<pre><code> // existing
save: (props) ->
el RichText.Content,
tagName: 'p'
value: props.attributes.content
// updated
save: (props) ->
el RichText.Content,
tagName: 'input'
value: props.attributes.content
</code></pre>
<p>What is the correct way of amending and updating existing Gutenberg blocks?</p>
| [
{
"answer_id": 364963,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>You have two choices.</p>\n\n<p>The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.</p>\n\n<p>The second option: add <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">deprecated code</a> into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the <code>save()</code> output. The downside is, the more times you change the output and keep the \"deprecated\" code available, the heavier your plugin gets.</p>\n"
},
{
"answer_id": 365284,
"author": "Maciek Rek",
"author_id": 125744,
"author_profile": "https://wordpress.stackexchange.com/users/125744",
"pm_score": 0,
"selected": false,
"text": "<p>After reading through the WP Handbook guide, I found out that the better solution might be using dynamic blocks, at least in the development stage.</p>\n\n<blockquote>\n <p>[...] Blocks where updates to the code (HTML, CSS, JS) should be immediately\n shown on the front end of the website. For example, if you update the\n structure of a block by adding a new class, adding an HTML element, or\n changing the layout in any other way, using a dynamic block ensures\n those changes are applied immediately on all occurrences of that block\n across the site.[...]</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/</a></p>\n"
}
] | 2020/04/24 | [
"https://wordpress.stackexchange.com/questions/364959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125744/"
] | I am trying to create a custom block for text input field.
I managed to create a simple block that produces the `<p>` tag. When I change it to produce the `<input>` tag and refresh I am getting *Block validation failed* and the only solution is to remove the block and re-insert it.
It is ok if you have few blocks on a page but I am wondering what if I want to update a whole theme with existing content. Seems like even changing a trivial property as colour results in validation error.
```
// existing
save: (props) ->
el RichText.Content,
tagName: 'p'
value: props.attributes.content
// updated
save: (props) ->
el RichText.Content,
tagName: 'input'
value: props.attributes.content
```
What is the correct way of amending and updating existing Gutenberg blocks? | You have two choices.
The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.
The second option: add [deprecated code](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/) into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the `save()` output. The downside is, the more times you change the output and keep the "deprecated" code available, the heavier your plugin gets. |
364,982 | <p>I have a Wordpress site functioning as a blog site on a website. The main website is just basic HTML it is only www.example.com/blog which has the WordPress site.</p>
<p>I have installed an SSL certificate for the domain and it is working fine. I have a .htaccess file in the root folder redirecting from HTTP to https for the main site and another in the /blog folder redirecting the Wordpress site. </p>
<p>The problem I am having is the main folder www.example.com/blog will redirect to https however none of the blog posts will redirect. </p>
<p>So for example if I enter <a href="http://www.example.com/blog" rel="nofollow noreferrer">http://www.example.com/blog</a> into the browser i get <a href="https://www.example.com/blog" rel="nofollow noreferrer">https://www.example.com/blog</a>.</p>
<p>But if I enter <a href="http://www.example.com/blog/blog-post" rel="nofollow noreferrer">http://www.example.com/blog/blog-post</a> I get <a href="http://www.example.com/blog/blog-post" rel="nofollow noreferrer">http://www.example.com/blog/blog-post</a> it does not redirect.</p>
<p>I have tried a number of different .htaccess commands, but they all give the same result. I currently have the following script in the .htaccess folder.</p>
<pre><code>RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
| [
{
"answer_id": 364963,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>You have two choices.</p>\n\n<p>The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.</p>\n\n<p>The second option: add <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">deprecated code</a> into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the <code>save()</code> output. The downside is, the more times you change the output and keep the \"deprecated\" code available, the heavier your plugin gets.</p>\n"
},
{
"answer_id": 365284,
"author": "Maciek Rek",
"author_id": 125744,
"author_profile": "https://wordpress.stackexchange.com/users/125744",
"pm_score": 0,
"selected": false,
"text": "<p>After reading through the WP Handbook guide, I found out that the better solution might be using dynamic blocks, at least in the development stage.</p>\n\n<blockquote>\n <p>[...] Blocks where updates to the code (HTML, CSS, JS) should be immediately\n shown on the front end of the website. For example, if you update the\n structure of a block by adding a new class, adding an HTML element, or\n changing the layout in any other way, using a dynamic block ensures\n those changes are applied immediately on all occurrences of that block\n across the site.[...]</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/</a></p>\n"
}
] | 2020/04/24 | [
"https://wordpress.stackexchange.com/questions/364982",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186817/"
] | I have a Wordpress site functioning as a blog site on a website. The main website is just basic HTML it is only www.example.com/blog which has the WordPress site.
I have installed an SSL certificate for the domain and it is working fine. I have a .htaccess file in the root folder redirecting from HTTP to https for the main site and another in the /blog folder redirecting the Wordpress site.
The problem I am having is the main folder www.example.com/blog will redirect to https however none of the blog posts will redirect.
So for example if I enter <http://www.example.com/blog> into the browser i get <https://www.example.com/blog>.
But if I enter <http://www.example.com/blog/blog-post> I get <http://www.example.com/blog/blog-post> it does not redirect.
I have tried a number of different .htaccess commands, but they all give the same result. I currently have the following script in the .htaccess folder.
```
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
```
Any help on this would be greatly appreciated. | You have two choices.
The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.
The second option: add [deprecated code](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/) into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the `save()` output. The downside is, the more times you change the output and keep the "deprecated" code available, the heavier your plugin gets. |
365,032 | <p>I've found another questions regarding on how to <code>set</code> cookies on wp/wc but i cannot find how to properly get those cookies, i created a hook on the <code>init</code> function like this;</p>
<pre><code>add_action('init', function () {
$utm_source = get_request_parameter('utm_source');
if (!empty($utm_source)) {
wc_setcookie(DEFAULT_COOKIE_KEY, $utm_source, DEFAULT_COOKIE_EXPIRATION);
}
});
</code></pre>
<p>And the cookie was set correctly (i saw it on the cookie options on my browser) but when i try to get this cookie value on my other <code>filter</code> the key is not present.</p>
<pre><code>function my_custom_price($price, $product) {
$cookie = isset($_COOKIE[DEFAULT_COOKIE_KEY]) ? $_COOKIE[DEFAULT_COOKIE_KEY] : "";
// $cookie is always empty string
}
add_filter('woocommerce_product_get_price', 'my_custom_price', 10, 2);
</code></pre>
<p>Is this related to the order that filter and hooks are called? how can i set a cookie and get the value from another filter action?</p>
| [
{
"answer_id": 364963,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>You have two choices.</p>\n\n<p>The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.</p>\n\n<p>The second option: add <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">deprecated code</a> into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the <code>save()</code> output. The downside is, the more times you change the output and keep the \"deprecated\" code available, the heavier your plugin gets.</p>\n"
},
{
"answer_id": 365284,
"author": "Maciek Rek",
"author_id": 125744,
"author_profile": "https://wordpress.stackexchange.com/users/125744",
"pm_score": 0,
"selected": false,
"text": "<p>After reading through the WP Handbook guide, I found out that the better solution might be using dynamic blocks, at least in the development stage.</p>\n\n<blockquote>\n <p>[...] Blocks where updates to the code (HTML, CSS, JS) should be immediately\n shown on the front end of the website. For example, if you update the\n structure of a block by adding a new class, adding an HTML element, or\n changing the layout in any other way, using a dynamic block ensures\n those changes are applied immediately on all occurrences of that block\n across the site.[...]</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/</a></p>\n"
}
] | 2020/04/25 | [
"https://wordpress.stackexchange.com/questions/365032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124888/"
] | I've found another questions regarding on how to `set` cookies on wp/wc but i cannot find how to properly get those cookies, i created a hook on the `init` function like this;
```
add_action('init', function () {
$utm_source = get_request_parameter('utm_source');
if (!empty($utm_source)) {
wc_setcookie(DEFAULT_COOKIE_KEY, $utm_source, DEFAULT_COOKIE_EXPIRATION);
}
});
```
And the cookie was set correctly (i saw it on the cookie options on my browser) but when i try to get this cookie value on my other `filter` the key is not present.
```
function my_custom_price($price, $product) {
$cookie = isset($_COOKIE[DEFAULT_COOKIE_KEY]) ? $_COOKIE[DEFAULT_COOKIE_KEY] : "";
// $cookie is always empty string
}
add_filter('woocommerce_product_get_price', 'my_custom_price', 10, 2);
```
Is this related to the order that filter and hooks are called? how can i set a cookie and get the value from another filter action? | You have two choices.
The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.
The second option: add [deprecated code](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/) into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the `save()` output. The downside is, the more times you change the output and keep the "deprecated" code available, the heavier your plugin gets. |
365,058 | <p>Hi I'm looking all over but I don't find the solution: I have an infobox with: Hi, welcome to our "some text"</p>
<p>Now I'd like to add posibility for logged in users "Hello <strong>Tony</strong>, welcome to our "some text"</p>
<p>I tried following code snippet: </p>
<pre><code><div id="infoBox">
<button class="cross" type="button">X</button>
<p> Hello </p> <?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo 'Username: ' . $current_user->user_login . "\n"; echo 'User display name: ' . $current_user->display_name . "\n"; }
else { wp_loginout(); } ?>
<p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gub
</p>
</div>
</code></pre>
<p>but there's a fatal error in my XAMPP testing environment:</p>
<blockquote>
<p>Fatal error: Uncaught Error: Call to undefined function
wp_get_current_user() in
/opt/lampp/htdocs/wordpress/wp-content/plugins/stoerer/stoerer.php:31
Stack trace: #0 /opt/lampp/htdocs/wordpress/wp-settings.php(377):
include_once() #1 /opt/lampp/htdocs/wp-config.php(90):
require_once('/opt/lampp/htdo...') #2
/opt/lampp/htdocs/wordpress/wp-load.php(42):
require_once('/opt/lampp/htdo...') #3
/opt/lampp/htdocs/wordpress/wp-blog-header.php(13):
require_once('/opt/lampp/htdo...') #4
/opt/lampp/htdocs/wordpress/index.php(17):
require('/opt/lampp/htdo...') #5 {main} thrown in
/opt/lampp/htdocs/wordpress/wp-content/plugins/stoerer/stoerer.php on
line 31 There has been a critical error on your website.</p>
</blockquote>
| [
{
"answer_id": 364963,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>You have two choices.</p>\n\n<p>The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.</p>\n\n<p>The second option: add <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">deprecated code</a> into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the <code>save()</code> output. The downside is, the more times you change the output and keep the \"deprecated\" code available, the heavier your plugin gets.</p>\n"
},
{
"answer_id": 365284,
"author": "Maciek Rek",
"author_id": 125744,
"author_profile": "https://wordpress.stackexchange.com/users/125744",
"pm_score": 0,
"selected": false,
"text": "<p>After reading through the WP Handbook guide, I found out that the better solution might be using dynamic blocks, at least in the development stage.</p>\n\n<blockquote>\n <p>[...] Blocks where updates to the code (HTML, CSS, JS) should be immediately\n shown on the front end of the website. For example, if you update the\n structure of a block by adding a new class, adding an HTML element, or\n changing the layout in any other way, using a dynamic block ensures\n those changes are applied immediately on all occurrences of that block\n across the site.[...]</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/</a></p>\n"
}
] | 2020/04/25 | [
"https://wordpress.stackexchange.com/questions/365058",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186880/"
] | Hi I'm looking all over but I don't find the solution: I have an infobox with: Hi, welcome to our "some text"
Now I'd like to add posibility for logged in users "Hello **Tony**, welcome to our "some text"
I tried following code snippet:
```
<div id="infoBox">
<button class="cross" type="button">X</button>
<p> Hello </p> <?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo 'Username: ' . $current_user->user_login . "\n"; echo 'User display name: ' . $current_user->display_name . "\n"; }
else { wp_loginout(); } ?>
<p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gub
</p>
</div>
```
but there's a fatal error in my XAMPP testing environment:
>
> Fatal error: Uncaught Error: Call to undefined function
> wp\_get\_current\_user() in
> /opt/lampp/htdocs/wordpress/wp-content/plugins/stoerer/stoerer.php:31
> Stack trace: #0 /opt/lampp/htdocs/wordpress/wp-settings.php(377):
> include\_once() #1 /opt/lampp/htdocs/wp-config.php(90):
> require\_once('/opt/lampp/htdo...') #2
> /opt/lampp/htdocs/wordpress/wp-load.php(42):
> require\_once('/opt/lampp/htdo...') #3
> /opt/lampp/htdocs/wordpress/wp-blog-header.php(13):
> require\_once('/opt/lampp/htdo...') #4
> /opt/lampp/htdocs/wordpress/index.php(17):
> require('/opt/lampp/htdo...') #5 {main} thrown in
> /opt/lampp/htdocs/wordpress/wp-content/plugins/stoerer/stoerer.php on
> line 31 There has been a critical error on your website.
>
>
> | You have two choices.
The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.
The second option: add [deprecated code](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/) into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the `save()` output. The downside is, the more times you change the output and keep the "deprecated" code available, the heavier your plugin gets. |
365,071 | <p>Just looking for a bit of advice on how to handle this:</p>
<p>In the past (many moons ago) when I did the occasional php/mysql work, it was relatively easy to pull/display data from a table using the table header in the "WHERE" query. (i.e. SELECT * FROM 'table' WHERE 'column-name' = 'query').
The tables would have columns for each piece of information such as email, phone, address, etc.</p>
<p>I am currently working on a project using a table that was installed into the database by a plugin where I want to use some of that data in a different area of the site not related to the plugin.</p>
<p>Instead of a column for each type of information as above, this table has</p>
<ul>
<li>a user_id column which is linked to the users wordpress account</li>
<li>user_id a meta_key column. This column has entries such as address, phone number, etc. (these would be the column names in my above example)</li>
<li>a meta_value column. This column holds the data for each type of meta_key (the actual address, phone number, etc.)</li>
</ul>
<p>What I am looking to do is get the value for each item for a particular user_id and pre-fill a form that is submitted.</p>
<p>So their User ID, Name and email are pulled from the users table of the WP database when they are logged in using the <em>wp_get_current_user()</em> function.
Once I have the User ID, I then want to display that user's address, phone number etc from the other table in my form but I'm stuck on the sql query</p>
<p>Something like:</p>
<pre><code>global $wpdb;
$current_user = wp_get_current_user();
$uid = $current_user->ID;
$table = $wpdb_>prefix . 'plugin-table';
</code></pre>
<p>I then want to select the user's address and phone number etc and display them as individual pieces of info, so:</p>
<pre><code>$mobile
$address
$studentnumber
</code></pre>
<p>so that I can use them where needed</p>
<p>What would be the correct way to query the database to get the info I'm looking for?</p>
<p>Hope that all made sense...</p>
| [
{
"answer_id": 365268,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 0,
"selected": false,
"text": "<p>OK, so maybe the above wasn't worded very well?</p>\n\n<p>I have since made some progress as follows:</p>\n\n<pre><code>global $wpdb; \n$current_user = wp_get_current_user();\n$uid = $current_user->ID;\n$fname = $current_user->first_name . \" \" . $current_user->last_name;\n$email = $current_user->user_email;\n\n$studentTable = $wpdb->prefix.'um_metadata';\n\n\n$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND 'um_key' = 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value;\n}\n</code></pre>\n\n<p>Quick context:</p>\n\n<ul>\n<li>um_key column is the type of data (phone, address,\netc.)</li>\n<li>um_value is the column with the information</li>\n</ul>\n\n<p>If I remove <code>AND 'um_key' = 'student_number'</code> from the SQL query, the result will spit out all the rows that have the correct user_id, but I am only looking to output the specific row that has the um_key 'student_number'</p>\n\n<p>Any help appreciated</p>\n"
},
{
"answer_id": 365274,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 1,
"selected": false,
"text": "<p>So, the following works:</p>\n\n<pre><code>$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value.'<br/>';\n}\n</code></pre>\n\n<p>though I feel that 'foreach' is not really the correct syntax/terminology to be using?</p>\n"
},
{
"answer_id": 376101,
"author": "Mr_Ussi",
"author_id": 194231,
"author_profile": "https://wordpress.stackexchange.com/users/194231",
"pm_score": 1,
"selected": false,
"text": "<pre><code>global $wpdb;\n\n$table_name = $wpdb->prefix . 'your_table_name';\n\n$results = $wpdb->get_results(\n\n "SELECT * FROM $table_name"\n\n);\n\nforeach($results as $row)\n{\n\n echo $row->id;\n\n}\n</code></pre>\n"
}
] | 2020/04/26 | [
"https://wordpress.stackexchange.com/questions/365071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183442/"
] | Just looking for a bit of advice on how to handle this:
In the past (many moons ago) when I did the occasional php/mysql work, it was relatively easy to pull/display data from a table using the table header in the "WHERE" query. (i.e. SELECT \* FROM 'table' WHERE 'column-name' = 'query').
The tables would have columns for each piece of information such as email, phone, address, etc.
I am currently working on a project using a table that was installed into the database by a plugin where I want to use some of that data in a different area of the site not related to the plugin.
Instead of a column for each type of information as above, this table has
* a user\_id column which is linked to the users wordpress account
* user\_id a meta\_key column. This column has entries such as address, phone number, etc. (these would be the column names in my above example)
* a meta\_value column. This column holds the data for each type of meta\_key (the actual address, phone number, etc.)
What I am looking to do is get the value for each item for a particular user\_id and pre-fill a form that is submitted.
So their User ID, Name and email are pulled from the users table of the WP database when they are logged in using the *wp\_get\_current\_user()* function.
Once I have the User ID, I then want to display that user's address, phone number etc from the other table in my form but I'm stuck on the sql query
Something like:
```
global $wpdb;
$current_user = wp_get_current_user();
$uid = $current_user->ID;
$table = $wpdb_>prefix . 'plugin-table';
```
I then want to select the user's address and phone number etc and display them as individual pieces of info, so:
```
$mobile
$address
$studentnumber
```
so that I can use them where needed
What would be the correct way to query the database to get the info I'm looking for?
Hope that all made sense... | So, the following works:
```
$result = $wpdb->get_results ( "SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' ");
foreach($result as $studentNumber){
echo $studentNumber->um_value.'<br/>';
}
```
though I feel that 'foreach' is not really the correct syntax/terminology to be using? |
365,094 | <p>This below script works great and redirects logged-out users to login page if they try to access the my-account page</p>
<pre><code>/**************************************START*******************************************
*********** Redirect account page to login page if user is logged out ****************
**************************************************************************************/
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$logged_in_restricted = array( 5156, 000 ); // all your restricted pages if user is logged out
if ( in_array( get_queried_object_id(), $logged_out_restricted ) ) {
wp_redirect( site_url( '/login' ) ); // page user redirected to if restriction met
exit();
}
});
</code></pre>
<p>How can i utilize the same script logic but target logged-in users instead of logged-out as an additional script? For example now i want to redirect logged-in users to the "my-account" page if they attempt to go to login/register pages. Here's an example:</p>
<pre><code>/**************************************START*******************************************
******* Redirect login and register page to account page if user is logged In *******
**************************************************************************************/
add_action( 'template_redirect', function() {
if ( is_user_logged_out() || ! is_page() ) return;
$logged_in_restricted = array( 3156, 4532 ); // all your restricted pages if user is logged In
if ( in_array( get_queried_object_id(), $logged_in_restricted ) ) {
wp_redirect( site_url( '/my-account' ) ); // page user redirected to if restriction met
exit();
}
});
</code></pre>
<p>I understand <code>is_user_logged_out</code> is not a thing. What can i use to accomplish this?</p>
| [
{
"answer_id": 365268,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 0,
"selected": false,
"text": "<p>OK, so maybe the above wasn't worded very well?</p>\n\n<p>I have since made some progress as follows:</p>\n\n<pre><code>global $wpdb; \n$current_user = wp_get_current_user();\n$uid = $current_user->ID;\n$fname = $current_user->first_name . \" \" . $current_user->last_name;\n$email = $current_user->user_email;\n\n$studentTable = $wpdb->prefix.'um_metadata';\n\n\n$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND 'um_key' = 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value;\n}\n</code></pre>\n\n<p>Quick context:</p>\n\n<ul>\n<li>um_key column is the type of data (phone, address,\netc.)</li>\n<li>um_value is the column with the information</li>\n</ul>\n\n<p>If I remove <code>AND 'um_key' = 'student_number'</code> from the SQL query, the result will spit out all the rows that have the correct user_id, but I am only looking to output the specific row that has the um_key 'student_number'</p>\n\n<p>Any help appreciated</p>\n"
},
{
"answer_id": 365274,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 1,
"selected": false,
"text": "<p>So, the following works:</p>\n\n<pre><code>$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value.'<br/>';\n}\n</code></pre>\n\n<p>though I feel that 'foreach' is not really the correct syntax/terminology to be using?</p>\n"
},
{
"answer_id": 376101,
"author": "Mr_Ussi",
"author_id": 194231,
"author_profile": "https://wordpress.stackexchange.com/users/194231",
"pm_score": 1,
"selected": false,
"text": "<pre><code>global $wpdb;\n\n$table_name = $wpdb->prefix . 'your_table_name';\n\n$results = $wpdb->get_results(\n\n "SELECT * FROM $table_name"\n\n);\n\nforeach($results as $row)\n{\n\n echo $row->id;\n\n}\n</code></pre>\n"
}
] | 2020/04/26 | [
"https://wordpress.stackexchange.com/questions/365094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
] | This below script works great and redirects logged-out users to login page if they try to access the my-account page
```
/**************************************START*******************************************
*********** Redirect account page to login page if user is logged out ****************
**************************************************************************************/
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$logged_in_restricted = array( 5156, 000 ); // all your restricted pages if user is logged out
if ( in_array( get_queried_object_id(), $logged_out_restricted ) ) {
wp_redirect( site_url( '/login' ) ); // page user redirected to if restriction met
exit();
}
});
```
How can i utilize the same script logic but target logged-in users instead of logged-out as an additional script? For example now i want to redirect logged-in users to the "my-account" page if they attempt to go to login/register pages. Here's an example:
```
/**************************************START*******************************************
******* Redirect login and register page to account page if user is logged In *******
**************************************************************************************/
add_action( 'template_redirect', function() {
if ( is_user_logged_out() || ! is_page() ) return;
$logged_in_restricted = array( 3156, 4532 ); // all your restricted pages if user is logged In
if ( in_array( get_queried_object_id(), $logged_in_restricted ) ) {
wp_redirect( site_url( '/my-account' ) ); // page user redirected to if restriction met
exit();
}
});
```
I understand `is_user_logged_out` is not a thing. What can i use to accomplish this? | So, the following works:
```
$result = $wpdb->get_results ( "SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' ");
foreach($result as $studentNumber){
echo $studentNumber->um_value.'<br/>';
}
```
though I feel that 'foreach' is not really the correct syntax/terminology to be using? |
365,131 | <p>We are two managers for one website , each of us have an AdSense account</p>
<p>Can our ad code display in the articles we write, based on the author slug or id?</p>
<p>I tried to use this code in head section , but it did not work :</p>
<p><code><?php if (is_author('author 1');) : ?>
<script data-ad-client="ca-pub-ءءءءء1ءءءء" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>;
<?php else : ?>
<script data-ad-client="ca-pub-ءءءءء2ءءءء" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<?php endif; ?></code></p>
<p>any ideas to switch automatically between the accounts, not as a revenue share.</p>
| [
{
"answer_id": 365268,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 0,
"selected": false,
"text": "<p>OK, so maybe the above wasn't worded very well?</p>\n\n<p>I have since made some progress as follows:</p>\n\n<pre><code>global $wpdb; \n$current_user = wp_get_current_user();\n$uid = $current_user->ID;\n$fname = $current_user->first_name . \" \" . $current_user->last_name;\n$email = $current_user->user_email;\n\n$studentTable = $wpdb->prefix.'um_metadata';\n\n\n$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND 'um_key' = 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value;\n}\n</code></pre>\n\n<p>Quick context:</p>\n\n<ul>\n<li>um_key column is the type of data (phone, address,\netc.)</li>\n<li>um_value is the column with the information</li>\n</ul>\n\n<p>If I remove <code>AND 'um_key' = 'student_number'</code> from the SQL query, the result will spit out all the rows that have the correct user_id, but I am only looking to output the specific row that has the um_key 'student_number'</p>\n\n<p>Any help appreciated</p>\n"
},
{
"answer_id": 365274,
"author": "Daniel Florian",
"author_id": 183442,
"author_profile": "https://wordpress.stackexchange.com/users/183442",
"pm_score": 1,
"selected": false,
"text": "<p>So, the following works:</p>\n\n<pre><code>$result = $wpdb->get_results ( \"SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' \");\n\nforeach($result as $studentNumber){\n echo $studentNumber->um_value.'<br/>';\n}\n</code></pre>\n\n<p>though I feel that 'foreach' is not really the correct syntax/terminology to be using?</p>\n"
},
{
"answer_id": 376101,
"author": "Mr_Ussi",
"author_id": 194231,
"author_profile": "https://wordpress.stackexchange.com/users/194231",
"pm_score": 1,
"selected": false,
"text": "<pre><code>global $wpdb;\n\n$table_name = $wpdb->prefix . 'your_table_name';\n\n$results = $wpdb->get_results(\n\n "SELECT * FROM $table_name"\n\n);\n\nforeach($results as $row)\n{\n\n echo $row->id;\n\n}\n</code></pre>\n"
}
] | 2020/04/26 | [
"https://wordpress.stackexchange.com/questions/365131",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186918/"
] | We are two managers for one website , each of us have an AdSense account
Can our ad code display in the articles we write, based on the author slug or id?
I tried to use this code in head section , but it did not work :
`<?php if (is_author('author 1');) : ?>
<script data-ad-client="ca-pub-ءءءءء1ءءءء" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>;
<?php else : ?>
<script data-ad-client="ca-pub-ءءءءء2ءءءء" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<?php endif; ?>`
any ideas to switch automatically between the accounts, not as a revenue share. | So, the following works:
```
$result = $wpdb->get_results ( "SELECT * FROM $studentTable WHERE `user_id` = $uid AND `um_key` LIKE 'student_number' ");
foreach($result as $studentNumber){
echo $studentNumber->um_value.'<br/>';
}
```
though I feel that 'foreach' is not really the correct syntax/terminology to be using? |
365,150 | <p>How can I add a new column to quick edit and put a custom field in it? I read <a href="https://wordpress.stackexchange.com/a/199758">this question</a> but one of the links lead to an error 404. I need a new column for my custom meta key, "<code>summary</code>" and post types, "<code>post</code>" and "<code>episode</code>".</p>
| [
{
"answer_id": 365166,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 5,
"selected": true,
"text": "<p>There are a few steps to create the custom quick edit box and custom column</p>\n<ol>\n<li>create a custom meta key (assumed that you have 1 already)</li>\n<li>add custom admin column title and data (assumed that you want to shows the custom meta key in the column, if not, you may also modify a bit of the logic to accomplish the same effect because the principal is the same)</li>\n<li>add custom quick edit box</li>\n<li>add save logic</li>\n<li>load script to modify original inline-edit-post function in order to support custom meta value</li>\n<li>prepare the script file</li>\n</ol>\n<h2>This example is going to add a quick edit input box in post type <code>Page</code>. The following code is proved to work by putting in functions.php .</h2>\n<h3>1. create a custom meta key (assumed that you have 1 already)</h3>\n<p>I have prepared a custom meta key <code>remark</code> for post type <code>page</code></p>\n<h3>2. add custom admin column title and data</h3>\n<p>for custom post type, you may use</p>\n<p>Add column title</p>\n<ul>\n<li>For specific Screen ID <a href=\"https://developer.wordpress.org/reference/hooks/manage_screen-id_columns/\" rel=\"nofollow noreferrer\">manage_{$screen->id}_columns</a></li>\n<li>Specificially for Page <a href=\"https://developer.wordpress.org/reference/hooks/manage_pages_columns/\" rel=\"nofollow noreferrer\">manage_pages_columns</a></li>\n<li>Specificially for generic (default Post or custom post type) <a href=\"https://developer.wordpress.org/reference/hooks/manage_posts_custom_column/\" rel=\"nofollow noreferrer\">manage_posts_custom_column</a> or for specific post type <a href=\"https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/\" rel=\"nofollow noreferrer\">manage_{$post->post_type}_posts_custom_column</a> to add column data</li>\n</ul>\n<p>Add column content</p>\n<ul>\n<li>Generic (default Post or custom post type) <a href=\"https://developer.wordpress.org/reference/hooks/manage_posts_columns/\" rel=\"nofollow noreferrer\">manage_posts_columns</a> with custom post type checking using post type argument or for specific post type <a href=\"https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/\" rel=\"nofollow noreferrer\">manage_{$post_type}_posts_columns</a> to add column title</li>\n</ul>\n<p>The following is an example for post type Page as well as custom post type + default <code>Post</code> as an example for multiple post types setup.</p>\n<pre><code>// add custom column title for custom meta value\nadd_filter('manage_edit-page_columns', 'ws365150_add_custom_columns_title' );\nfunction ws365150_add_custom_columns_title( $columns ) {\n $columns['page_remark'] = 'Remark'; // you may use __() later on for translation support\n \n return $columns;\n}\n \n// add custom column data with custom meta value\nadd_action('manage_pages_custom_column', 'ws365150_add_custom_column_data', 10, 2 );\nfunction ws365150_add_custom_column_data( $column_name, $post_id ) {\n switch ( $column_name ) {\n case 'page_remark':\n echo get_post_meta( $post_id, 'remark', true );\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<p>The following is an example for custom post type <code>episode</code> + default <code>Post</code> with meta key <code>summary</code></p>\n<pre><code>// add custom column title for custom meta value\n// 'manage_pages_columns' or 'manage_edit-post_columns' both works\nadd_filter('manage_posts_columns', 'ws365150_add_custom_columns_title_pt', 10, 2 );\nfunction ws365150_add_custom_columns_title_pt( $columns, $post_type ) {\n switch ( $post_type ) {\n case 'post':\n case 'episode':\n $columns['ws365150_summary'] = 'Summary'; // you may use __() later on for translation support\n break;\n \n default:\n \n break;\n }\n \n return $columns;\n}\n \n// add custom column data with custom meta value for custom post types\nadd_action('manage_posts_custom_column', 'ws365150_add_custom_column_data_pt', 10, 2 );\nfunction ws365150_add_custom_column_data_pt( $column_name, $post_id ) {\n switch ( $column_name ) {\n case 'ws365150_summary': // specified for this column assigned in the column title\n echo get_post_meta( $post_id, 'summary', true );\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<h3>3. add custom quick edit box</h3>\n<pre><code>// for page\nadd_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box', 10, 3 );\nfunction ws365150_custom_edit_box( $column_name, $post_type, $taxonomy ) {\n global $post;\n\n switch ( $post_type ) {\n case 'page':\n\n if( $column_name === 'page_remark' ): // same column title as defined in previous step\n ?>\n <?php // echo get_post_meta( $post->ID, 'remark', true ); ?>\n <fieldset class="inline-edit-col-right" id="#edit-">\n <div class="inline-edit-col">\n <label>\n <span class="title">Remark</span>\n <span class="input-text-wrap"><input type="text" name="remark" class="inline-edit-menu-order-input" value=""></span>\n </label>\n </div>\n </fieldset>\n <?php\n endif;\n // echo 'custom page field';\n break;\n \n default:\n break;\n }\n}\n\n// for Post + custom post type\nadd_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box_pt', 10, 3 );\nfunction ws365150_custom_edit_box_pt( $column_name, $post_type, $taxonomy ) {\n global $post;\n\n switch ( $post_type ) {\n case 'post':\n case 'episode':\n\n if( $column_name === 'ws365150_summary' ): // same column title as defined in previous step\n ?>\n <?php // echo get_post_meta( $post->ID, 'remark', true ); ?>\n <fieldset class="inline-edit-col-right" id="#edit-">\n <div class="inline-edit-col">\n <label>\n <span class="title">Summary</span>\n <span class="input-text-wrap"><input type="text" name="summary" class="inline-edit-menu-order-input" value=""></span>\n </label>\n </div>\n </fieldset>\n <?php\n endif;\n // echo 'custom page field';\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<h3>4. add save logic</h3>\n<pre><code>add_action( 'save_post', 'ws365150_update_custom_quickedit_box' );\nfunction ws365150_update_custom_quickedit_box() {\n // any checking logic here, skip and keep it simple for simple illustration purpose (nonce, existing of $_POST['remark'], ajax save and so on\n \n // remark in Page\n if( isset( $_POST ) && isset( $_POST['remark'] ) ) { // where remark is defined in the <input name="remark">\n update_post_meta($_POST['post_ID'], 'remark', $_POST['remark']);\n }\n\n // summary in Post, custom post type\n if( isset( $_POST ) && isset( $_POST['summary'] ) ) { // where summary is defined in the <input name="summary">\n update_post_meta($_POST['post_ID'], 'summary', $_POST['summary']);\n }\n \n // for debugging purpose in inspector, not necessary, enable this will break the saving but could see the ajax return\n // wp_send_json_success( array(\n // 'message' => 'Save test!',\n // 'post_data' => $_POST,\n // ) );\n return; // finish the function call\n}\n</code></pre>\n<h3>5. load script to modify original inline-edit-post function</h3>\n<pre><code>add_action( 'admin_enqueue_scripts', function( $page ) {\n\n // add page checking logic, this is a simple one, you may test post type and so on...\n if ( 'edit.php' != $page ) {\n return;\n }\n \n wp_enqueue_script( 'custom-quickedit-box', get_stylesheet_directory_uri() . '/ws365150_custom_quickedit_box.js', array( 'jquery', 'inline-edit-post' ) );\n});\n</code></pre>\n<h3>6. prepare the script file (ws365150_custom_quickedit_box.js, when test the above code, put in the theme folder)</h3>\n<pre><code>( function( $, wp ) {\n // clone from original function in inline-post-edit.js for override\n // actually no need to create an alias object, however, create an alias could be a note and mark of override without forgetting for later maintenance\n window.customInlineEditPost = window.inlineEditPost;\n\n // function override: add custom meta value, the base is copied from the source\n customInlineEditPost.edit = function(id) {\n // console.log( 'custom edit' );\n var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw;\n t.revert();\n\n if ( typeof(id) === 'object' ) {\n id = t.getId(id);\n }\n\n fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template'];\n if ( t.type === 'page' ) {\n fields.push('post_parent');\n }\n\n // Add the new edit row with an extra blank row underneath to maintain zebra striping.\n editRow = $('#inline-edit').clone(true);\n $( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );\n\n $(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>');\n\n // Populate fields in the quick edit window.\n rowData = $('#inline_'+id);\n if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {\n\n // The post author no longer has edit capabilities, so we need to add them to the list of authors.\n $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');\n }\n if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {\n $('label.inline-edit-author', editRow).hide();\n }\n\n // populate custom meta value\n if ( $( ':input[name="remark"]', editRow ).length === 1 ) {\n $( ':input[name="remark"]', editRow ).val( $('#post-' + id + ' .page_remark').text() );\n }\n\n if ( $( ':input[name="summary"]', editRow ).length === 1 ) {\n $( ':input[name="summary"]', editRow ).val( $('#post-' + id + ' .ws365150_summary').text() );\n }\n\n for ( f = 0; f < fields.length; f++ ) {\n val = $('.'+fields[f], rowData);\n\n /**\n * Replaces the image for a Twemoji(Twitter emoji) with it's alternate text.\n *\n * @returns Alternate text from the image.\n */\n val.find( 'img' ).replaceWith( function() { return this.alt; } );\n val = val.text();\n $(':input[name="' + fields[f] + '"]', editRow).val( val );\n }\n\n if ( $( '.comment_status', rowData ).text() === 'open' ) {\n $( 'input[name="comment_status"]', editRow ).prop( 'checked', true );\n }\n if ( $( '.ping_status', rowData ).text() === 'open' ) {\n $( 'input[name="ping_status"]', editRow ).prop( 'checked', true );\n }\n if ( $( '.sticky', rowData ).text() === 'sticky' ) {\n $( 'input[name="sticky"]', editRow ).prop( 'checked', true );\n }\n\n /**\n * Creates the select boxes for the categories.\n */\n $('.post_category', rowData).each(function(){\n var taxname,\n term_ids = $(this).text();\n\n if ( term_ids ) {\n taxname = $(this).attr('id').replace('_'+id, '');\n $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));\n }\n });\n\n /**\n * Gets all the taxonomies for live auto-fill suggestions when typing the name\n * of a tag.\n */\n $('.tags_input', rowData).each(function(){\n var terms = $(this),\n taxname = $(this).attr('id').replace('_' + id, ''),\n textarea = $('textarea.tax_input_' + taxname, editRow),\n comma = inlineEditL10n.comma;\n\n terms.find( 'img' ).replaceWith( function() { return this.alt; } );\n terms = terms.text();\n\n if ( terms ) {\n if ( ',' !== comma ) {\n terms = terms.replace(/,/g, comma);\n }\n textarea.val(terms);\n }\n\n textarea.wpTagsSuggest();\n });\n\n // Handle the post status.\n status = $('._status', rowData).text();\n if ( 'future' !== status ) {\n $('select[name="_status"] option[value="future"]', editRow).remove();\n }\n\n pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );\n if ( 'private' === status ) {\n $('input[name="keep_private"]', editRow).prop('checked', true);\n pw.val( '' ).prop( 'disabled', true );\n }\n\n // Remove the current page and children from the parent dropdown.\n pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);\n if ( pageOpt.length > 0 ) {\n pageLevel = pageOpt[0].className.split('-')[1];\n nextPage = pageOpt;\n while ( pageLoop ) {\n nextPage = nextPage.next('option');\n if ( nextPage.length === 0 ) {\n break;\n }\n\n nextLevel = nextPage[0].className.split('-')[1];\n\n if ( nextLevel <= pageLevel ) {\n pageLoop = false;\n } else {\n nextPage.remove();\n nextPage = pageOpt;\n }\n }\n pageOpt.remove();\n }\n\n $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();\n $('.ptitle', editRow).focus();\n\n return false;\n };\n})( jQuery, window.wp );\n</code></pre>\n<p>The above is for quick edit using <a href=\"https://developer.wordpress.org/reference/hooks/quick_edit_custom_box/\" rel=\"nofollow noreferrer\"><code>quick_edit_custom_box</code></a> hook, and you may need to take care of bulk edit also. You may explore more by reading and using <a href=\"https://developer.wordpress.org/reference/hooks/bulk_edit_custom_box/\" rel=\"nofollow noreferrer\"><code>bulk_edit_custom_box</code></a>.</p>\n"
},
{
"answer_id": 382368,
"author": "Дима Иванов",
"author_id": 201119,
"author_profile": "https://wordpress.stackexchange.com/users/201119",
"pm_score": 1,
"selected": false,
"text": "<p>i didn't rewrite full js\nin step 6 i added just</p>\n<pre><code>(function($){\n lesson_orders={};\n if($('.post_type_page').length && $('.post_type_page').val()=='resource'){\n $('#the-list tr').each(function(){\n id=$(this).find('.check-column input').val();\n val=$(this).find('.lesson_order').text();\n lesson_orders['edit-'+id]=val;\n });\n }\n $(document).on('focus','.ptitle',function(){\n id =$(this).closest('.inline-edit-row').attr('id');\n $('#'+id+' input[name="lesson_order"]').val(lesson_orders[''+id]);\n }); \n})(jQuery);\n</code></pre>\n"
}
] | 2020/04/27 | [
"https://wordpress.stackexchange.com/questions/365150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187384/"
] | How can I add a new column to quick edit and put a custom field in it? I read [this question](https://wordpress.stackexchange.com/a/199758) but one of the links lead to an error 404. I need a new column for my custom meta key, "`summary`" and post types, "`post`" and "`episode`". | There are a few steps to create the custom quick edit box and custom column
1. create a custom meta key (assumed that you have 1 already)
2. add custom admin column title and data (assumed that you want to shows the custom meta key in the column, if not, you may also modify a bit of the logic to accomplish the same effect because the principal is the same)
3. add custom quick edit box
4. add save logic
5. load script to modify original inline-edit-post function in order to support custom meta value
6. prepare the script file
This example is going to add a quick edit input box in post type `Page`. The following code is proved to work by putting in functions.php .
-------------------------------------------------------------------------------------------------------------------------------------------
### 1. create a custom meta key (assumed that you have 1 already)
I have prepared a custom meta key `remark` for post type `page`
### 2. add custom admin column title and data
for custom post type, you may use
Add column title
* For specific Screen ID [manage\_{$screen->id}\_columns](https://developer.wordpress.org/reference/hooks/manage_screen-id_columns/)
* Specificially for Page [manage\_pages\_columns](https://developer.wordpress.org/reference/hooks/manage_pages_columns/)
* Specificially for generic (default Post or custom post type) [manage\_posts\_custom\_column](https://developer.wordpress.org/reference/hooks/manage_posts_custom_column/) or for specific post type [manage\_{$post->post\_type}\_posts\_custom\_column](https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/) to add column data
Add column content
* Generic (default Post or custom post type) [manage\_posts\_columns](https://developer.wordpress.org/reference/hooks/manage_posts_columns/) with custom post type checking using post type argument or for specific post type [manage\_{$post\_type}\_posts\_columns](https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/) to add column title
The following is an example for post type Page as well as custom post type + default `Post` as an example for multiple post types setup.
```
// add custom column title for custom meta value
add_filter('manage_edit-page_columns', 'ws365150_add_custom_columns_title' );
function ws365150_add_custom_columns_title( $columns ) {
$columns['page_remark'] = 'Remark'; // you may use __() later on for translation support
return $columns;
}
// add custom column data with custom meta value
add_action('manage_pages_custom_column', 'ws365150_add_custom_column_data', 10, 2 );
function ws365150_add_custom_column_data( $column_name, $post_id ) {
switch ( $column_name ) {
case 'page_remark':
echo get_post_meta( $post_id, 'remark', true );
break;
default:
break;
}
}
```
The following is an example for custom post type `episode` + default `Post` with meta key `summary`
```
// add custom column title for custom meta value
// 'manage_pages_columns' or 'manage_edit-post_columns' both works
add_filter('manage_posts_columns', 'ws365150_add_custom_columns_title_pt', 10, 2 );
function ws365150_add_custom_columns_title_pt( $columns, $post_type ) {
switch ( $post_type ) {
case 'post':
case 'episode':
$columns['ws365150_summary'] = 'Summary'; // you may use __() later on for translation support
break;
default:
break;
}
return $columns;
}
// add custom column data with custom meta value for custom post types
add_action('manage_posts_custom_column', 'ws365150_add_custom_column_data_pt', 10, 2 );
function ws365150_add_custom_column_data_pt( $column_name, $post_id ) {
switch ( $column_name ) {
case 'ws365150_summary': // specified for this column assigned in the column title
echo get_post_meta( $post_id, 'summary', true );
break;
default:
break;
}
}
```
### 3. add custom quick edit box
```
// for page
add_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box', 10, 3 );
function ws365150_custom_edit_box( $column_name, $post_type, $taxonomy ) {
global $post;
switch ( $post_type ) {
case 'page':
if( $column_name === 'page_remark' ): // same column title as defined in previous step
?>
<?php // echo get_post_meta( $post->ID, 'remark', true ); ?>
<fieldset class="inline-edit-col-right" id="#edit-">
<div class="inline-edit-col">
<label>
<span class="title">Remark</span>
<span class="input-text-wrap"><input type="text" name="remark" class="inline-edit-menu-order-input" value=""></span>
</label>
</div>
</fieldset>
<?php
endif;
// echo 'custom page field';
break;
default:
break;
}
}
// for Post + custom post type
add_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box_pt', 10, 3 );
function ws365150_custom_edit_box_pt( $column_name, $post_type, $taxonomy ) {
global $post;
switch ( $post_type ) {
case 'post':
case 'episode':
if( $column_name === 'ws365150_summary' ): // same column title as defined in previous step
?>
<?php // echo get_post_meta( $post->ID, 'remark', true ); ?>
<fieldset class="inline-edit-col-right" id="#edit-">
<div class="inline-edit-col">
<label>
<span class="title">Summary</span>
<span class="input-text-wrap"><input type="text" name="summary" class="inline-edit-menu-order-input" value=""></span>
</label>
</div>
</fieldset>
<?php
endif;
// echo 'custom page field';
break;
default:
break;
}
}
```
### 4. add save logic
```
add_action( 'save_post', 'ws365150_update_custom_quickedit_box' );
function ws365150_update_custom_quickedit_box() {
// any checking logic here, skip and keep it simple for simple illustration purpose (nonce, existing of $_POST['remark'], ajax save and so on
// remark in Page
if( isset( $_POST ) && isset( $_POST['remark'] ) ) { // where remark is defined in the <input name="remark">
update_post_meta($_POST['post_ID'], 'remark', $_POST['remark']);
}
// summary in Post, custom post type
if( isset( $_POST ) && isset( $_POST['summary'] ) ) { // where summary is defined in the <input name="summary">
update_post_meta($_POST['post_ID'], 'summary', $_POST['summary']);
}
// for debugging purpose in inspector, not necessary, enable this will break the saving but could see the ajax return
// wp_send_json_success( array(
// 'message' => 'Save test!',
// 'post_data' => $_POST,
// ) );
return; // finish the function call
}
```
### 5. load script to modify original inline-edit-post function
```
add_action( 'admin_enqueue_scripts', function( $page ) {
// add page checking logic, this is a simple one, you may test post type and so on...
if ( 'edit.php' != $page ) {
return;
}
wp_enqueue_script( 'custom-quickedit-box', get_stylesheet_directory_uri() . '/ws365150_custom_quickedit_box.js', array( 'jquery', 'inline-edit-post' ) );
});
```
### 6. prepare the script file (ws365150\_custom\_quickedit\_box.js, when test the above code, put in the theme folder)
```
( function( $, wp ) {
// clone from original function in inline-post-edit.js for override
// actually no need to create an alias object, however, create an alias could be a note and mark of override without forgetting for later maintenance
window.customInlineEditPost = window.inlineEditPost;
// function override: add custom meta value, the base is copied from the source
customInlineEditPost.edit = function(id) {
// console.log( 'custom edit' );
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw;
t.revert();
if ( typeof(id) === 'object' ) {
id = t.getId(id);
}
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template'];
if ( t.type === 'page' ) {
fields.push('post_parent');
}
// Add the new edit row with an extra blank row underneath to maintain zebra striping.
editRow = $('#inline-edit').clone(true);
$( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );
$(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>');
// Populate fields in the quick edit window.
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// The post author no longer has edit capabilities, so we need to add them to the list of authors.
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// populate custom meta value
if ( $( ':input[name="remark"]', editRow ).length === 1 ) {
$( ':input[name="remark"]', editRow ).val( $('#post-' + id + ' .page_remark').text() );
}
if ( $( ':input[name="summary"]', editRow ).length === 1 ) {
$( ':input[name="summary"]', editRow ).val( $('#post-' + id + ' .ws365150_summary').text() );
}
for ( f = 0; f < fields.length; f++ ) {
val = $('.'+fields[f], rowData);
/**
* Replaces the image for a Twemoji(Twitter emoji) with it's alternate text.
*
* @returns Alternate text from the image.
*/
val.find( 'img' ).replaceWith( function() { return this.alt; } );
val = val.text();
$(':input[name="' + fields[f] + '"]', editRow).val( val );
}
if ( $( '.comment_status', rowData ).text() === 'open' ) {
$( 'input[name="comment_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.ping_status', rowData ).text() === 'open' ) {
$( 'input[name="ping_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.sticky', rowData ).text() === 'sticky' ) {
$( 'input[name="sticky"]', editRow ).prop( 'checked', true );
}
/**
* Creates the select boxes for the categories.
*/
$('.post_category', rowData).each(function(){
var taxname,
term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
/**
* Gets all the taxonomies for live auto-fill suggestions when typing the name
* of a tag.
*/
$('.tags_input', rowData).each(function(){
var terms = $(this),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
terms.find( 'img' ).replaceWith( function() { return this.alt; } );
terms = terms.text();
if ( terms ) {
if ( ',' !== comma ) {
terms = terms.replace(/,/g, comma);
}
textarea.val(terms);
}
textarea.wpTagsSuggest();
});
// Handle the post status.
status = $('._status', rowData).text();
if ( 'future' !== status ) {
$('select[name="_status"] option[value="future"]', editRow).remove();
}
pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );
if ( 'private' === status ) {
$('input[name="keep_private"]', editRow).prop('checked', true);
pw.val( '' ).prop( 'disabled', true );
}
// Remove the current page and children from the parent dropdown.
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if ( nextPage.length === 0 ) {
break;
}
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
};
})( jQuery, window.wp );
```
The above is for quick edit using [`quick_edit_custom_box`](https://developer.wordpress.org/reference/hooks/quick_edit_custom_box/) hook, and you may need to take care of bulk edit also. You may explore more by reading and using [`bulk_edit_custom_box`](https://developer.wordpress.org/reference/hooks/bulk_edit_custom_box/). |
365,162 | <p>I need to limit the number of posts that can be created.</p>
<p>I'd like any variation of total posts, posts per time period (month), by author (ID) or by role.</p>
<p>off-the-shelf plugins found so far in the repository are no longer supported.</p>
<p>is there a functions.php snippet or other approach that works consistently?</p>
<p>any suggestions? </p>
<p>thanks</p>
| [
{
"answer_id": 365166,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 5,
"selected": true,
"text": "<p>There are a few steps to create the custom quick edit box and custom column</p>\n<ol>\n<li>create a custom meta key (assumed that you have 1 already)</li>\n<li>add custom admin column title and data (assumed that you want to shows the custom meta key in the column, if not, you may also modify a bit of the logic to accomplish the same effect because the principal is the same)</li>\n<li>add custom quick edit box</li>\n<li>add save logic</li>\n<li>load script to modify original inline-edit-post function in order to support custom meta value</li>\n<li>prepare the script file</li>\n</ol>\n<h2>This example is going to add a quick edit input box in post type <code>Page</code>. The following code is proved to work by putting in functions.php .</h2>\n<h3>1. create a custom meta key (assumed that you have 1 already)</h3>\n<p>I have prepared a custom meta key <code>remark</code> for post type <code>page</code></p>\n<h3>2. add custom admin column title and data</h3>\n<p>for custom post type, you may use</p>\n<p>Add column title</p>\n<ul>\n<li>For specific Screen ID <a href=\"https://developer.wordpress.org/reference/hooks/manage_screen-id_columns/\" rel=\"nofollow noreferrer\">manage_{$screen->id}_columns</a></li>\n<li>Specificially for Page <a href=\"https://developer.wordpress.org/reference/hooks/manage_pages_columns/\" rel=\"nofollow noreferrer\">manage_pages_columns</a></li>\n<li>Specificially for generic (default Post or custom post type) <a href=\"https://developer.wordpress.org/reference/hooks/manage_posts_custom_column/\" rel=\"nofollow noreferrer\">manage_posts_custom_column</a> or for specific post type <a href=\"https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/\" rel=\"nofollow noreferrer\">manage_{$post->post_type}_posts_custom_column</a> to add column data</li>\n</ul>\n<p>Add column content</p>\n<ul>\n<li>Generic (default Post or custom post type) <a href=\"https://developer.wordpress.org/reference/hooks/manage_posts_columns/\" rel=\"nofollow noreferrer\">manage_posts_columns</a> with custom post type checking using post type argument or for specific post type <a href=\"https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/\" rel=\"nofollow noreferrer\">manage_{$post_type}_posts_columns</a> to add column title</li>\n</ul>\n<p>The following is an example for post type Page as well as custom post type + default <code>Post</code> as an example for multiple post types setup.</p>\n<pre><code>// add custom column title for custom meta value\nadd_filter('manage_edit-page_columns', 'ws365150_add_custom_columns_title' );\nfunction ws365150_add_custom_columns_title( $columns ) {\n $columns['page_remark'] = 'Remark'; // you may use __() later on for translation support\n \n return $columns;\n}\n \n// add custom column data with custom meta value\nadd_action('manage_pages_custom_column', 'ws365150_add_custom_column_data', 10, 2 );\nfunction ws365150_add_custom_column_data( $column_name, $post_id ) {\n switch ( $column_name ) {\n case 'page_remark':\n echo get_post_meta( $post_id, 'remark', true );\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<p>The following is an example for custom post type <code>episode</code> + default <code>Post</code> with meta key <code>summary</code></p>\n<pre><code>// add custom column title for custom meta value\n// 'manage_pages_columns' or 'manage_edit-post_columns' both works\nadd_filter('manage_posts_columns', 'ws365150_add_custom_columns_title_pt', 10, 2 );\nfunction ws365150_add_custom_columns_title_pt( $columns, $post_type ) {\n switch ( $post_type ) {\n case 'post':\n case 'episode':\n $columns['ws365150_summary'] = 'Summary'; // you may use __() later on for translation support\n break;\n \n default:\n \n break;\n }\n \n return $columns;\n}\n \n// add custom column data with custom meta value for custom post types\nadd_action('manage_posts_custom_column', 'ws365150_add_custom_column_data_pt', 10, 2 );\nfunction ws365150_add_custom_column_data_pt( $column_name, $post_id ) {\n switch ( $column_name ) {\n case 'ws365150_summary': // specified for this column assigned in the column title\n echo get_post_meta( $post_id, 'summary', true );\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<h3>3. add custom quick edit box</h3>\n<pre><code>// for page\nadd_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box', 10, 3 );\nfunction ws365150_custom_edit_box( $column_name, $post_type, $taxonomy ) {\n global $post;\n\n switch ( $post_type ) {\n case 'page':\n\n if( $column_name === 'page_remark' ): // same column title as defined in previous step\n ?>\n <?php // echo get_post_meta( $post->ID, 'remark', true ); ?>\n <fieldset class="inline-edit-col-right" id="#edit-">\n <div class="inline-edit-col">\n <label>\n <span class="title">Remark</span>\n <span class="input-text-wrap"><input type="text" name="remark" class="inline-edit-menu-order-input" value=""></span>\n </label>\n </div>\n </fieldset>\n <?php\n endif;\n // echo 'custom page field';\n break;\n \n default:\n break;\n }\n}\n\n// for Post + custom post type\nadd_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box_pt', 10, 3 );\nfunction ws365150_custom_edit_box_pt( $column_name, $post_type, $taxonomy ) {\n global $post;\n\n switch ( $post_type ) {\n case 'post':\n case 'episode':\n\n if( $column_name === 'ws365150_summary' ): // same column title as defined in previous step\n ?>\n <?php // echo get_post_meta( $post->ID, 'remark', true ); ?>\n <fieldset class="inline-edit-col-right" id="#edit-">\n <div class="inline-edit-col">\n <label>\n <span class="title">Summary</span>\n <span class="input-text-wrap"><input type="text" name="summary" class="inline-edit-menu-order-input" value=""></span>\n </label>\n </div>\n </fieldset>\n <?php\n endif;\n // echo 'custom page field';\n break;\n \n default:\n break;\n }\n}\n</code></pre>\n<h3>4. add save logic</h3>\n<pre><code>add_action( 'save_post', 'ws365150_update_custom_quickedit_box' );\nfunction ws365150_update_custom_quickedit_box() {\n // any checking logic here, skip and keep it simple for simple illustration purpose (nonce, existing of $_POST['remark'], ajax save and so on\n \n // remark in Page\n if( isset( $_POST ) && isset( $_POST['remark'] ) ) { // where remark is defined in the <input name="remark">\n update_post_meta($_POST['post_ID'], 'remark', $_POST['remark']);\n }\n\n // summary in Post, custom post type\n if( isset( $_POST ) && isset( $_POST['summary'] ) ) { // where summary is defined in the <input name="summary">\n update_post_meta($_POST['post_ID'], 'summary', $_POST['summary']);\n }\n \n // for debugging purpose in inspector, not necessary, enable this will break the saving but could see the ajax return\n // wp_send_json_success( array(\n // 'message' => 'Save test!',\n // 'post_data' => $_POST,\n // ) );\n return; // finish the function call\n}\n</code></pre>\n<h3>5. load script to modify original inline-edit-post function</h3>\n<pre><code>add_action( 'admin_enqueue_scripts', function( $page ) {\n\n // add page checking logic, this is a simple one, you may test post type and so on...\n if ( 'edit.php' != $page ) {\n return;\n }\n \n wp_enqueue_script( 'custom-quickedit-box', get_stylesheet_directory_uri() . '/ws365150_custom_quickedit_box.js', array( 'jquery', 'inline-edit-post' ) );\n});\n</code></pre>\n<h3>6. prepare the script file (ws365150_custom_quickedit_box.js, when test the above code, put in the theme folder)</h3>\n<pre><code>( function( $, wp ) {\n // clone from original function in inline-post-edit.js for override\n // actually no need to create an alias object, however, create an alias could be a note and mark of override without forgetting for later maintenance\n window.customInlineEditPost = window.inlineEditPost;\n\n // function override: add custom meta value, the base is copied from the source\n customInlineEditPost.edit = function(id) {\n // console.log( 'custom edit' );\n var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw;\n t.revert();\n\n if ( typeof(id) === 'object' ) {\n id = t.getId(id);\n }\n\n fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template'];\n if ( t.type === 'page' ) {\n fields.push('post_parent');\n }\n\n // Add the new edit row with an extra blank row underneath to maintain zebra striping.\n editRow = $('#inline-edit').clone(true);\n $( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );\n\n $(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>');\n\n // Populate fields in the quick edit window.\n rowData = $('#inline_'+id);\n if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {\n\n // The post author no longer has edit capabilities, so we need to add them to the list of authors.\n $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');\n }\n if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {\n $('label.inline-edit-author', editRow).hide();\n }\n\n // populate custom meta value\n if ( $( ':input[name="remark"]', editRow ).length === 1 ) {\n $( ':input[name="remark"]', editRow ).val( $('#post-' + id + ' .page_remark').text() );\n }\n\n if ( $( ':input[name="summary"]', editRow ).length === 1 ) {\n $( ':input[name="summary"]', editRow ).val( $('#post-' + id + ' .ws365150_summary').text() );\n }\n\n for ( f = 0; f < fields.length; f++ ) {\n val = $('.'+fields[f], rowData);\n\n /**\n * Replaces the image for a Twemoji(Twitter emoji) with it's alternate text.\n *\n * @returns Alternate text from the image.\n */\n val.find( 'img' ).replaceWith( function() { return this.alt; } );\n val = val.text();\n $(':input[name="' + fields[f] + '"]', editRow).val( val );\n }\n\n if ( $( '.comment_status', rowData ).text() === 'open' ) {\n $( 'input[name="comment_status"]', editRow ).prop( 'checked', true );\n }\n if ( $( '.ping_status', rowData ).text() === 'open' ) {\n $( 'input[name="ping_status"]', editRow ).prop( 'checked', true );\n }\n if ( $( '.sticky', rowData ).text() === 'sticky' ) {\n $( 'input[name="sticky"]', editRow ).prop( 'checked', true );\n }\n\n /**\n * Creates the select boxes for the categories.\n */\n $('.post_category', rowData).each(function(){\n var taxname,\n term_ids = $(this).text();\n\n if ( term_ids ) {\n taxname = $(this).attr('id').replace('_'+id, '');\n $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));\n }\n });\n\n /**\n * Gets all the taxonomies for live auto-fill suggestions when typing the name\n * of a tag.\n */\n $('.tags_input', rowData).each(function(){\n var terms = $(this),\n taxname = $(this).attr('id').replace('_' + id, ''),\n textarea = $('textarea.tax_input_' + taxname, editRow),\n comma = inlineEditL10n.comma;\n\n terms.find( 'img' ).replaceWith( function() { return this.alt; } );\n terms = terms.text();\n\n if ( terms ) {\n if ( ',' !== comma ) {\n terms = terms.replace(/,/g, comma);\n }\n textarea.val(terms);\n }\n\n textarea.wpTagsSuggest();\n });\n\n // Handle the post status.\n status = $('._status', rowData).text();\n if ( 'future' !== status ) {\n $('select[name="_status"] option[value="future"]', editRow).remove();\n }\n\n pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );\n if ( 'private' === status ) {\n $('input[name="keep_private"]', editRow).prop('checked', true);\n pw.val( '' ).prop( 'disabled', true );\n }\n\n // Remove the current page and children from the parent dropdown.\n pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);\n if ( pageOpt.length > 0 ) {\n pageLevel = pageOpt[0].className.split('-')[1];\n nextPage = pageOpt;\n while ( pageLoop ) {\n nextPage = nextPage.next('option');\n if ( nextPage.length === 0 ) {\n break;\n }\n\n nextLevel = nextPage[0].className.split('-')[1];\n\n if ( nextLevel <= pageLevel ) {\n pageLoop = false;\n } else {\n nextPage.remove();\n nextPage = pageOpt;\n }\n }\n pageOpt.remove();\n }\n\n $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();\n $('.ptitle', editRow).focus();\n\n return false;\n };\n})( jQuery, window.wp );\n</code></pre>\n<p>The above is for quick edit using <a href=\"https://developer.wordpress.org/reference/hooks/quick_edit_custom_box/\" rel=\"nofollow noreferrer\"><code>quick_edit_custom_box</code></a> hook, and you may need to take care of bulk edit also. You may explore more by reading and using <a href=\"https://developer.wordpress.org/reference/hooks/bulk_edit_custom_box/\" rel=\"nofollow noreferrer\"><code>bulk_edit_custom_box</code></a>.</p>\n"
},
{
"answer_id": 382368,
"author": "Дима Иванов",
"author_id": 201119,
"author_profile": "https://wordpress.stackexchange.com/users/201119",
"pm_score": 1,
"selected": false,
"text": "<p>i didn't rewrite full js\nin step 6 i added just</p>\n<pre><code>(function($){\n lesson_orders={};\n if($('.post_type_page').length && $('.post_type_page').val()=='resource'){\n $('#the-list tr').each(function(){\n id=$(this).find('.check-column input').val();\n val=$(this).find('.lesson_order').text();\n lesson_orders['edit-'+id]=val;\n });\n }\n $(document).on('focus','.ptitle',function(){\n id =$(this).closest('.inline-edit-row').attr('id');\n $('#'+id+' input[name="lesson_order"]').val(lesson_orders[''+id]);\n }); \n})(jQuery);\n</code></pre>\n"
}
] | 2020/04/27 | [
"https://wordpress.stackexchange.com/questions/365162",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121961/"
] | I need to limit the number of posts that can be created.
I'd like any variation of total posts, posts per time period (month), by author (ID) or by role.
off-the-shelf plugins found so far in the repository are no longer supported.
is there a functions.php snippet or other approach that works consistently?
any suggestions?
thanks | There are a few steps to create the custom quick edit box and custom column
1. create a custom meta key (assumed that you have 1 already)
2. add custom admin column title and data (assumed that you want to shows the custom meta key in the column, if not, you may also modify a bit of the logic to accomplish the same effect because the principal is the same)
3. add custom quick edit box
4. add save logic
5. load script to modify original inline-edit-post function in order to support custom meta value
6. prepare the script file
This example is going to add a quick edit input box in post type `Page`. The following code is proved to work by putting in functions.php .
-------------------------------------------------------------------------------------------------------------------------------------------
### 1. create a custom meta key (assumed that you have 1 already)
I have prepared a custom meta key `remark` for post type `page`
### 2. add custom admin column title and data
for custom post type, you may use
Add column title
* For specific Screen ID [manage\_{$screen->id}\_columns](https://developer.wordpress.org/reference/hooks/manage_screen-id_columns/)
* Specificially for Page [manage\_pages\_columns](https://developer.wordpress.org/reference/hooks/manage_pages_columns/)
* Specificially for generic (default Post or custom post type) [manage\_posts\_custom\_column](https://developer.wordpress.org/reference/hooks/manage_posts_custom_column/) or for specific post type [manage\_{$post->post\_type}\_posts\_custom\_column](https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/) to add column data
Add column content
* Generic (default Post or custom post type) [manage\_posts\_columns](https://developer.wordpress.org/reference/hooks/manage_posts_columns/) with custom post type checking using post type argument or for specific post type [manage\_{$post\_type}\_posts\_columns](https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/) to add column title
The following is an example for post type Page as well as custom post type + default `Post` as an example for multiple post types setup.
```
// add custom column title for custom meta value
add_filter('manage_edit-page_columns', 'ws365150_add_custom_columns_title' );
function ws365150_add_custom_columns_title( $columns ) {
$columns['page_remark'] = 'Remark'; // you may use __() later on for translation support
return $columns;
}
// add custom column data with custom meta value
add_action('manage_pages_custom_column', 'ws365150_add_custom_column_data', 10, 2 );
function ws365150_add_custom_column_data( $column_name, $post_id ) {
switch ( $column_name ) {
case 'page_remark':
echo get_post_meta( $post_id, 'remark', true );
break;
default:
break;
}
}
```
The following is an example for custom post type `episode` + default `Post` with meta key `summary`
```
// add custom column title for custom meta value
// 'manage_pages_columns' or 'manage_edit-post_columns' both works
add_filter('manage_posts_columns', 'ws365150_add_custom_columns_title_pt', 10, 2 );
function ws365150_add_custom_columns_title_pt( $columns, $post_type ) {
switch ( $post_type ) {
case 'post':
case 'episode':
$columns['ws365150_summary'] = 'Summary'; // you may use __() later on for translation support
break;
default:
break;
}
return $columns;
}
// add custom column data with custom meta value for custom post types
add_action('manage_posts_custom_column', 'ws365150_add_custom_column_data_pt', 10, 2 );
function ws365150_add_custom_column_data_pt( $column_name, $post_id ) {
switch ( $column_name ) {
case 'ws365150_summary': // specified for this column assigned in the column title
echo get_post_meta( $post_id, 'summary', true );
break;
default:
break;
}
}
```
### 3. add custom quick edit box
```
// for page
add_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box', 10, 3 );
function ws365150_custom_edit_box( $column_name, $post_type, $taxonomy ) {
global $post;
switch ( $post_type ) {
case 'page':
if( $column_name === 'page_remark' ): // same column title as defined in previous step
?>
<?php // echo get_post_meta( $post->ID, 'remark', true ); ?>
<fieldset class="inline-edit-col-right" id="#edit-">
<div class="inline-edit-col">
<label>
<span class="title">Remark</span>
<span class="input-text-wrap"><input type="text" name="remark" class="inline-edit-menu-order-input" value=""></span>
</label>
</div>
</fieldset>
<?php
endif;
// echo 'custom page field';
break;
default:
break;
}
}
// for Post + custom post type
add_action( 'quick_edit_custom_box', 'ws365150_custom_edit_box_pt', 10, 3 );
function ws365150_custom_edit_box_pt( $column_name, $post_type, $taxonomy ) {
global $post;
switch ( $post_type ) {
case 'post':
case 'episode':
if( $column_name === 'ws365150_summary' ): // same column title as defined in previous step
?>
<?php // echo get_post_meta( $post->ID, 'remark', true ); ?>
<fieldset class="inline-edit-col-right" id="#edit-">
<div class="inline-edit-col">
<label>
<span class="title">Summary</span>
<span class="input-text-wrap"><input type="text" name="summary" class="inline-edit-menu-order-input" value=""></span>
</label>
</div>
</fieldset>
<?php
endif;
// echo 'custom page field';
break;
default:
break;
}
}
```
### 4. add save logic
```
add_action( 'save_post', 'ws365150_update_custom_quickedit_box' );
function ws365150_update_custom_quickedit_box() {
// any checking logic here, skip and keep it simple for simple illustration purpose (nonce, existing of $_POST['remark'], ajax save and so on
// remark in Page
if( isset( $_POST ) && isset( $_POST['remark'] ) ) { // where remark is defined in the <input name="remark">
update_post_meta($_POST['post_ID'], 'remark', $_POST['remark']);
}
// summary in Post, custom post type
if( isset( $_POST ) && isset( $_POST['summary'] ) ) { // where summary is defined in the <input name="summary">
update_post_meta($_POST['post_ID'], 'summary', $_POST['summary']);
}
// for debugging purpose in inspector, not necessary, enable this will break the saving but could see the ajax return
// wp_send_json_success( array(
// 'message' => 'Save test!',
// 'post_data' => $_POST,
// ) );
return; // finish the function call
}
```
### 5. load script to modify original inline-edit-post function
```
add_action( 'admin_enqueue_scripts', function( $page ) {
// add page checking logic, this is a simple one, you may test post type and so on...
if ( 'edit.php' != $page ) {
return;
}
wp_enqueue_script( 'custom-quickedit-box', get_stylesheet_directory_uri() . '/ws365150_custom_quickedit_box.js', array( 'jquery', 'inline-edit-post' ) );
});
```
### 6. prepare the script file (ws365150\_custom\_quickedit\_box.js, when test the above code, put in the theme folder)
```
( function( $, wp ) {
// clone from original function in inline-post-edit.js for override
// actually no need to create an alias object, however, create an alias could be a note and mark of override without forgetting for later maintenance
window.customInlineEditPost = window.inlineEditPost;
// function override: add custom meta value, the base is copied from the source
customInlineEditPost.edit = function(id) {
// console.log( 'custom edit' );
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw;
t.revert();
if ( typeof(id) === 'object' ) {
id = t.getId(id);
}
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template'];
if ( t.type === 'page' ) {
fields.push('post_parent');
}
// Add the new edit row with an extra blank row underneath to maintain zebra striping.
editRow = $('#inline-edit').clone(true);
$( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );
$(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>');
// Populate fields in the quick edit window.
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// The post author no longer has edit capabilities, so we need to add them to the list of authors.
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// populate custom meta value
if ( $( ':input[name="remark"]', editRow ).length === 1 ) {
$( ':input[name="remark"]', editRow ).val( $('#post-' + id + ' .page_remark').text() );
}
if ( $( ':input[name="summary"]', editRow ).length === 1 ) {
$( ':input[name="summary"]', editRow ).val( $('#post-' + id + ' .ws365150_summary').text() );
}
for ( f = 0; f < fields.length; f++ ) {
val = $('.'+fields[f], rowData);
/**
* Replaces the image for a Twemoji(Twitter emoji) with it's alternate text.
*
* @returns Alternate text from the image.
*/
val.find( 'img' ).replaceWith( function() { return this.alt; } );
val = val.text();
$(':input[name="' + fields[f] + '"]', editRow).val( val );
}
if ( $( '.comment_status', rowData ).text() === 'open' ) {
$( 'input[name="comment_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.ping_status', rowData ).text() === 'open' ) {
$( 'input[name="ping_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.sticky', rowData ).text() === 'sticky' ) {
$( 'input[name="sticky"]', editRow ).prop( 'checked', true );
}
/**
* Creates the select boxes for the categories.
*/
$('.post_category', rowData).each(function(){
var taxname,
term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
/**
* Gets all the taxonomies for live auto-fill suggestions when typing the name
* of a tag.
*/
$('.tags_input', rowData).each(function(){
var terms = $(this),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
terms.find( 'img' ).replaceWith( function() { return this.alt; } );
terms = terms.text();
if ( terms ) {
if ( ',' !== comma ) {
terms = terms.replace(/,/g, comma);
}
textarea.val(terms);
}
textarea.wpTagsSuggest();
});
// Handle the post status.
status = $('._status', rowData).text();
if ( 'future' !== status ) {
$('select[name="_status"] option[value="future"]', editRow).remove();
}
pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );
if ( 'private' === status ) {
$('input[name="keep_private"]', editRow).prop('checked', true);
pw.val( '' ).prop( 'disabled', true );
}
// Remove the current page and children from the parent dropdown.
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if ( nextPage.length === 0 ) {
break;
}
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
};
})( jQuery, window.wp );
```
The above is for quick edit using [`quick_edit_custom_box`](https://developer.wordpress.org/reference/hooks/quick_edit_custom_box/) hook, and you may need to take care of bulk edit also. You may explore more by reading and using [`bulk_edit_custom_box`](https://developer.wordpress.org/reference/hooks/bulk_edit_custom_box/). |
365,281 | <p>i create ajax request in
<strong>functions.php</strong></p>
<pre><code>function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'cc_ajax_object',
array( 'ajax_url' => admin_url( 'ajaxrequest.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_footer', 'add_js_to_wp_footer' );
function add_js_to_wp_footer()
{
?>
<script type="text/javascript">
jQuery('.all-categories').click(function($){
jQuery.ajax({
type : "post",
dataType : "json",
url : cc_ajax_object.ajax_url,
data: {
'action': 'get_products',
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
</script>
</code></pre>
<p>and in <strong>ajaxrequest.php</strong> </p>
<pre><code><?php
/* ajaxrequest page */
function get_products()
{
echo "test";
}
</code></pre>
<p>no errors in network but data = null in console </p>
<p>whats is the mistake ????</p>
| [
{
"answer_id": 365287,
"author": "sialfa",
"author_id": 177581,
"author_profile": "https://wordpress.stackexchange.com/users/177581",
"pm_score": 0,
"selected": false,
"text": "<p>Forget about the separate <code>ajaxrequest.php</code> file. Your error is in the <code>wp_localize_script</code>, you need to point to the <code>admin-ajax.php</code> file when you localize the script: </p>\n\n<pre><code>function my_enqueue() {\n wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );\n wp_localize_script( 'ajax-script', 'cc_ajax_object', \n array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_enqueue' );\n</code></pre>\n\n<p>Another thing is about the function that will manage the response, instead of requiring it in your theme <code>function.php</code> file, put the code directly in the theme function file.</p>\n"
},
{
"answer_id": 365291,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 2,
"selected": true,
"text": "<p>You can take reference from below code. Remove your ajaxrequest.php file, no need of that file because i have added ajaxrequest.php file's code in active theme's functions.php file.</p>\n\n<p>I have changed ajax url and add js script code in script.js file. I have tested and it is working for me. let me know if this works for you.</p>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function my_enqueue() {\n wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );\n wp_localize_script( 'ajax-script', 'cc_ajax_object', \n array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_enqueue' );\n\n\nadd_action('wp_ajax_get_products', 'get_products' ); // executed when logged in\nadd_action('wp_ajax_nopriv_get_products', 'get_products' ); // executed when logged out\nfunction get_products()\n{\n echo \"test\";\n wp_die();\n}\n</code></pre>\n\n<p><strong>script.js</strong></p>\n\n<pre><code>jQuery(document).ready(function($) {\n jQuery('.all-categories').click(function($){\n jQuery.ajax({\n type : \"post\",\n dataType : \"json\",\n url : cc_ajax_object.ajax_url,\n data: {\n 'action': 'get_products', \n },\n success:function(data) {\n // This outputs the result of the ajax request\n console.log(data);\n },\n error: function(errorThrown){\n console.log(errorThrown);\n }\n });\n });\n});\n</code></pre>\n"
}
] | 2020/04/28 | [
"https://wordpress.stackexchange.com/questions/365281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186508/"
] | i create ajax request in
**functions.php**
```
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'cc_ajax_object',
array( 'ajax_url' => admin_url( 'ajaxrequest.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_footer', 'add_js_to_wp_footer' );
function add_js_to_wp_footer()
{
?>
<script type="text/javascript">
jQuery('.all-categories').click(function($){
jQuery.ajax({
type : "post",
dataType : "json",
url : cc_ajax_object.ajax_url,
data: {
'action': 'get_products',
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
</script>
```
and in **ajaxrequest.php**
```
<?php
/* ajaxrequest page */
function get_products()
{
echo "test";
}
```
no errors in network but data = null in console
whats is the mistake ???? | You can take reference from below code. Remove your ajaxrequest.php file, no need of that file because i have added ajaxrequest.php file's code in active theme's functions.php file.
I have changed ajax url and add js script code in script.js file. I have tested and it is working for me. let me know if this works for you.
**functions.php**
```
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'cc_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('wp_ajax_get_products', 'get_products' ); // executed when logged in
add_action('wp_ajax_nopriv_get_products', 'get_products' ); // executed when logged out
function get_products()
{
echo "test";
wp_die();
}
```
**script.js**
```
jQuery(document).ready(function($) {
jQuery('.all-categories').click(function($){
jQuery.ajax({
type : "post",
dataType : "json",
url : cc_ajax_object.ajax_url,
data: {
'action': 'get_products',
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
``` |
365,303 | <p>I am getting below error in Admin Panel.</p>
<p><strong>Deprecated : contextual_help has been deprecated since version 3.3.0. Use get_current_screen () -> add_help_tab (), get_current_screen () -> remove_help_tab () instead. in /var/www/html/invertir/wp-includes/functions.php on line 5088</strong></p>
<p><a href="https://i.stack.imgur.com/AfAbq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AfAbq.png" alt="enter image description here"></a></p>
<p>I got below code in <em>/var/www/html/invertir/wp-includes/functions.php on line 5088</em></p>
<pre><code>if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
$message = empty( $message ) ? '' : ' ' . $message;
if ( ! is_null( $replacement ) ) {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
__( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
$hook,
$version,
$replacement
) . $message,
E_USER_DEPRECATED
);
} else {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number. */
__( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
$hook,
$version
) . $message,
E_USER_DEPRECATED
);
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/VVL2C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VVL2C.png" alt="enter image description here"></a></p>
<p>How can I solve the issue ?</p>
| [
{
"answer_id": 365306,
"author": "Nate",
"author_id": 186686,
"author_profile": "https://wordpress.stackexchange.com/users/186686",
"pm_score": 3,
"selected": true,
"text": "<p>I see that you have a lot of updates, first, update everything, then you update the plugins, themes, then if that does not work then disable all your plugins and themes and see if that fixes the issue. If it does then you enable one plugin at a time until you have all your plugins enabled, if it appears again then you know that it is a plugin and you can remove your plugins, if it does not appear then you enable all your themes one at a time and do the same thing the plugins. </p>\n"
},
{
"answer_id": 375539,
"author": "Tom Hale",
"author_id": 80672,
"author_profile": "https://wordpress.stackexchange.com/users/80672",
"pm_score": 0,
"selected": false,
"text": "<p>For me it was a plugin with <code>MailChimp</code> in the title. I disabled all of these as I'm now using MailerLite, and the issue went away.</p>\n<p>I hope this helps narrow down the offending plugin search for others.</p>\n"
}
] | 2020/04/28 | [
"https://wordpress.stackexchange.com/questions/365303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65189/"
] | I am getting below error in Admin Panel.
**Deprecated : contextual\_help has been deprecated since version 3.3.0. Use get\_current\_screen () -> add\_help\_tab (), get\_current\_screen () -> remove\_help\_tab () instead. in /var/www/html/invertir/wp-includes/functions.php on line 5088**
[](https://i.stack.imgur.com/AfAbq.png)
I got below code in */var/www/html/invertir/wp-includes/functions.php on line 5088*
```
if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
$message = empty( $message ) ? '' : ' ' . $message;
if ( ! is_null( $replacement ) ) {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
__( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
$hook,
$version,
$replacement
) . $message,
E_USER_DEPRECATED
);
} else {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number. */
__( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
$hook,
$version
) . $message,
E_USER_DEPRECATED
);
}
}
}
```
[](https://i.stack.imgur.com/VVL2C.png)
How can I solve the issue ? | I see that you have a lot of updates, first, update everything, then you update the plugins, themes, then if that does not work then disable all your plugins and themes and see if that fixes the issue. If it does then you enable one plugin at a time until you have all your plugins enabled, if it appears again then you know that it is a plugin and you can remove your plugins, if it does not appear then you enable all your themes one at a time and do the same thing the plugins. |
365,308 | <p>How do I add a shortcode without plugins? I am going to add a shortcode that will give a count of views on a page. </p>
| [
{
"answer_id": 365311,
"author": "Drmzindec",
"author_id": 74335,
"author_profile": "https://wordpress.stackexchange.com/users/74335",
"pm_score": 2,
"selected": false,
"text": "<p>There is a whole section on the WordPress Codex on this: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">Shortcode API</a></p>\n\n<pre><code>[foobar]\n\nfunction foobar_func( $atts ){\n return \"foo and bar\";\n}\nadd_shortcode( 'foobar', 'foobar_func' );\n</code></pre>\n\n<p>With attributes:</p>\n\n<p>[bartag foo=\"foo-value\"]</p>\n\n<pre><code>function bartag_func( $atts ) {\n $a = shortcode_atts( array(\n 'foo' => 'something',\n 'bar' => 'something else',\n ), $atts );\n\n return \"foo = {$a['foo']}\";\n}\nadd_shortcode( 'bartag', 'bartag_func' );\n</code></pre>\n"
},
{
"answer_id": 365313,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 2,
"selected": true,
"text": "<p>You'll probably need to modify this a bit to ensure things get placed where you want them but here's something I wrote that counts views on <code>posts</code> and displays the view counts for administrators:</p>\n\n<pre><code> //ADD TRACKER FUNCTION TO ALL SINGLE VIEWS\n function custom_hook_tracker( $post_id ) {\n if( !is_single() ) return;\n if( empty( $post_id ) ) {\n global $post;\n $post_id = $post->ID;\n }\n custom_track_post_views( $post_id );\n }\n add_action( 'wp_head', 'custom_hook_tracker' );\n\n //ADD VIEW TRACKER\n function custom_track_post_views( $postID ) {\n $count_key = 'custom_view_count';\n $count = get_post_meta( $postID, $count_key, true );\n if( $count=='' ) {\n $count = 0;\n delete_post_meta( $postID, $count_key );\n add_post_meta( $postID, $count_key, '0' );\n } else {\n $count++;\n update_post_meta( $postID, $count_key, $count );\n }\n //REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG\n if( is_single() && current_user_can( 'administrator' ) ) { //remove or adjust the '&& current_user_can( 'administrator' )' to modify who CAN see the counts\n //ALSO REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG\n echo '<div style=\"position:absolute;top:2.75rem;width:auto;display:block;float:left;background:#FFF;border-radius:4px;box-shadow:#333 1px 1px 4px;padding:0.25rem 0.5rem;margin-left:-5px;color:#777;\"><small>Views: '.$count.'</small></div>';\n }\n }\n //REMOVE PRE-FETCHING TO KEEP COUNTS ACCURATE\n remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);\n</code></pre>\n\n<p>Ok, I couldn't just leave it - here's the template tag:</p>\n\n<pre><code>function custom_view_counts() {\n $count_key = 'custom_view_count';\n $count = get_post_meta( $postID, $count_key, true );\n echo '<div class=\"view-tracker\"><small>Views: '.$count.'</small></div>';\n}\n</code></pre>\n\n<p>Then to display it drop this in your theme files exactly where you want it to appear:\n<code><?php custom_view_counts() ;?></code></p>\n\n<p>You'll need to write css that address/styles/targets the <code>.view-tracker</code> class/div.</p>\n\n<p>You can basically build your own plugin, or just drop all of the above into your functions.php.</p>\n"
},
{
"answer_id": 365367,
"author": "cssler",
"author_id": 187094,
"author_profile": "https://wordpress.stackexchange.com/users/187094",
"pm_score": 2,
"selected": false,
"text": "<p>Please check the official WordPress Shortcode API. You can create custom shortcodes easily without any Plugin.</p>\n\n<p><strong>Code Example:</strong></p>\n\n<pre><code>// HOW TO EMBED \n// Shortcode: [new_shortcode] \n\nfunction create_newshortcode_shortcode() {\n // Do whatever you want \n} \nadd_shortcode( 'new_shortcode', 'create_newshortcode_shortcode' );\n</code></pre>\n\n<p>Links you can help:</p>\n\n<p><a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a></p>\n\n<p><a href=\"https://app.wp-monkey.com/generators/shortcode-generator\" rel=\"nofollow noreferrer\">https://app.wp-monkey.com/generators/shortcode-generator</a></p>\n"
}
] | 2020/04/28 | [
"https://wordpress.stackexchange.com/questions/365308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186686/"
] | How do I add a shortcode without plugins? I am going to add a shortcode that will give a count of views on a page. | You'll probably need to modify this a bit to ensure things get placed where you want them but here's something I wrote that counts views on `posts` and displays the view counts for administrators:
```
//ADD TRACKER FUNCTION TO ALL SINGLE VIEWS
function custom_hook_tracker( $post_id ) {
if( !is_single() ) return;
if( empty( $post_id ) ) {
global $post;
$post_id = $post->ID;
}
custom_track_post_views( $post_id );
}
add_action( 'wp_head', 'custom_hook_tracker' );
//ADD VIEW TRACKER
function custom_track_post_views( $postID ) {
$count_key = 'custom_view_count';
$count = get_post_meta( $postID, $count_key, true );
if( $count=='' ) {
$count = 0;
delete_post_meta( $postID, $count_key );
add_post_meta( $postID, $count_key, '0' );
} else {
$count++;
update_post_meta( $postID, $count_key, $count );
}
//REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG
if( is_single() && current_user_can( 'administrator' ) ) { //remove or adjust the '&& current_user_can( 'administrator' )' to modify who CAN see the counts
//ALSO REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG
echo '<div style="position:absolute;top:2.75rem;width:auto;display:block;float:left;background:#FFF;border-radius:4px;box-shadow:#333 1px 1px 4px;padding:0.25rem 0.5rem;margin-left:-5px;color:#777;"><small>Views: '.$count.'</small></div>';
}
}
//REMOVE PRE-FETCHING TO KEEP COUNTS ACCURATE
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
```
Ok, I couldn't just leave it - here's the template tag:
```
function custom_view_counts() {
$count_key = 'custom_view_count';
$count = get_post_meta( $postID, $count_key, true );
echo '<div class="view-tracker"><small>Views: '.$count.'</small></div>';
}
```
Then to display it drop this in your theme files exactly where you want it to appear:
`<?php custom_view_counts() ;?>`
You'll need to write css that address/styles/targets the `.view-tracker` class/div.
You can basically build your own plugin, or just drop all of the above into your functions.php. |
365,394 | <p>I have custom fields to display in a post. But all of the custom fields are displaying in a single continuous line, while i want them in separate lines. I am not a coder. I tried <code><br>, <li></code> but still no luck. I also searched in stack exchange and web for similar problem, but could not get answer. Please help.</p>
<p>Below is the Code i have in single.php after - <code>while ( have_posts() ) : the_post();
$key_name = get_post_custom_values ($key = 'country'); echo 'Country : ', $key_name[0];
$key_name = get_post_custom_values ($key = 'status'); echo 'Status : ', $key_name[0];</code></p>
<p>The result in the post is as below:</p>
<p>Country : Saudi ArabiaStatus : Announced</p>
<p>I want it to appear it like the one below:</p>
<p>Country : Saudi Arabia</p>
<p>Status : Announced</p>
| [
{
"answer_id": 365311,
"author": "Drmzindec",
"author_id": 74335,
"author_profile": "https://wordpress.stackexchange.com/users/74335",
"pm_score": 2,
"selected": false,
"text": "<p>There is a whole section on the WordPress Codex on this: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">Shortcode API</a></p>\n\n<pre><code>[foobar]\n\nfunction foobar_func( $atts ){\n return \"foo and bar\";\n}\nadd_shortcode( 'foobar', 'foobar_func' );\n</code></pre>\n\n<p>With attributes:</p>\n\n<p>[bartag foo=\"foo-value\"]</p>\n\n<pre><code>function bartag_func( $atts ) {\n $a = shortcode_atts( array(\n 'foo' => 'something',\n 'bar' => 'something else',\n ), $atts );\n\n return \"foo = {$a['foo']}\";\n}\nadd_shortcode( 'bartag', 'bartag_func' );\n</code></pre>\n"
},
{
"answer_id": 365313,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 2,
"selected": true,
"text": "<p>You'll probably need to modify this a bit to ensure things get placed where you want them but here's something I wrote that counts views on <code>posts</code> and displays the view counts for administrators:</p>\n\n<pre><code> //ADD TRACKER FUNCTION TO ALL SINGLE VIEWS\n function custom_hook_tracker( $post_id ) {\n if( !is_single() ) return;\n if( empty( $post_id ) ) {\n global $post;\n $post_id = $post->ID;\n }\n custom_track_post_views( $post_id );\n }\n add_action( 'wp_head', 'custom_hook_tracker' );\n\n //ADD VIEW TRACKER\n function custom_track_post_views( $postID ) {\n $count_key = 'custom_view_count';\n $count = get_post_meta( $postID, $count_key, true );\n if( $count=='' ) {\n $count = 0;\n delete_post_meta( $postID, $count_key );\n add_post_meta( $postID, $count_key, '0' );\n } else {\n $count++;\n update_post_meta( $postID, $count_key, $count );\n }\n //REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG\n if( is_single() && current_user_can( 'administrator' ) ) { //remove or adjust the '&& current_user_can( 'administrator' )' to modify who CAN see the counts\n //ALSO REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG\n echo '<div style=\"position:absolute;top:2.75rem;width:auto;display:block;float:left;background:#FFF;border-radius:4px;box-shadow:#333 1px 1px 4px;padding:0.25rem 0.5rem;margin-left:-5px;color:#777;\"><small>Views: '.$count.'</small></div>';\n }\n }\n //REMOVE PRE-FETCHING TO KEEP COUNTS ACCURATE\n remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);\n</code></pre>\n\n<p>Ok, I couldn't just leave it - here's the template tag:</p>\n\n<pre><code>function custom_view_counts() {\n $count_key = 'custom_view_count';\n $count = get_post_meta( $postID, $count_key, true );\n echo '<div class=\"view-tracker\"><small>Views: '.$count.'</small></div>';\n}\n</code></pre>\n\n<p>Then to display it drop this in your theme files exactly where you want it to appear:\n<code><?php custom_view_counts() ;?></code></p>\n\n<p>You'll need to write css that address/styles/targets the <code>.view-tracker</code> class/div.</p>\n\n<p>You can basically build your own plugin, or just drop all of the above into your functions.php.</p>\n"
},
{
"answer_id": 365367,
"author": "cssler",
"author_id": 187094,
"author_profile": "https://wordpress.stackexchange.com/users/187094",
"pm_score": 2,
"selected": false,
"text": "<p>Please check the official WordPress Shortcode API. You can create custom shortcodes easily without any Plugin.</p>\n\n<p><strong>Code Example:</strong></p>\n\n<pre><code>// HOW TO EMBED \n// Shortcode: [new_shortcode] \n\nfunction create_newshortcode_shortcode() {\n // Do whatever you want \n} \nadd_shortcode( 'new_shortcode', 'create_newshortcode_shortcode' );\n</code></pre>\n\n<p>Links you can help:</p>\n\n<p><a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a></p>\n\n<p><a href=\"https://app.wp-monkey.com/generators/shortcode-generator\" rel=\"nofollow noreferrer\">https://app.wp-monkey.com/generators/shortcode-generator</a></p>\n"
}
] | 2020/04/29 | [
"https://wordpress.stackexchange.com/questions/365394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187122/"
] | I have custom fields to display in a post. But all of the custom fields are displaying in a single continuous line, while i want them in separate lines. I am not a coder. I tried `<br>, <li>` but still no luck. I also searched in stack exchange and web for similar problem, but could not get answer. Please help.
Below is the Code i have in single.php after - `while ( have_posts() ) : the_post();
$key_name = get_post_custom_values ($key = 'country'); echo 'Country : ', $key_name[0];
$key_name = get_post_custom_values ($key = 'status'); echo 'Status : ', $key_name[0];`
The result in the post is as below:
Country : Saudi ArabiaStatus : Announced
I want it to appear it like the one below:
Country : Saudi Arabia
Status : Announced | You'll probably need to modify this a bit to ensure things get placed where you want them but here's something I wrote that counts views on `posts` and displays the view counts for administrators:
```
//ADD TRACKER FUNCTION TO ALL SINGLE VIEWS
function custom_hook_tracker( $post_id ) {
if( !is_single() ) return;
if( empty( $post_id ) ) {
global $post;
$post_id = $post->ID;
}
custom_track_post_views( $post_id );
}
add_action( 'wp_head', 'custom_hook_tracker' );
//ADD VIEW TRACKER
function custom_track_post_views( $postID ) {
$count_key = 'custom_view_count';
$count = get_post_meta( $postID, $count_key, true );
if( $count=='' ) {
$count = 0;
delete_post_meta( $postID, $count_key );
add_post_meta( $postID, $count_key, '0' );
} else {
$count++;
update_post_meta( $postID, $count_key, $count );
}
//REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG
if( is_single() && current_user_can( 'administrator' ) ) { //remove or adjust the '&& current_user_can( 'administrator' )' to modify who CAN see the counts
//ALSO REMOVE THIS LINE IF YOU USE THE TEMPLATE TAG
echo '<div style="position:absolute;top:2.75rem;width:auto;display:block;float:left;background:#FFF;border-radius:4px;box-shadow:#333 1px 1px 4px;padding:0.25rem 0.5rem;margin-left:-5px;color:#777;"><small>Views: '.$count.'</small></div>';
}
}
//REMOVE PRE-FETCHING TO KEEP COUNTS ACCURATE
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
```
Ok, I couldn't just leave it - here's the template tag:
```
function custom_view_counts() {
$count_key = 'custom_view_count';
$count = get_post_meta( $postID, $count_key, true );
echo '<div class="view-tracker"><small>Views: '.$count.'</small></div>';
}
```
Then to display it drop this in your theme files exactly where you want it to appear:
`<?php custom_view_counts() ;?>`
You'll need to write css that address/styles/targets the `.view-tracker` class/div.
You can basically build your own plugin, or just drop all of the above into your functions.php. |
365,476 | <p>I have a multi-site Wordpress setup. Each sub-site uses it's own child theme, but there is one stylesheet that has CSS rules that should be used on several of these sub-sites. I do not want to have multiple identical stylesheet files for each sub-site, because when I make changes to it, I would have to make these changes in every instance of the stylesheet, or have to copy-paste it to each sub-site.</p>
<p>How can I tell each sub-site to use just one instance of that stylesheet? Perhaps I can create a style.css file for every sub-site, and inside it, write some kind of redirect to the main style.css (one that actually contains the rules)?</p>
| [
{
"answer_id": 365477,
"author": "Bevan",
"author_id": 187183,
"author_profile": "https://wordpress.stackexchange.com/users/187183",
"pm_score": -1,
"selected": false,
"text": "<p>Use the wp_enqueue_style function, and put the path to the master CSS sheet in the source <code>src=\"full-path-goes-here\"</code>. See WP docs on function here: <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a></p>\n"
},
{
"answer_id": 365487,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": -1,
"selected": false,
"text": "<p>If you put the universal styles in the parent theme's stylesheet, those will be applied regardless of child theme. They just have to be more specific than the child themes' styles.</p>\n\n<p>You won't have multiple identical stylesheets; MultiSite stores all sites' themes in one central location, and typically with a parent-child theme setup you include both the parent CSS and the child CSS.</p>\n"
},
{
"answer_id": 393607,
"author": "omega33",
"author_id": 11064,
"author_profile": "https://wordpress.stackexchange.com/users/11064",
"pm_score": 0,
"selected": false,
"text": "<p>First off, you'll obviously need to be using the same parent theme for all sites. You then set up each sub-site with a child-theme for that parent theme.</p>\n<p>To use the same stylesheet on multiple sites, add the following code to the <code>functions.php</code> file of each sub-site:</p>\n<pre><code>function import_shared_style_sheet() {\n wp_enqueue_style( 'shared-style-sheet', content_url( '/themes/SOURCE-THEME/style.css') );\n\n}\nadd_action( 'wp_enqueue_scripts', 'import_shared_style_sheet' );\n</code></pre>\n<p><code>SOURCE-THEME</code> needs to be replaced with the folder name of the theme you are sharing the master <code>styles.css</code> file from.</p>\n<p>Keep in mind that the <code>styles.css</code> file of the child-theme of each sub-site will still load. So be sure to remove all css from below the theme data at the top of the file. For example, you should only have something like the following (it will differ, based on whatever child-theme you are using). In this example, the parent theme (for all the sites) is twentytwenty, so the shared <code>styles.css</code> file is in a twentytwenty child theme.</p>\n<pre><code>/*\nTheme Name: Sub-site Theme (child theme)\nTheme URI: \nTemplate: twentytwenty\nAuthor: \nDescription: Child theme of Twenty Twenty. Shares style.css of XXX child theme.\nVersion: 1.01\nUpdated: 2021-02-01 01:14:52\n*/\n</code></pre>\n<p>Note, that if you end up with some styles you need to apply only to a specific sub-site, you can still add those styles to the <code>styles.css</code> file of that sub-site's child-theme <code>styles.css</code> file.</p>\n"
}
] | 2020/04/30 | [
"https://wordpress.stackexchange.com/questions/365476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187182/"
] | I have a multi-site Wordpress setup. Each sub-site uses it's own child theme, but there is one stylesheet that has CSS rules that should be used on several of these sub-sites. I do not want to have multiple identical stylesheet files for each sub-site, because when I make changes to it, I would have to make these changes in every instance of the stylesheet, or have to copy-paste it to each sub-site.
How can I tell each sub-site to use just one instance of that stylesheet? Perhaps I can create a style.css file for every sub-site, and inside it, write some kind of redirect to the main style.css (one that actually contains the rules)? | First off, you'll obviously need to be using the same parent theme for all sites. You then set up each sub-site with a child-theme for that parent theme.
To use the same stylesheet on multiple sites, add the following code to the `functions.php` file of each sub-site:
```
function import_shared_style_sheet() {
wp_enqueue_style( 'shared-style-sheet', content_url( '/themes/SOURCE-THEME/style.css') );
}
add_action( 'wp_enqueue_scripts', 'import_shared_style_sheet' );
```
`SOURCE-THEME` needs to be replaced with the folder name of the theme you are sharing the master `styles.css` file from.
Keep in mind that the `styles.css` file of the child-theme of each sub-site will still load. So be sure to remove all css from below the theme data at the top of the file. For example, you should only have something like the following (it will differ, based on whatever child-theme you are using). In this example, the parent theme (for all the sites) is twentytwenty, so the shared `styles.css` file is in a twentytwenty child theme.
```
/*
Theme Name: Sub-site Theme (child theme)
Theme URI:
Template: twentytwenty
Author:
Description: Child theme of Twenty Twenty. Shares style.css of XXX child theme.
Version: 1.01
Updated: 2021-02-01 01:14:52
*/
```
Note, that if you end up with some styles you need to apply only to a specific sub-site, you can still add those styles to the `styles.css` file of that sub-site's child-theme `styles.css` file. |
365,530 | <p>I want to create the a link like <a href="https://mywordpresssite.com/mypage" rel="nofollow noreferrer">https://mywordpresssite.com/mypage</a>, that should call my function and execute the code. I am doing this for my backend script call that link and send some parameters to save data in database, I want to create that link by plugin only so it will use any of other wordpress websites</p>
<p>I tried this by searching-</p>
<pre><code>add_action( 'wp_loaded', function() {
if ( $_SERVER[REQUEST_URI] == '/mypage' ) {
data_collection();
}
});
function data_collection(){
//my coding stuff
}
</code></pre>
<p>But this showing me error and not worked as expected.</p>
| [
{
"answer_id": 365497,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The reason you are advised to put a custom post type in a plugin rather than your theme is that in this way the user can keep the cpt even if he decides to switch to another theme. In five years or so, design trends may change significantly and you don't want to be stuck with a theme, just because it also holds your custom post definition.</p>\n\n<p>Now, if you look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">hook order</a>, you see that mu-plugins are loaded before everything else. This means that the main function of the plugin is registered by the time you initialize your theme at the <code>after_setup_theme</code> hook. At that point you can use <a href=\"https://www.php.net/manual/en/function.function-exists.php\" rel=\"nofollow noreferrer\"><code>function_exists</code></a> to check if the plugin has been loaded. If not your can notify the user or do something more drastic, like stop loading the theme.</p>\n\n<p>By the way, it is not necessary to make your plugin a must use. The <code>plugins_loaded</code> hook is also executed before <code>after_setup_theme</code>, so any plugin function is known to WP before you start initializing the theme.</p>\n\n<p>Also, it is possible to make the dependency a two way affair. If your plugin initializes (as it should do) at the <code>init</code> hook, the theme has been loaded by that time, so you can check for the existence of the theme's main function and issue a warning to the user that he is not using the theme that is optimal for this custom post type.</p>\n"
},
{
"answer_id": 365500,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Don't</strong></p>\n\n<p>Just register your post types in a normal plugin in the plugin folder. You don't need an <code>mu-plugin</code> to use CPT's.</p>\n"
}
] | 2020/05/01 | [
"https://wordpress.stackexchange.com/questions/365530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174404/"
] | I want to create the a link like <https://mywordpresssite.com/mypage>, that should call my function and execute the code. I am doing this for my backend script call that link and send some parameters to save data in database, I want to create that link by plugin only so it will use any of other wordpress websites
I tried this by searching-
```
add_action( 'wp_loaded', function() {
if ( $_SERVER[REQUEST_URI] == '/mypage' ) {
data_collection();
}
});
function data_collection(){
//my coding stuff
}
```
But this showing me error and not worked as expected. | The reason you are advised to put a custom post type in a plugin rather than your theme is that in this way the user can keep the cpt even if he decides to switch to another theme. In five years or so, design trends may change significantly and you don't want to be stuck with a theme, just because it also holds your custom post definition.
Now, if you look at the [hook order](https://codex.wordpress.org/Plugin_API/Action_Reference), you see that mu-plugins are loaded before everything else. This means that the main function of the plugin is registered by the time you initialize your theme at the `after_setup_theme` hook. At that point you can use [`function_exists`](https://www.php.net/manual/en/function.function-exists.php) to check if the plugin has been loaded. If not your can notify the user or do something more drastic, like stop loading the theme.
By the way, it is not necessary to make your plugin a must use. The `plugins_loaded` hook is also executed before `after_setup_theme`, so any plugin function is known to WP before you start initializing the theme.
Also, it is possible to make the dependency a two way affair. If your plugin initializes (as it should do) at the `init` hook, the theme has been loaded by that time, so you can check for the existence of the theme's main function and issue a warning to the user that he is not using the theme that is optimal for this custom post type. |
365,547 | <p>I'm looking for a way to pass post meta data to each of the blocks in the editor for the purpose of styling the content. My actual use case is hard to explain briefly, but for the sake of example, pretend it's the ability to display the post either in dark or light mode depending on a post meta value that the user sets.</p>
<p>The most obvious way to do this, for me, would be to add a class to the <code><div class="block-editor"></code> element like <code><div class="block-editor dark-editor-mode"></code>. But I don't see an obvious way to do that. Everything I find via search is about modifying the individual blocks, but I want to modify the editor. Is there a hook for this? Either in JS or PHP?</p>
| [
{
"answer_id": 365588,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Your proposed solution is not possible.</strong> There is no hook or filter that would allow you to apply a CSS class to the block list or the styles wrapper div, and no means to insert one.</p>\n\n<p><em>This appears to be intentional</em>, and also runs contrary to how things would work going forward, or how blocks in general work ( how would this work inside if the post meta was present in a reusable block post, or a site footer rather than a page/post? ).</p>\n\n<p>Your next step if you absolutely must take this route, is to open a feature request in the github issues for the gutenberg repo, or write a pull request.</p>\n\n<p>You can very easily just wait until the editor is initialised and grab the post meta from the data store, but there's no way to set a HTML class to apply the styling at an editor level.</p>\n\n<p>Alternatives include:</p>\n\n<ul>\n<li>Using your own custom blocks, and checking the post meta via the data store for each block</li>\n<li>Using a containing block with child blocks, where the child blocks are then styled according to the settings of the parent block ( this also allows the post meta to be eliminated entirely, and futureproofs the functionality for full site editing and reusable blocks )</li>\n<li>Using block styles ( perhaps bulk setting of block styles is an equivalent to what you want to achieve? )</li>\n</ul>\n"
},
{
"answer_id": 365919,
"author": "Josiah Sprague",
"author_id": 21290,
"author_profile": "https://wordpress.stackexchange.com/users/21290",
"pm_score": 1,
"selected": true,
"text": "<p>I was able to solve this problem by using the <code>admin_body_class</code> filter to add a class name to the <code><body></code> element of the admin page, and writing selectors for that class in my stylesheet.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'admin_body_class', 'add_status_classes' );\n</code></pre>\n\n<pre class=\"lang-php prettyprint-override\"><code>function add_status_classes( $classes ) {\n $post_meta = get_post_meta( get_the_ID() );\n $is_darkmode = $post_meta['_is_post_dark_mode'];\n if ( $is_darkmode ) {\n $classes = $classes . ' dark-editor-mode';\n }\n return $classes;\n}\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* Normal Styles */\np:after {\n content: \"Walking on sunshine!\";\n}\n/* Styles when custom post meta option is true */\n.dark-editor-mode p {\n content: \"It sure is dark in here!\";\n}\n\n</code></pre>\n\n<p>Again, the dark mode is just a simple example, since my real use case is too complex to explain here, but the concept is the same.</p>\n\n<p>Unfortunately, the drawback of this solution is that the editor has to be refreshed after the user changes the post meta setting, since the class isn't tied to a JavaScript store. If anyone knows how to hook into a data store that controls a classname on a parent element to the editor panel in Gutenberg, please add to my answer.</p>\n"
}
] | 2020/05/01 | [
"https://wordpress.stackexchange.com/questions/365547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21290/"
] | I'm looking for a way to pass post meta data to each of the blocks in the editor for the purpose of styling the content. My actual use case is hard to explain briefly, but for the sake of example, pretend it's the ability to display the post either in dark or light mode depending on a post meta value that the user sets.
The most obvious way to do this, for me, would be to add a class to the `<div class="block-editor">` element like `<div class="block-editor dark-editor-mode">`. But I don't see an obvious way to do that. Everything I find via search is about modifying the individual blocks, but I want to modify the editor. Is there a hook for this? Either in JS or PHP? | I was able to solve this problem by using the `admin_body_class` filter to add a class name to the `<body>` element of the admin page, and writing selectors for that class in my stylesheet.
```php
add_filter( 'admin_body_class', 'add_status_classes' );
```
```php
function add_status_classes( $classes ) {
$post_meta = get_post_meta( get_the_ID() );
$is_darkmode = $post_meta['_is_post_dark_mode'];
if ( $is_darkmode ) {
$classes = $classes . ' dark-editor-mode';
}
return $classes;
}
```
```css
/* Normal Styles */
p:after {
content: "Walking on sunshine!";
}
/* Styles when custom post meta option is true */
.dark-editor-mode p {
content: "It sure is dark in here!";
}
```
Again, the dark mode is just a simple example, since my real use case is too complex to explain here, but the concept is the same.
Unfortunately, the drawback of this solution is that the editor has to be refreshed after the user changes the post meta setting, since the class isn't tied to a JavaScript store. If anyone knows how to hook into a data store that controls a classname on a parent element to the editor panel in Gutenberg, please add to my answer. |
365,557 | <p>I'm looking for a way to remove the eye icon that shows visibility on login screen (wp-admin and wp-login) and reset password screen (/wp-login.php?action=rp).</p>
<p>As you can see on the screenshot below :</p>
<p>Login Page :</p>
<p><a href="https://i.stack.imgur.com/NRANB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NRANB.png" alt="enter image description here"></a></p>
<p>Reset password Page :</p>
<p><a href="https://i.stack.imgur.com/4TAZ2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4TAZ2.png" alt="enter image description here"></a></p>
<p>Update : I need to remove this button not only the visibility :</p>
<p><a href="https://i.stack.imgur.com/wExO4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wExO4.png" alt="enter image description here"></a></p>
<p>Thanks in advance for your reply.</p>
<p>regards. </p>
| [
{
"answer_id": 365566,
"author": "dyg",
"author_id": 150607,
"author_profile": "https://wordpress.stackexchange.com/users/150607",
"pm_score": 1,
"selected": false,
"text": "<p>This is one way</p>\n\n<pre><code>add_action('login_head', 'my_remove_eye');\n\nfunction my_remove_eye() {\n echo \n '<style>\n span.dashicons-visibility:before {\n content: \"\";\n }\n </style>';\n}\n</code></pre>\n"
},
{
"answer_id": 380729,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the same mechanism to enqueue some JavaScript that will actually remove the button:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_wp_hide_pw_button() {\n?><script>\nif ((document.addEventListener != null) && (document.querySelector != null)) {\n document.addEventListener( 'DOMContentLoaded', function() {\n var b = document.querySelector('button.wp-hide-pw');\n if (b != null) b.remove();\n });\n}\n</script>\n<?php\n}\nadd_action('login_footer', 'remove_wp_hide_pw_button');\n</code></pre>\n<p>However the button will appear briefly then disappear, so you probably do need CSS to hide it the button or icon too.</p>\n"
}
] | 2020/05/01 | [
"https://wordpress.stackexchange.com/questions/365557",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] | I'm looking for a way to remove the eye icon that shows visibility on login screen (wp-admin and wp-login) and reset password screen (/wp-login.php?action=rp).
As you can see on the screenshot below :
Login Page :
[](https://i.stack.imgur.com/NRANB.png)
Reset password Page :
[](https://i.stack.imgur.com/4TAZ2.png)
Update : I need to remove this button not only the visibility :
[](https://i.stack.imgur.com/wExO4.png)
Thanks in advance for your reply.
regards. | This is one way
```
add_action('login_head', 'my_remove_eye');
function my_remove_eye() {
echo
'<style>
span.dashicons-visibility:before {
content: "";
}
</style>';
}
``` |
365,594 | <p>I am new with wordpress en I try to build a website for soccer teams. this is what I like to have:</p>
<p>team name (Arsenal) 1 role: player1 can see the following pages (Test1 - Test2 - team1 score)</p>
<p>Team name (Chelsea) 2 role: player2 can see the following pages (test1 - test2 - team2 score)</p>
<p>Role palyer1 should not be able to see the page team2 score, and role player2 should also not able
to see the page team1 score.</p>
<p>Structure of my website:</p>
<p>Team Valencia
- role player / coach</p>
<p>Team Barcelona
role player / coach</p>
<p>Can somebody tell me how to manage this thank you.</p>
| [
{
"answer_id": 365566,
"author": "dyg",
"author_id": 150607,
"author_profile": "https://wordpress.stackexchange.com/users/150607",
"pm_score": 1,
"selected": false,
"text": "<p>This is one way</p>\n\n<pre><code>add_action('login_head', 'my_remove_eye');\n\nfunction my_remove_eye() {\n echo \n '<style>\n span.dashicons-visibility:before {\n content: \"\";\n }\n </style>';\n}\n</code></pre>\n"
},
{
"answer_id": 380729,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the same mechanism to enqueue some JavaScript that will actually remove the button:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_wp_hide_pw_button() {\n?><script>\nif ((document.addEventListener != null) && (document.querySelector != null)) {\n document.addEventListener( 'DOMContentLoaded', function() {\n var b = document.querySelector('button.wp-hide-pw');\n if (b != null) b.remove();\n });\n}\n</script>\n<?php\n}\nadd_action('login_footer', 'remove_wp_hide_pw_button');\n</code></pre>\n<p>However the button will appear briefly then disappear, so you probably do need CSS to hide it the button or icon too.</p>\n"
}
] | 2020/05/01 | [
"https://wordpress.stackexchange.com/questions/365594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187277/"
] | I am new with wordpress en I try to build a website for soccer teams. this is what I like to have:
team name (Arsenal) 1 role: player1 can see the following pages (Test1 - Test2 - team1 score)
Team name (Chelsea) 2 role: player2 can see the following pages (test1 - test2 - team2 score)
Role palyer1 should not be able to see the page team2 score, and role player2 should also not able
to see the page team1 score.
Structure of my website:
Team Valencia
- role player / coach
Team Barcelona
role player / coach
Can somebody tell me how to manage this thank you. | This is one way
```
add_action('login_head', 'my_remove_eye');
function my_remove_eye() {
echo
'<style>
span.dashicons-visibility:before {
content: "";
}
</style>';
}
``` |
365,619 | <p>Can someone assist with a function code that displays children on a parent page. </p>
<p>I have breadcrumbs for when standing on child page going back to parent but,</p>
<p>I need standing on parent page to display all children in UL/li list below the page title</p>
| [
{
"answer_id": 365566,
"author": "dyg",
"author_id": 150607,
"author_profile": "https://wordpress.stackexchange.com/users/150607",
"pm_score": 1,
"selected": false,
"text": "<p>This is one way</p>\n\n<pre><code>add_action('login_head', 'my_remove_eye');\n\nfunction my_remove_eye() {\n echo \n '<style>\n span.dashicons-visibility:before {\n content: \"\";\n }\n </style>';\n}\n</code></pre>\n"
},
{
"answer_id": 380729,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the same mechanism to enqueue some JavaScript that will actually remove the button:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_wp_hide_pw_button() {\n?><script>\nif ((document.addEventListener != null) && (document.querySelector != null)) {\n document.addEventListener( 'DOMContentLoaded', function() {\n var b = document.querySelector('button.wp-hide-pw');\n if (b != null) b.remove();\n });\n}\n</script>\n<?php\n}\nadd_action('login_footer', 'remove_wp_hide_pw_button');\n</code></pre>\n<p>However the button will appear briefly then disappear, so you probably do need CSS to hide it the button or icon too.</p>\n"
}
] | 2020/05/01 | [
"https://wordpress.stackexchange.com/questions/365619",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186632/"
] | Can someone assist with a function code that displays children on a parent page.
I have breadcrumbs for when standing on child page going back to parent but,
I need standing on parent page to display all children in UL/li list below the page title | This is one way
```
add_action('login_head', 'my_remove_eye');
function my_remove_eye() {
echo
'<style>
span.dashicons-visibility:before {
content: "";
}
</style>';
}
``` |
365,632 | <p>I need help in getting this to work, i want to pass the site url in a jquery window.location.replace("URL")
And i want it to work like this window.location.replace("site_url/contact-us")
My whole concept is to redirect to www.mysite.com/contact-us but am getting www.mysite.com/login/contact-us</p>
<p>Here is my full code</p>
<pre><code>// PHP
// Add the javascript file only if user is logged in and page id login
if ( is_user_logged_in() && is_page( 'login' ) ) {
wp_enqueue_script( 'java_reload', get_stylesheet_directory_uri() . '/java-reload.js', array('jquery'), '201951218', true );
}
//JAVASCRIPT
jQuery(document).ready(function($){
window.location.replace("/contact-us");
});
</code></pre>
| [
{
"answer_id": 365566,
"author": "dyg",
"author_id": 150607,
"author_profile": "https://wordpress.stackexchange.com/users/150607",
"pm_score": 1,
"selected": false,
"text": "<p>This is one way</p>\n\n<pre><code>add_action('login_head', 'my_remove_eye');\n\nfunction my_remove_eye() {\n echo \n '<style>\n span.dashicons-visibility:before {\n content: \"\";\n }\n </style>';\n}\n</code></pre>\n"
},
{
"answer_id": 380729,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the same mechanism to enqueue some JavaScript that will actually remove the button:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_wp_hide_pw_button() {\n?><script>\nif ((document.addEventListener != null) && (document.querySelector != null)) {\n document.addEventListener( 'DOMContentLoaded', function() {\n var b = document.querySelector('button.wp-hide-pw');\n if (b != null) b.remove();\n });\n}\n</script>\n<?php\n}\nadd_action('login_footer', 'remove_wp_hide_pw_button');\n</code></pre>\n<p>However the button will appear briefly then disappear, so you probably do need CSS to hide it the button or icon too.</p>\n"
}
] | 2020/05/02 | [
"https://wordpress.stackexchange.com/questions/365632",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152456/"
] | I need help in getting this to work, i want to pass the site url in a jquery window.location.replace("URL")
And i want it to work like this window.location.replace("site\_url/contact-us")
My whole concept is to redirect to www.mysite.com/contact-us but am getting www.mysite.com/login/contact-us
Here is my full code
```
// PHP
// Add the javascript file only if user is logged in and page id login
if ( is_user_logged_in() && is_page( 'login' ) ) {
wp_enqueue_script( 'java_reload', get_stylesheet_directory_uri() . '/java-reload.js', array('jquery'), '201951218', true );
}
//JAVASCRIPT
jQuery(document).ready(function($){
window.location.replace("/contact-us");
});
``` | This is one way
```
add_action('login_head', 'my_remove_eye');
function my_remove_eye() {
echo
'<style>
span.dashicons-visibility:before {
content: "";
}
</style>';
}
``` |
365,647 | <p>WooCommerce has a built in <code>product_tag</code> url filter as such:</p>
<pre><code>https://my-url.com/my-page/?product_tag=my-slug
</code></pre>
<p>Bringing back all the <code>product_tag</code>s with the given slug in the url.</p>
<p>I am trying to do something relatively simple, retrieve the name of the <code>product_tag</code> and put it in a text heading block so the visitor knows what it is filtering.</p>
<p>The only thing I was able to figure out is in my woocommerce template page <code>woocommerce-page.php</code> is latching onto the global variable <code>$wp_query</code></p>
<p>And then putting the product tags slug in a variable.</p>
<pre><code>$producttag = $wp_query->query['product_tag'];
</code></pre>
<p>Questions:</p>
<p>Is this an appropriate way to retrieve the product tag slug?
How do I convert the product slug into its actual Name?</p>
<p>Or is there a way to bypass the slug altogether and just get the product tags name?
The only way I found how to get these variables was by looking at <code>$wp_query</code>, and that only returns the slug.</p>
| [
{
"answer_id": 365650,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if I'm understanding you correctly, but why don't you just use $_GET['product_tag'] at the moment where you want to retrieve it? </p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>If the product posts exist in the basic wp_{custom}_posts database or similar, this solution of a basic WP post query method may be more convenient to you:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'product_post_type',\n 'name' => 'your_post_slug',\n);\n\n$arr_posts = new WP_Query($args);\n\nif ($arr_posts->have_posts()) {\n while ($arr_posts->have_posts()) {\n echo $arr_posts->the_post();\n the_title();\n }\n } else {\n echo \"<p class='error'>No posts with this slug found!<p>\";\n }\n</code></pre>\n\n<p>This example queries in the database mentioned above for posts of the specified type and slug name and echoes out their title. You can also further specify query paramaters, as post tag names, category names, and so on, in the $args array. Also, the post type is not a must, just thought it's probably also unique to product posts if they're stored in the same database.</p>\n\n<p>Just found this <a href=\"https://wp-staging.com/in-which-database-table-is-woocommerce-storing-products/\" rel=\"nofollow noreferrer\">https://wp-staging.com/in-which-database-table-is-woocommerce-storing-products/</a>, so the code above should definitely work.</p>\n"
},
{
"answer_id": 365663,
"author": "bbruman",
"author_id": 102212,
"author_profile": "https://wordpress.stackexchange.com/users/102212",
"pm_score": 1,
"selected": true,
"text": "<p>I suppose this works.\nStill not sure if it is the best method. If someone knows of a better way to do this please chime in, I'll gladly adjust the answer.</p>\n\n<pre><code>function slugToName($slug) {\n global $wpdb;\n $query = 'SELECT name FROM `wp_terms` WHERE slug = \"' . $slug . '\"';\n $getname = $wpdb->get_results($query);\n $name = $getname[0]->name;\n return $name;\n}\n</code></pre>\n"
}
] | 2020/05/02 | [
"https://wordpress.stackexchange.com/questions/365647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102212/"
] | WooCommerce has a built in `product_tag` url filter as such:
```
https://my-url.com/my-page/?product_tag=my-slug
```
Bringing back all the `product_tag`s with the given slug in the url.
I am trying to do something relatively simple, retrieve the name of the `product_tag` and put it in a text heading block so the visitor knows what it is filtering.
The only thing I was able to figure out is in my woocommerce template page `woocommerce-page.php` is latching onto the global variable `$wp_query`
And then putting the product tags slug in a variable.
```
$producttag = $wp_query->query['product_tag'];
```
Questions:
Is this an appropriate way to retrieve the product tag slug?
How do I convert the product slug into its actual Name?
Or is there a way to bypass the slug altogether and just get the product tags name?
The only way I found how to get these variables was by looking at `$wp_query`, and that only returns the slug. | I suppose this works.
Still not sure if it is the best method. If someone knows of a better way to do this please chime in, I'll gladly adjust the answer.
```
function slugToName($slug) {
global $wpdb;
$query = 'SELECT name FROM `wp_terms` WHERE slug = "' . $slug . '"';
$getname = $wpdb->get_results($query);
$name = $getname[0]->name;
return $name;
}
``` |
365,712 | <p>I have php.ini files in the following directories of my WordPress installation:</p>
<ul>
<li>/wp-admin</li>
<li>/wp-content</li>
<li>/ (where there wp-config.php lies)</li>
</ul>
<p>In all of them I set <code>upload_max_filesize = 640M;</code> - <strong>640MB</strong> is the maximum value that is allowed by my provider in my package (I called).</p>
<pre><code>memory_limit = 268435456;
post_max_size = 67108864;
upload_max_filesize = 640M;
</code></pre>
<p>I did NOT configure an upload_max_filesize in wp-config.php or in .htaccess. I confirmed this value with <code>phpinfo()</code> and with <code>ini_get('upload_max_filesize')</code>. </p>
<p>Nonetheless, WordPress displayes <strong>64 MB</strong> as maximum on the media upload page and on the WooCommerce status page.</p>
<p>I am utterly puzzled. I checked every post on stack but I couldn't find an answer to that dissonance. Help would be much appreciated.</p>
<p><a href="https://i.stack.imgur.com/X632M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X632M.png" alt="upload page"></a>
<a href="https://i.stack.imgur.com/zUovw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zUovw.png" alt="WC status"></a></p>
| [
{
"answer_id": 365713,
"author": "jasie",
"author_id": 124308,
"author_profile": "https://wordpress.stackexchange.com/users/124308",
"pm_score": 1,
"selected": true,
"text": "<p>UPDATED:</p>\n\n<p>I figured out the following by playing with the numbers in the php.ini in /wp-admin:</p>\n\n<p>The add upload page in the admin area seems to always <strong>display the lower value</strong> of either <code>post_max_size</code> and <code>upload_max_filesize</code>.</p>\n\n<p>In my case, <code>post_max_size</code> was lower than <code>upload_max_filesize</code> which is the reason for \"Maximum size of files for uploads\" not displaying the 640MB but 64MB.</p>\n\n<p>I suppose this has to do with this: see <a href=\"http://docs.php.net/manual/en/ini.core.php#ini.post-max-size\" rel=\"nofollow noreferrer\">php.net docs</a> as:</p>\n\n<blockquote>\n <p>post_max_size integer<br>\n Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size.</p>\n</blockquote>\n"
},
{
"answer_id": 365717,
"author": "Omer YILMAZ",
"author_id": 187357,
"author_profile": "https://wordpress.stackexchange.com/users/187357",
"pm_score": -1,
"selected": false,
"text": "<p><code>upload_max_filesize</code> for uploading file from multipart-form. Other hand <code>post_max_size</code> is posted size from form. (input textarea etc). So i prefer, create php file in root directory such as php.php and write phpinfo for real compare.</p>\n\n<pre><code><?php\nphpinfo();\n</code></pre>\n"
}
] | 2020/05/03 | [
"https://wordpress.stackexchange.com/questions/365712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124308/"
] | I have php.ini files in the following directories of my WordPress installation:
* /wp-admin
* /wp-content
* / (where there wp-config.php lies)
In all of them I set `upload_max_filesize = 640M;` - **640MB** is the maximum value that is allowed by my provider in my package (I called).
```
memory_limit = 268435456;
post_max_size = 67108864;
upload_max_filesize = 640M;
```
I did NOT configure an upload\_max\_filesize in wp-config.php or in .htaccess. I confirmed this value with `phpinfo()` and with `ini_get('upload_max_filesize')`.
Nonetheless, WordPress displayes **64 MB** as maximum on the media upload page and on the WooCommerce status page.
I am utterly puzzled. I checked every post on stack but I couldn't find an answer to that dissonance. Help would be much appreciated.
[](https://i.stack.imgur.com/X632M.png)
[](https://i.stack.imgur.com/zUovw.png) | UPDATED:
I figured out the following by playing with the numbers in the php.ini in /wp-admin:
The add upload page in the admin area seems to always **display the lower value** of either `post_max_size` and `upload_max_filesize`.
In my case, `post_max_size` was lower than `upload_max_filesize` which is the reason for "Maximum size of files for uploads" not displaying the 640MB but 64MB.
I suppose this has to do with this: see [php.net docs](http://docs.php.net/manual/en/ini.core.php#ini.post-max-size) as:
>
> post\_max\_size integer
>
> Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload\_max\_filesize. Generally speaking, memory\_limit should be larger than post\_max\_size.
>
>
> |
365,743 | <p>I will really appreciate your help to create a function that will check by a given <code>$my_custom_post_type_name</code> and <code>$post_name</code> and return <code>true</code> if the current page / post is a <code>$post_name</code> or <code>$post_name_child</code> or <code>$post_name_grandchild</code> and so on based on the provided parent slug and custom post type.</p>
<p>Let's say this is the structure:</p>
<pre><code>my_custom_post_type_name
-first_page (example.com/my_custom_post_type_name/first_page)
--first_page_child
---first_page_grandchild
--first_page_child_2
-second_page
--second_page_child
---second_page_grandchild
</code></pre>
<p>I want to be able to target all pages that are <code>first_page</code> or its children / grandchildren and so on.</p>
<p>Something like:</p>
<pre><code>if( my_custom_function('my_custom_post_type_name', 'first_page') ){
//do stuff if the current page is 'first_page' OR 'first_page_child' OR 'first_page_grandchild' OR 'first_page_child_2'
}
</code></pre>
<p>After some research I was able to come up with the following (still need to change <code>first_page ID</code> to be a slug, and to get rid of <code>in_array()</code> check so the custom function will do it all at once):</p>
<pre><code>function get_posts_children($CPT, $parent_id){
$children = array();
$children[] = $parent_id;
// grab the posts children
$posts = get_posts(
array(
'numberposts' => -1,
'post_status' => 'publish',
'post_type' => $CPT,
'post_parent' => $parent_id
)
);
// now grab the grand children
foreach( $posts as $child ){
// call the same function again for grandchildren
$gchildren = get_posts_children($CPT, $child->ID);
// merge the grand children into the children array
if( ! empty($gchildren) ) {
$children = array_merge($children, $gchildren);
}
}
// merge in the direct descendants we found earlier
$children = array_merge($children, $posts);
return $children;
}
//and then (where 3060 is the first_page ID):
global $post;
if( in_array( $post->ID, get_posts_children( 'my_custom_post_type_name', 3060 ) ) ) {
//do stuff. As it is now, it is working fine. But would really like to simplify it and to change the first_page ID to be a slug for obvious reasons.
}
</code></pre>
| [
{
"answer_id": 365713,
"author": "jasie",
"author_id": 124308,
"author_profile": "https://wordpress.stackexchange.com/users/124308",
"pm_score": 1,
"selected": true,
"text": "<p>UPDATED:</p>\n\n<p>I figured out the following by playing with the numbers in the php.ini in /wp-admin:</p>\n\n<p>The add upload page in the admin area seems to always <strong>display the lower value</strong> of either <code>post_max_size</code> and <code>upload_max_filesize</code>.</p>\n\n<p>In my case, <code>post_max_size</code> was lower than <code>upload_max_filesize</code> which is the reason for \"Maximum size of files for uploads\" not displaying the 640MB but 64MB.</p>\n\n<p>I suppose this has to do with this: see <a href=\"http://docs.php.net/manual/en/ini.core.php#ini.post-max-size\" rel=\"nofollow noreferrer\">php.net docs</a> as:</p>\n\n<blockquote>\n <p>post_max_size integer<br>\n Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size.</p>\n</blockquote>\n"
},
{
"answer_id": 365717,
"author": "Omer YILMAZ",
"author_id": 187357,
"author_profile": "https://wordpress.stackexchange.com/users/187357",
"pm_score": -1,
"selected": false,
"text": "<p><code>upload_max_filesize</code> for uploading file from multipart-form. Other hand <code>post_max_size</code> is posted size from form. (input textarea etc). So i prefer, create php file in root directory such as php.php and write phpinfo for real compare.</p>\n\n<pre><code><?php\nphpinfo();\n</code></pre>\n"
}
] | 2020/05/03 | [
"https://wordpress.stackexchange.com/questions/365743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180722/"
] | I will really appreciate your help to create a function that will check by a given `$my_custom_post_type_name` and `$post_name` and return `true` if the current page / post is a `$post_name` or `$post_name_child` or `$post_name_grandchild` and so on based on the provided parent slug and custom post type.
Let's say this is the structure:
```
my_custom_post_type_name
-first_page (example.com/my_custom_post_type_name/first_page)
--first_page_child
---first_page_grandchild
--first_page_child_2
-second_page
--second_page_child
---second_page_grandchild
```
I want to be able to target all pages that are `first_page` or its children / grandchildren and so on.
Something like:
```
if( my_custom_function('my_custom_post_type_name', 'first_page') ){
//do stuff if the current page is 'first_page' OR 'first_page_child' OR 'first_page_grandchild' OR 'first_page_child_2'
}
```
After some research I was able to come up with the following (still need to change `first_page ID` to be a slug, and to get rid of `in_array()` check so the custom function will do it all at once):
```
function get_posts_children($CPT, $parent_id){
$children = array();
$children[] = $parent_id;
// grab the posts children
$posts = get_posts(
array(
'numberposts' => -1,
'post_status' => 'publish',
'post_type' => $CPT,
'post_parent' => $parent_id
)
);
// now grab the grand children
foreach( $posts as $child ){
// call the same function again for grandchildren
$gchildren = get_posts_children($CPT, $child->ID);
// merge the grand children into the children array
if( ! empty($gchildren) ) {
$children = array_merge($children, $gchildren);
}
}
// merge in the direct descendants we found earlier
$children = array_merge($children, $posts);
return $children;
}
//and then (where 3060 is the first_page ID):
global $post;
if( in_array( $post->ID, get_posts_children( 'my_custom_post_type_name', 3060 ) ) ) {
//do stuff. As it is now, it is working fine. But would really like to simplify it and to change the first_page ID to be a slug for obvious reasons.
}
``` | UPDATED:
I figured out the following by playing with the numbers in the php.ini in /wp-admin:
The add upload page in the admin area seems to always **display the lower value** of either `post_max_size` and `upload_max_filesize`.
In my case, `post_max_size` was lower than `upload_max_filesize` which is the reason for "Maximum size of files for uploads" not displaying the 640MB but 64MB.
I suppose this has to do with this: see [php.net docs](http://docs.php.net/manual/en/ini.core.php#ini.post-max-size) as:
>
> post\_max\_size integer
>
> Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload\_max\_filesize. Generally speaking, memory\_limit should be larger than post\_max\_size.
>
>
> |
365,766 | <p>I am trying to make a custom loop that will display the latest 5 posts from select categories, all using a single query. I want the loop to display the category name followed by the 5 posts, and then the next category, etc.</p>
<p>I followed <a href="https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories/#answer-145960">this answer</a> and it seems to do what I want, except it doesn't output the categories properly.</p>
<p>For example, let's say I want to display categories 100,101,102 and 103, it should display like this:</p>
<p><code>100
Post 1
Post 2
Post 3
Post 4
Post 5</code></p>
<p><code>101
Post 1
Post 2
Post 3
Post 4
Post 5</code></p>
<p>etc.</p>
<hr>
<h1>The Problem</h1>
<p><strong>However</strong>, currently, if there is a post in category 100, and also in category 250, it will also display the title of category 250 too, like so</p>
<p><code>250
Post 1</code></p>
<p>How do I get it that it ONLY displays the categories specified?
<hr>
Here's the code I have so far, based on <a href="https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories/#answer-145960">this</a>.</p>
<pre><code><?php
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
// arguments for your query
'taxonomy' => 'category',
'field' => 'id',
'terms' => $selected_categories, // $selected_categories contains an array of post IDs.
)
)
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<ul>';
foreach ($values as $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
?>
</code></pre>
<p>Thanks for any help!</p>
| [
{
"answer_id": 365852,
"author": "Karthick",
"author_id": 186872,
"author_profile": "https://wordpress.stackexchange.com/users/186872",
"pm_score": 2,
"selected": true,
"text": "<p>I have used <a href=\"https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query\" rel=\"nofollow noreferrer\">Custom Select Query</a> to gather all information in a single call and hope it may work out.</p>\n\n<pre><code>global $wpdb;\n$selected_cat_id = '6,7,8,9';\n$post_count = 5;\n\n$custom_query = \"SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->terms.name FROM $wpdb->posts \nLEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) \nLEFT JOIN $wpdb->terms ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id) \nWHERE 1=1 AND ($wpdb->term_relationships.term_taxonomy_id IN ($selected_cat_id))\nAND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') ORDER BY $wpdb->posts.post_date ASC\";\n$pageposts = $wpdb->get_results($custom_query, OBJECT);\n\n$cat_posts = array();\nforeach($pageposts as $post){\n $cat_posts[$post->name][$post->ID] = $post->post_title;\n}\n\nforeach($cat_posts as $key => $values) {\n $category_id = get_cat_ID( $key );\n echo '<a href=\"'.get_category_link($category_id).'\">'.$key.'</a>';\n $values = array_slice($values,0,$post_count,true);\n echo '<ul>';\n foreach ($values as $post_id => $value){\n echo '<li><a href=\"'.get_permalink($post_id).'\">' . $value . '</a></li>';\n }\n echo '</ul>';\n}\n</code></pre>\n"
},
{
"answer_id": 365882,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": 0,
"selected": false,
"text": "<p>Use 'category_name' as direct argument in your $args array, not inside your tax_query array. I always displayed posts of a category on my pages in that way. </p>\n"
}
] | 2020/05/04 | [
"https://wordpress.stackexchange.com/questions/365766",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151735/"
] | I am trying to make a custom loop that will display the latest 5 posts from select categories, all using a single query. I want the loop to display the category name followed by the 5 posts, and then the next category, etc.
I followed [this answer](https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories/#answer-145960) and it seems to do what I want, except it doesn't output the categories properly.
For example, let's say I want to display categories 100,101,102 and 103, it should display like this:
`100
Post 1
Post 2
Post 3
Post 4
Post 5`
`101
Post 1
Post 2
Post 3
Post 4
Post 5`
etc.
---
The Problem
===========
**However**, currently, if there is a post in category 100, and also in category 250, it will also display the title of category 250 too, like so
`250
Post 1`
How do I get it that it ONLY displays the categories specified?
---
Here's the code I have so far, based on [this](https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories/#answer-145960).
```
<?php
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
// arguments for your query
'taxonomy' => 'category',
'field' => 'id',
'terms' => $selected_categories, // $selected_categories contains an array of post IDs.
)
)
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<ul>';
foreach ($values as $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
?>
```
Thanks for any help! | I have used [Custom Select Query](https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query) to gather all information in a single call and hope it may work out.
```
global $wpdb;
$selected_cat_id = '6,7,8,9';
$post_count = 5;
$custom_query = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->terms.name FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->terms ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id)
WHERE 1=1 AND ($wpdb->term_relationships.term_taxonomy_id IN ($selected_cat_id))
AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') ORDER BY $wpdb->posts.post_date ASC";
$pageposts = $wpdb->get_results($custom_query, OBJECT);
$cat_posts = array();
foreach($pageposts as $post){
$cat_posts[$post->name][$post->ID] = $post->post_title;
}
foreach($cat_posts as $key => $values) {
$category_id = get_cat_ID( $key );
echo '<a href="'.get_category_link($category_id).'">'.$key.'</a>';
$values = array_slice($values,0,$post_count,true);
echo '<ul>';
foreach ($values as $post_id => $value){
echo '<li><a href="'.get_permalink($post_id).'">' . $value . '</a></li>';
}
echo '</ul>';
}
``` |
365,787 | <p>In category display type u can choose between (default, products, subcategories, both) options.
Is there any way to make an if statement that uses those values?</p>
<p>I would like todo something like the below but i'm having a hard time figuring out how u can check for those values.</p>
<p>Now i have something like the below but that requires me to do this for hundreds of categories</p>
<pre><code><?php if (is_product_category('979') || is_product_category('979')) then do something ?>
</code></pre>
<p>So i'm actually looking for something like the below</p>
<pre><code><?php if (category is display type ('products')) then do something ?>
</code></pre>
<p>So if anyone know a way to filter using display type that would be great.</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 365852,
"author": "Karthick",
"author_id": 186872,
"author_profile": "https://wordpress.stackexchange.com/users/186872",
"pm_score": 2,
"selected": true,
"text": "<p>I have used <a href=\"https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query\" rel=\"nofollow noreferrer\">Custom Select Query</a> to gather all information in a single call and hope it may work out.</p>\n\n<pre><code>global $wpdb;\n$selected_cat_id = '6,7,8,9';\n$post_count = 5;\n\n$custom_query = \"SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->terms.name FROM $wpdb->posts \nLEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) \nLEFT JOIN $wpdb->terms ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id) \nWHERE 1=1 AND ($wpdb->term_relationships.term_taxonomy_id IN ($selected_cat_id))\nAND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') ORDER BY $wpdb->posts.post_date ASC\";\n$pageposts = $wpdb->get_results($custom_query, OBJECT);\n\n$cat_posts = array();\nforeach($pageposts as $post){\n $cat_posts[$post->name][$post->ID] = $post->post_title;\n}\n\nforeach($cat_posts as $key => $values) {\n $category_id = get_cat_ID( $key );\n echo '<a href=\"'.get_category_link($category_id).'\">'.$key.'</a>';\n $values = array_slice($values,0,$post_count,true);\n echo '<ul>';\n foreach ($values as $post_id => $value){\n echo '<li><a href=\"'.get_permalink($post_id).'\">' . $value . '</a></li>';\n }\n echo '</ul>';\n}\n</code></pre>\n"
},
{
"answer_id": 365882,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": 0,
"selected": false,
"text": "<p>Use 'category_name' as direct argument in your $args array, not inside your tax_query array. I always displayed posts of a category on my pages in that way. </p>\n"
}
] | 2020/05/04 | [
"https://wordpress.stackexchange.com/questions/365787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184144/"
] | In category display type u can choose between (default, products, subcategories, both) options.
Is there any way to make an if statement that uses those values?
I would like todo something like the below but i'm having a hard time figuring out how u can check for those values.
Now i have something like the below but that requires me to do this for hundreds of categories
```
<?php if (is_product_category('979') || is_product_category('979')) then do something ?>
```
So i'm actually looking for something like the below
```
<?php if (category is display type ('products')) then do something ?>
```
So if anyone know a way to filter using display type that would be great.
Thanks in advance | I have used [Custom Select Query](https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query) to gather all information in a single call and hope it may work out.
```
global $wpdb;
$selected_cat_id = '6,7,8,9';
$post_count = 5;
$custom_query = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->terms.name FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->terms ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id)
WHERE 1=1 AND ($wpdb->term_relationships.term_taxonomy_id IN ($selected_cat_id))
AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') ORDER BY $wpdb->posts.post_date ASC";
$pageposts = $wpdb->get_results($custom_query, OBJECT);
$cat_posts = array();
foreach($pageposts as $post){
$cat_posts[$post->name][$post->ID] = $post->post_title;
}
foreach($cat_posts as $key => $values) {
$category_id = get_cat_ID( $key );
echo '<a href="'.get_category_link($category_id).'">'.$key.'</a>';
$values = array_slice($values,0,$post_count,true);
echo '<ul>';
foreach ($values as $post_id => $value){
echo '<li><a href="'.get_permalink($post_id).'">' . $value . '</a></li>';
}
echo '</ul>';
}
``` |
365,788 | <p>I really new in Wordpress development and have a little bit of knowledge of jquery.
I was trying to understand a WordPress plugin and also trying to understand the js code they wrote for the plugin.
I don't understand what does the following code mean.</p>
<pre><code>(function( api, wp, $ ) {
'use strict';
})( wp.customize, wp, jQuery );
</code></pre>
<p>what is <strong>api</strong> , <strong>wp</strong> and <strong>$</strong> at the top and <strong>wp.customize</strong> , <strong>wp</strong> , <strong>jQuery</strong> at the bottom mean? </p>
| [
{
"answer_id": 365792,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": -1,
"selected": false,
"text": "<p>As I understand it, this function just tells you that strict mode (<a href=\"https://www.w3schools.com/js/js_strict.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/js/js_strict.asp</a>) is being used for the execution of jQuery Scripts of your WordPress customizer. api here just refers to the \"connection\" onto a specific part, which in this case is the wordpress customizer (<a href=\"https://developer.wordpress.org/themes/customize-api/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/customize-api/</a>).</p>\n"
},
{
"answer_id": 365841,
"author": "kwellmann",
"author_id": 186667,
"author_profile": "https://wordpress.stackexchange.com/users/186667",
"pm_score": 3,
"selected": true,
"text": "<p>It's an Immediately Invoked Function Expression (IIFE) - an anonymous function that executes itself after it has been defined.\nThe variables at the bottom are taken from the global scope and are passed as parameters to the anonymous function.</p>\n\n<p>So <code>api</code> represents <code>wp.customize</code>,<br>\n<code>wp</code> represents <code>wp</code> and<br>\n<code>$</code> represents <code>jQuery</code> inside the function.</p>\n"
}
] | 2020/05/04 | [
"https://wordpress.stackexchange.com/questions/365788",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186128/"
] | I really new in Wordpress development and have a little bit of knowledge of jquery.
I was trying to understand a WordPress plugin and also trying to understand the js code they wrote for the plugin.
I don't understand what does the following code mean.
```
(function( api, wp, $ ) {
'use strict';
})( wp.customize, wp, jQuery );
```
what is **api** , **wp** and **$** at the top and **wp.customize** , **wp** , **jQuery** at the bottom mean? | It's an Immediately Invoked Function Expression (IIFE) - an anonymous function that executes itself after it has been defined.
The variables at the bottom are taken from the global scope and are passed as parameters to the anonymous function.
So `api` represents `wp.customize`,
`wp` represents `wp` and
`$` represents `jQuery` inside the function. |
365,814 | <p>I am trying to create a post when my <a href="https://www.gravityforms.com/" rel="nofollow noreferrer">Gravity Form</a> submits and redirect to the post permalink on form confirmation.</p>
<p>See below the function which creates my post/order when my form submits using the <a href="https://docs.gravityforms.com/gform_after_submission/" rel="nofollow noreferrer"><code>gform_after_submission</code></a> action.</p>
<pre><code>add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );
/**
* ajax reload the cart summary
* @param object $entry
* @param array $form
* @return void
*/
public function create_order($entry,$form)
{
// convert keys to admin labels
$entry = self::admin_labels($entry,$form);
// get the current cart data array
$data = self::data();
// create an order array
$order = [
'post_author' => User::$id,
'post_content' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
'post_type' => 'purchase-order',
'post_status' => 'publish'
];
// create order post using an array and return the post id
$result = wp_insert_post($order);
// if post id and is not a wp error then
if($result && !is_wp_error($result)) {
// get the id
$post_id = $result;
// update gform meta with the order id
gform_update_meta($entry['id'],'order_id',$post_id );
// create our order reference number
$order_ref = str_pad($post_id,5,'0',STR_PAD_LEFT);
// create our title
$title = 'Order #' . $order_ref;
// new order array of updates
$order = [
'ID' => $post_id,
'post_title' => $title,
'post_name' => $order_ref
];
// update the order with new details
wp_update_post($order);
// set the the order type as purchase order
wp_set_post_terms($post_id,'purchase-order','order_type');
// update all the order custom fields
self::update_order_fields($post_id,User::$id,$data,$entry);
// unset cookie
unset($_COOKIE['wm_cart']);
// re set cookie and backdate to end cookie
setcookie('wm_cart', null, -1, '/');
}
}
</code></pre>
<p><br/>The above code works good and creates my order/post fine.</p>
<p>I am then trying to redirect to the newly created post when the form confirmations fires.</p>
<p>So i'm using <a href="https://docs.gravityforms.com/gform_confirmation/" rel="nofollow noreferrer"><code>gform_confirmation</code></a> filter but I can't find away to the pass the id to here. </p>
<pre><code>add_filter('gform_confirmation_1', [ $this, 'order_confirmation' ], 10, 4 );
/**
* ajax reload the cart summary
* @param array $confirmation
* @param array $form
* @param object $entry
* @param array $ajax
* @return array $confirmation
*/
public function order_confirmation($confirmation,$form,$entry,$ajax)
{
// get order id from gform get meta
$post_id = gform_get_meta($entry['id'],'order_id');
// confirmation
$confirmation = array( 'redirect' => get_permalink( $post_id ) );
// return confirmation
return $confirmation;
}
</code></pre>
<p><br/>
I cant redirect in the submission because my form is AJAX, and the redirect just happens in the ajax call, so I am having to try to use <code>$confirmation</code> to modify the redirect.</p>
<p>Can anyone help me figure out a safe way to redirect to my newly created post via the submission?</p>
<p>Thanks
<br/></p>
| [
{
"answer_id": 365817,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>The entry object is available in both hooks, so how about saving the created post ID as meta on the entry with <a href=\"https://docs.gravityforms.com/gform_update_meta/\" rel=\"nofollow noreferrer\"><code>gform_update_meta()</code></a>:</p>\n\n<pre><code>gform_update_meta( $entry->id, 'order_id', $post_id );\n</code></pre>\n\n<p>Then retrieving it in the confirmation, using <a href=\"https://docs.gravityforms.com/gform_get_meta/\" rel=\"nofollow noreferrer\"><code>gform_get_meta()</code></a>:</p>\n\n<pre><code>$post_id = gform_get_meta( $entry->id, 'order_id' );\n</code></pre>\n"
},
{
"answer_id": 365833,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 0,
"selected": false,
"text": "<p>So basically I managed get <a href=\"https://wordpress.stackexchange.com/users/39152/jacob-peattie\">Jacob Peattie</a> idea working by using..</p>\n\n<pre><code>add_action('gform_pre_handle_confirmation', [ $this, 'create_order' ], 10, 2 );\n</code></pre>\n\n<p>instead of...</p>\n\n<pre><code>add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );\n</code></pre>\n\n<p>But you can't specify the form with <code>gform_pre_handle_confirmation</code> action so I had put this check in my <code>create_order</code> function to make sure this only runs for this form.</p>\n\n<pre><code>// only allow this method to handle form 1\nif (!array_key_exists('id', $form) || $form['id'] <> 1) {\n return;\n}\n</code></pre>\n"
}
] | 2020/05/04 | [
"https://wordpress.stackexchange.com/questions/365814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111152/"
] | I am trying to create a post when my [Gravity Form](https://www.gravityforms.com/) submits and redirect to the post permalink on form confirmation.
See below the function which creates my post/order when my form submits using the [`gform_after_submission`](https://docs.gravityforms.com/gform_after_submission/) action.
```
add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );
/**
* ajax reload the cart summary
* @param object $entry
* @param array $form
* @return void
*/
public function create_order($entry,$form)
{
// convert keys to admin labels
$entry = self::admin_labels($entry,$form);
// get the current cart data array
$data = self::data();
// create an order array
$order = [
'post_author' => User::$id,
'post_content' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
'post_type' => 'purchase-order',
'post_status' => 'publish'
];
// create order post using an array and return the post id
$result = wp_insert_post($order);
// if post id and is not a wp error then
if($result && !is_wp_error($result)) {
// get the id
$post_id = $result;
// update gform meta with the order id
gform_update_meta($entry['id'],'order_id',$post_id );
// create our order reference number
$order_ref = str_pad($post_id,5,'0',STR_PAD_LEFT);
// create our title
$title = 'Order #' . $order_ref;
// new order array of updates
$order = [
'ID' => $post_id,
'post_title' => $title,
'post_name' => $order_ref
];
// update the order with new details
wp_update_post($order);
// set the the order type as purchase order
wp_set_post_terms($post_id,'purchase-order','order_type');
// update all the order custom fields
self::update_order_fields($post_id,User::$id,$data,$entry);
// unset cookie
unset($_COOKIE['wm_cart']);
// re set cookie and backdate to end cookie
setcookie('wm_cart', null, -1, '/');
}
}
```
The above code works good and creates my order/post fine.
I am then trying to redirect to the newly created post when the form confirmations fires.
So i'm using [`gform_confirmation`](https://docs.gravityforms.com/gform_confirmation/) filter but I can't find away to the pass the id to here.
```
add_filter('gform_confirmation_1', [ $this, 'order_confirmation' ], 10, 4 );
/**
* ajax reload the cart summary
* @param array $confirmation
* @param array $form
* @param object $entry
* @param array $ajax
* @return array $confirmation
*/
public function order_confirmation($confirmation,$form,$entry,$ajax)
{
// get order id from gform get meta
$post_id = gform_get_meta($entry['id'],'order_id');
// confirmation
$confirmation = array( 'redirect' => get_permalink( $post_id ) );
// return confirmation
return $confirmation;
}
```
I cant redirect in the submission because my form is AJAX, and the redirect just happens in the ajax call, so I am having to try to use `$confirmation` to modify the redirect.
Can anyone help me figure out a safe way to redirect to my newly created post via the submission?
Thanks | The entry object is available in both hooks, so how about saving the created post ID as meta on the entry with [`gform_update_meta()`](https://docs.gravityforms.com/gform_update_meta/):
```
gform_update_meta( $entry->id, 'order_id', $post_id );
```
Then retrieving it in the confirmation, using [`gform_get_meta()`](https://docs.gravityforms.com/gform_get_meta/):
```
$post_id = gform_get_meta( $entry->id, 'order_id' );
``` |
365,848 | <p>I am using the Shamrock theme and I am happy with link colours on the main page however when you go into a blog post and hover over any links within the body they are red. </p>
<p>I have tried multiple things with CSS (after hours of googling as I do not know CSS) and without using !important and therefore changing ALL links I can't get just the links within the blog posts to change when hovering over them.</p>
<p>Is anyone able to help with this, please?</p>
| [
{
"answer_id": 365817,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>The entry object is available in both hooks, so how about saving the created post ID as meta on the entry with <a href=\"https://docs.gravityforms.com/gform_update_meta/\" rel=\"nofollow noreferrer\"><code>gform_update_meta()</code></a>:</p>\n\n<pre><code>gform_update_meta( $entry->id, 'order_id', $post_id );\n</code></pre>\n\n<p>Then retrieving it in the confirmation, using <a href=\"https://docs.gravityforms.com/gform_get_meta/\" rel=\"nofollow noreferrer\"><code>gform_get_meta()</code></a>:</p>\n\n<pre><code>$post_id = gform_get_meta( $entry->id, 'order_id' );\n</code></pre>\n"
},
{
"answer_id": 365833,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 0,
"selected": false,
"text": "<p>So basically I managed get <a href=\"https://wordpress.stackexchange.com/users/39152/jacob-peattie\">Jacob Peattie</a> idea working by using..</p>\n\n<pre><code>add_action('gform_pre_handle_confirmation', [ $this, 'create_order' ], 10, 2 );\n</code></pre>\n\n<p>instead of...</p>\n\n<pre><code>add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );\n</code></pre>\n\n<p>But you can't specify the form with <code>gform_pre_handle_confirmation</code> action so I had put this check in my <code>create_order</code> function to make sure this only runs for this form.</p>\n\n<pre><code>// only allow this method to handle form 1\nif (!array_key_exists('id', $form) || $form['id'] <> 1) {\n return;\n}\n</code></pre>\n"
}
] | 2020/05/04 | [
"https://wordpress.stackexchange.com/questions/365848",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187431/"
] | I am using the Shamrock theme and I am happy with link colours on the main page however when you go into a blog post and hover over any links within the body they are red.
I have tried multiple things with CSS (after hours of googling as I do not know CSS) and without using !important and therefore changing ALL links I can't get just the links within the blog posts to change when hovering over them.
Is anyone able to help with this, please? | The entry object is available in both hooks, so how about saving the created post ID as meta on the entry with [`gform_update_meta()`](https://docs.gravityforms.com/gform_update_meta/):
```
gform_update_meta( $entry->id, 'order_id', $post_id );
```
Then retrieving it in the confirmation, using [`gform_get_meta()`](https://docs.gravityforms.com/gform_get_meta/):
```
$post_id = gform_get_meta( $entry->id, 'order_id' );
``` |
365,860 | <p>Was just checking the error logs on a new install of 5.4.1 and see a lot:</p>
<pre><code>Got error 'PHP message: PHP Deprecated: media_buttons_context is <strong>deprecated</strong> since version 3.5.0! Use media_buttons instead. in /var/www/susites/evozyne/htdocs/wp-includes/functions.php on line 5088', referer: https://evozyne.highgatewebworks.com/wp-admin/post.php?post=8&action=edit
</code></pre>
<p>I can't find any mention of this anywhere except in an old WordPress Core discussion.</p>
<p>Can anyone shed some light on this?</p>
<p>Brad</p>
| [
{
"answer_id": 365868,
"author": "Brooke.",
"author_id": 2204,
"author_profile": "https://wordpress.stackexchange.com/users/2204",
"pm_score": 0,
"selected": false,
"text": "<p>According to the developer documentation, <a href=\"https://developer.wordpress.org/reference/hooks/media_buttons_context/\" rel=\"nofollow noreferrer\"><code>media_buttons_context</code></a> has been deprecated since 3.5.0 in favor of <a href=\"https://developer.wordpress.org/reference/hooks/media_buttons/\" rel=\"nofollow noreferrer\"><code>media_buttons</code></a>. The Warning is there to point you in the right direction to update the code to use the newer, preferred function. </p>\n\n<p>I bet if you do a search of your codebase (active plugins and theme) you'll find <code>media_buttons_context</code> somewhere which should be updated. </p>\n"
},
{
"answer_id": 365897,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 1,
"selected": false,
"text": "<p>Try this media_buttons instead of media_buttons_context</p>\n\n<p>Please refer these URL:\n<a href=\"https://developer.wordpress.org/reference/hooks/media_buttons_context/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/media_buttons_context/</a>\n<a href=\"https://developer.wordpress.org/reference/hooks/media_buttons/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/media_buttons/</a></p>\n"
}
] | 2020/05/05 | [
"https://wordpress.stackexchange.com/questions/365860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153797/"
] | Was just checking the error logs on a new install of 5.4.1 and see a lot:
```
Got error 'PHP message: PHP Deprecated: media_buttons_context is <strong>deprecated</strong> since version 3.5.0! Use media_buttons instead. in /var/www/susites/evozyne/htdocs/wp-includes/functions.php on line 5088', referer: https://evozyne.highgatewebworks.com/wp-admin/post.php?post=8&action=edit
```
I can't find any mention of this anywhere except in an old WordPress Core discussion.
Can anyone shed some light on this?
Brad | Try this media\_buttons instead of media\_buttons\_context
Please refer these URL:
<https://developer.wordpress.org/reference/hooks/media_buttons_context/>
<https://developer.wordpress.org/reference/hooks/media_buttons/> |
365,863 | <p>I am having an issue with using global variables to get values inserted into my custom database table:</p>
<pre><code>// example that does not work
$user = wp_get_current_user();
$mega = $user->user_login; // this values will return blank when
// inserted into database especially
// when used with an if statement.
</code></pre>
<p>The values work fine within the code in making a database query, but once inserted into the database it returns a blank empty value.</p>
<pre><code> // here is my full code
global $wp;
$user = wp_get_current_user();
$mega = $user->user_login;
$age = 19;
// if records were not found in the database
// then insert new row with the details
if ( $age == 19) {
$fillup = $wpdb->insert("markrecord_table", array(
"username" => $mega,
"post_id" => 340,
"counted" => 1,
));
}
</code></pre>
| [
{
"answer_id": 365868,
"author": "Brooke.",
"author_id": 2204,
"author_profile": "https://wordpress.stackexchange.com/users/2204",
"pm_score": 0,
"selected": false,
"text": "<p>According to the developer documentation, <a href=\"https://developer.wordpress.org/reference/hooks/media_buttons_context/\" rel=\"nofollow noreferrer\"><code>media_buttons_context</code></a> has been deprecated since 3.5.0 in favor of <a href=\"https://developer.wordpress.org/reference/hooks/media_buttons/\" rel=\"nofollow noreferrer\"><code>media_buttons</code></a>. The Warning is there to point you in the right direction to update the code to use the newer, preferred function. </p>\n\n<p>I bet if you do a search of your codebase (active plugins and theme) you'll find <code>media_buttons_context</code> somewhere which should be updated. </p>\n"
},
{
"answer_id": 365897,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 1,
"selected": false,
"text": "<p>Try this media_buttons instead of media_buttons_context</p>\n\n<p>Please refer these URL:\n<a href=\"https://developer.wordpress.org/reference/hooks/media_buttons_context/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/media_buttons_context/</a>\n<a href=\"https://developer.wordpress.org/reference/hooks/media_buttons/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/media_buttons/</a></p>\n"
}
] | 2020/05/05 | [
"https://wordpress.stackexchange.com/questions/365863",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152456/"
] | I am having an issue with using global variables to get values inserted into my custom database table:
```
// example that does not work
$user = wp_get_current_user();
$mega = $user->user_login; // this values will return blank when
// inserted into database especially
// when used with an if statement.
```
The values work fine within the code in making a database query, but once inserted into the database it returns a blank empty value.
```
// here is my full code
global $wp;
$user = wp_get_current_user();
$mega = $user->user_login;
$age = 19;
// if records were not found in the database
// then insert new row with the details
if ( $age == 19) {
$fillup = $wpdb->insert("markrecord_table", array(
"username" => $mega,
"post_id" => 340,
"counted" => 1,
));
}
``` | Try this media\_buttons instead of media\_buttons\_context
Please refer these URL:
<https://developer.wordpress.org/reference/hooks/media_buttons_context/>
<https://developer.wordpress.org/reference/hooks/media_buttons/> |
365,980 | <p>I'm trying to find a way to add repeatable fields inside a custom admin page that I've made.</p>
<p>Code:</p>
<pre><code> /*WordPress Menus API.*/
function add_new_menu_items()
{
add_menu_page(
"Theme Options",
"Theme Options",
"manage_options",
"theme-options",
"theme_options_page",
"",
100
);
}
function theme_options_page()
{
?>
<?php settings_errors(); ?>
<div class="wrap">
<div id="icon-options-general" class="icon32"></div>
<h1>Theme Options</h1>
<form method="post" action="options.php">
<?php
settings_fields("header_section");
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
add_action("admin_menu", "add_new_menu_items");
function display_options()
{
add_settings_section("header_section", "Header Options", "display_header_options_content", "theme-options");
add_settings_field("header_logo", "Logo Url", "display_logo_form_element", "theme-options", "header_section");
add_settings_field("advertising_code", "Ads Code", "display_ads_form_element", "theme-options", "header_section");
register_setting("header_section", "header_logo");
register_setting("header_section", "advertising_code");
}
function display_header_options_content(){echo "The header of the theme";}
function display_logo_form_element()
{
?>
<input type="text" name="header_logo" id="header_logo" value="<?php echo get_option('header_logo'); ?>" />
<?php
}
function display_ads_form_element()
{
?>
<input type="text" name="advertising_code" id="advertising_code" value="<?php echo get_option('advertising_code'); ?>" />
<?php
}
add_action("admin_init", "display_options");
</code></pre>
<p>Is there any way to make advertising_code input repeatable field?</p>
<p>Thank you</p>
| [
{
"answer_id": 365999,
"author": "Ejaz UL Haq",
"author_id": 178714,
"author_profile": "https://wordpress.stackexchange.com/users/178714",
"pm_score": 0,
"selected": false,
"text": "<p>Add at the top of the page after PHP opening tag \nlike <br>\n<code><?php \n$advertising_code = 'advertising_code';</code><br>\nand call it where you need to <br>\n<code>$advertising_code;</code></p>\n"
},
{
"answer_id": 366298,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 1,
"selected": false,
"text": "<p>It`s not the best solution but maybe it is helpful for you to create your own solution. </p>\n\n<pre><code>function display_ads_form_element()\n{\n // get the total number of \"advertising codes\" from the database\n // the default value is 1\n $codes = array('1' => '' );\n if( get_option('advertising_code') !== FALSE ) {\n $codes = get_option('advertising_code');\n }\n ?>\n\n <?php /// button to add the new field // ?>\n <input type=\"button\" onClick=\"add_new_ad_code()\" value=\"add new advertising code\">\n\n <ul id=\"advertising_code_list\" >\n\n <?php foreach($codes as $key => $code): ?>\n\n <?php /// create for every \"advertising code\" an input field // ?>\n <?php /// advertising_codes[key] => square brackets means the data will send as array // ?>\n <?php /// data-listkey => is only an easy way that the js can detect the last key // ?>\n <li><input type=\"text\" name=\"advertising_code[<?php echo esc_attr( $key ); ?>]\" value=\"<?php echo esc_attr( $code ); ?>\" data-listkey=\"<?php echo esc_attr( $key ); ?>\"/></li>\n\n <?php endforeach; ?>\n\n\n </ul>\n\n <script>\n\n function add_new_ad_code() {\n\n // detect the last li element\n const last_li = document.getElementById('advertising_code_list').lastElementChild;\n\n // get the listKey from the input field\n const new_key = parseInt(last_li.childNodes[0].dataset.listkey) + 1;\n\n // create the new list tag\n const li_element = document.createElement('li');\n\n // create the new input tag for the new advertising code\n const input_element = document.createElement('input');\n\n // set the type\n input_element.type = \"text\";\n\n // set the name attribute\n input_element.name = \"advertising_code[\" + new_key + \"]\";\n\n // set empty value\n input_element.value = \"\";\n\n // add the new key as data attribute\n input_element.dataset.listkey = new_key;\n\n // add the new advertising code to the list element\n li_element.appendChild(input_element);\n\n // add the list element to the list\n document.getElementById('advertising_code_list').appendChild(li_element);\n }\n\n </script>\n\n <?php\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/neZ9T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/neZ9T.png\" alt=\"screenshot\"></a></p>\n"
}
] | 2020/05/06 | [
"https://wordpress.stackexchange.com/questions/365980",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187466/"
] | I'm trying to find a way to add repeatable fields inside a custom admin page that I've made.
Code:
```
/*WordPress Menus API.*/
function add_new_menu_items()
{
add_menu_page(
"Theme Options",
"Theme Options",
"manage_options",
"theme-options",
"theme_options_page",
"",
100
);
}
function theme_options_page()
{
?>
<?php settings_errors(); ?>
<div class="wrap">
<div id="icon-options-general" class="icon32"></div>
<h1>Theme Options</h1>
<form method="post" action="options.php">
<?php
settings_fields("header_section");
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
add_action("admin_menu", "add_new_menu_items");
function display_options()
{
add_settings_section("header_section", "Header Options", "display_header_options_content", "theme-options");
add_settings_field("header_logo", "Logo Url", "display_logo_form_element", "theme-options", "header_section");
add_settings_field("advertising_code", "Ads Code", "display_ads_form_element", "theme-options", "header_section");
register_setting("header_section", "header_logo");
register_setting("header_section", "advertising_code");
}
function display_header_options_content(){echo "The header of the theme";}
function display_logo_form_element()
{
?>
<input type="text" name="header_logo" id="header_logo" value="<?php echo get_option('header_logo'); ?>" />
<?php
}
function display_ads_form_element()
{
?>
<input type="text" name="advertising_code" id="advertising_code" value="<?php echo get_option('advertising_code'); ?>" />
<?php
}
add_action("admin_init", "display_options");
```
Is there any way to make advertising\_code input repeatable field?
Thank you | It`s not the best solution but maybe it is helpful for you to create your own solution.
```
function display_ads_form_element()
{
// get the total number of "advertising codes" from the database
// the default value is 1
$codes = array('1' => '' );
if( get_option('advertising_code') !== FALSE ) {
$codes = get_option('advertising_code');
}
?>
<?php /// button to add the new field // ?>
<input type="button" onClick="add_new_ad_code()" value="add new advertising code">
<ul id="advertising_code_list" >
<?php foreach($codes as $key => $code): ?>
<?php /// create for every "advertising code" an input field // ?>
<?php /// advertising_codes[key] => square brackets means the data will send as array // ?>
<?php /// data-listkey => is only an easy way that the js can detect the last key // ?>
<li><input type="text" name="advertising_code[<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( $code ); ?>" data-listkey="<?php echo esc_attr( $key ); ?>"/></li>
<?php endforeach; ?>
</ul>
<script>
function add_new_ad_code() {
// detect the last li element
const last_li = document.getElementById('advertising_code_list').lastElementChild;
// get the listKey from the input field
const new_key = parseInt(last_li.childNodes[0].dataset.listkey) + 1;
// create the new list tag
const li_element = document.createElement('li');
// create the new input tag for the new advertising code
const input_element = document.createElement('input');
// set the type
input_element.type = "text";
// set the name attribute
input_element.name = "advertising_code[" + new_key + "]";
// set empty value
input_element.value = "";
// add the new key as data attribute
input_element.dataset.listkey = new_key;
// add the new advertising code to the list element
li_element.appendChild(input_element);
// add the list element to the list
document.getElementById('advertising_code_list').appendChild(li_element);
}
</script>
<?php
}
```
[](https://i.stack.imgur.com/neZ9T.png) |
365,986 | <p>I am trying to redirect non-existing woocommerce product's url's to worpdress page.</p>
<p>Example:</p>
<p><a href="https://testname.com/product/abc" rel="nofollow noreferrer">https://testname.com/product/abc</a> to <a href="https://testname.com/sample-page" rel="nofollow noreferrer">https://testname.com/sample-page</a></p>
<p>here there is no product published as abc.</p>
<p>also i have few working products at <a href="https://testname.com/product/def" rel="nofollow noreferrer">https://testname.com/product/def</a>.</p>
<p>i tried with .htaccess but looks like it's not possible to use .htaccess in this case.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 366072,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible with the .htaccess file, add the below rule in the .htaccess:</p>\n\n<p>Redirect 301 <a href=\"https://testname.com/product/abc\" rel=\"nofollow noreferrer\">https://testname.com/product/abc</a> <a href=\"https://testname.com/sample-page\" rel=\"nofollow noreferrer\">https://testname.com/sample-page</a></p>\n\n<p>or</p>\n\n<p>Redirect 301 /product/abc /sample-page</p>\n"
},
{
"answer_id": 366079,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>If you prefer more control in coding, you may use</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/request/\" rel=\"nofollow noreferrer\">request hook</a> - test the WordPress query after it is being setup</li>\n<li><a href=\"https://www.php.net/manual/en/function.preg-match.php\" rel=\"nofollow noreferrer\">preg_match()</a> - match <code>/product/</code> keyword</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/url_to_postid/\" rel=\"nofollow noreferrer\">url_to_postid()</a> - test if product url exists</li>\n</ul>\n\n<p>to build a checking when <code>WordPress query is being setup</code>. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.</p>\n\n<p>The following code is placed in theme functions.php and proved to work in a testing site.</p>\n\n<pre><code>add_filter( 'request', 'ws365986_check_request' );\nfunction ws365986_check_request( $query ) {\n // var_dump($_SERVER['REQUEST_URI']); // for debug\n\n // only check for product url if /product/ is found in URL\n if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\\/product\\//', $_SERVER['REQUEST_URI'], $matches ) ) {\n // check if url product exist\n if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {\n // redirect if return is 0 (empty)\n\n $url = home_url( '/sample-page' );\n // wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough\n wp_safe_redirect( $url );\n exit(); // exit script after redirect\n }\n }\n\n // default\n return $query;\n}\n</code></pre>\n"
}
] | 2020/05/06 | [
"https://wordpress.stackexchange.com/questions/365986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5669/"
] | I am trying to redirect non-existing woocommerce product's url's to worpdress page.
Example:
<https://testname.com/product/abc> to <https://testname.com/sample-page>
here there is no product published as abc.
also i have few working products at <https://testname.com/product/def>.
i tried with .htaccess but looks like it's not possible to use .htaccess in this case.
Thanks in advance. | If you prefer more control in coding, you may use
* [request hook](https://developer.wordpress.org/reference/hooks/request/) - test the WordPress query after it is being setup
* [preg\_match()](https://www.php.net/manual/en/function.preg-match.php) - match `/product/` keyword
* [url\_to\_postid()](https://developer.wordpress.org/reference/functions/url_to_postid/) - test if product url exists
to build a checking when `WordPress query is being setup`. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.
The following code is placed in theme functions.php and proved to work in a testing site.
```
add_filter( 'request', 'ws365986_check_request' );
function ws365986_check_request( $query ) {
// var_dump($_SERVER['REQUEST_URI']); // for debug
// only check for product url if /product/ is found in URL
if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\/product\//', $_SERVER['REQUEST_URI'], $matches ) ) {
// check if url product exist
if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {
// redirect if return is 0 (empty)
$url = home_url( '/sample-page' );
// wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough
wp_safe_redirect( $url );
exit(); // exit script after redirect
}
}
// default
return $query;
}
``` |
365,998 | <p>I'm trying to add products using data gathered from a Caldera form. I'm successful in creating the product and adding other attributes, but 'reviews_allowed' is proving to be elusive.</p>
<pre><code>$post_id = wp_insert_post(array(
'post_title' => 'ProductName '.$data['uniquenumber'],
'post_type' => 'product',
'post_status' => 'draft',
'post_content' => $data[ 'description' ],
'post_excerpt' => $data[ 'short_description' ]
));
wp_set_object_terms( $post_id, 'simple,virtual', 'product_type' );
wp_set_object_terms( $post_id, ['services'] ,'product_cat');
wp_set_object_terms( $post_id, 1 ,'reviews_allowed' ); // DOESN'T WORK
//update_post_meta( $post_id, 'reviews_allowed', 'yes'); //CREATES SEPARATE ATTRIBUTE,
// All these work though
update_post_meta( $post_id, 'real_name', $data['first_name']." ".$data['last_name'] );
update_post_meta( $post_id, '_nyp', 'yes' );
update_post_meta( $post_id, '_virtual', 'yes' );
update_post_meta( $post_id, '_visibility', 'visible' );
</code></pre>
<p>I've searched throught the WC code and I'm pretty sure the attribute is 'reviews_allowed' and the type is bool. I'm new to this, so I hope/expect this is an easy problem.</p>
<p>Thanks,
John</p>
| [
{
"answer_id": 366072,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible with the .htaccess file, add the below rule in the .htaccess:</p>\n\n<p>Redirect 301 <a href=\"https://testname.com/product/abc\" rel=\"nofollow noreferrer\">https://testname.com/product/abc</a> <a href=\"https://testname.com/sample-page\" rel=\"nofollow noreferrer\">https://testname.com/sample-page</a></p>\n\n<p>or</p>\n\n<p>Redirect 301 /product/abc /sample-page</p>\n"
},
{
"answer_id": 366079,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>If you prefer more control in coding, you may use</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/request/\" rel=\"nofollow noreferrer\">request hook</a> - test the WordPress query after it is being setup</li>\n<li><a href=\"https://www.php.net/manual/en/function.preg-match.php\" rel=\"nofollow noreferrer\">preg_match()</a> - match <code>/product/</code> keyword</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/url_to_postid/\" rel=\"nofollow noreferrer\">url_to_postid()</a> - test if product url exists</li>\n</ul>\n\n<p>to build a checking when <code>WordPress query is being setup</code>. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.</p>\n\n<p>The following code is placed in theme functions.php and proved to work in a testing site.</p>\n\n<pre><code>add_filter( 'request', 'ws365986_check_request' );\nfunction ws365986_check_request( $query ) {\n // var_dump($_SERVER['REQUEST_URI']); // for debug\n\n // only check for product url if /product/ is found in URL\n if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\\/product\\//', $_SERVER['REQUEST_URI'], $matches ) ) {\n // check if url product exist\n if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {\n // redirect if return is 0 (empty)\n\n $url = home_url( '/sample-page' );\n // wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough\n wp_safe_redirect( $url );\n exit(); // exit script after redirect\n }\n }\n\n // default\n return $query;\n}\n</code></pre>\n"
}
] | 2020/05/06 | [
"https://wordpress.stackexchange.com/questions/365998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187547/"
] | I'm trying to add products using data gathered from a Caldera form. I'm successful in creating the product and adding other attributes, but 'reviews\_allowed' is proving to be elusive.
```
$post_id = wp_insert_post(array(
'post_title' => 'ProductName '.$data['uniquenumber'],
'post_type' => 'product',
'post_status' => 'draft',
'post_content' => $data[ 'description' ],
'post_excerpt' => $data[ 'short_description' ]
));
wp_set_object_terms( $post_id, 'simple,virtual', 'product_type' );
wp_set_object_terms( $post_id, ['services'] ,'product_cat');
wp_set_object_terms( $post_id, 1 ,'reviews_allowed' ); // DOESN'T WORK
//update_post_meta( $post_id, 'reviews_allowed', 'yes'); //CREATES SEPARATE ATTRIBUTE,
// All these work though
update_post_meta( $post_id, 'real_name', $data['first_name']." ".$data['last_name'] );
update_post_meta( $post_id, '_nyp', 'yes' );
update_post_meta( $post_id, '_virtual', 'yes' );
update_post_meta( $post_id, '_visibility', 'visible' );
```
I've searched throught the WC code and I'm pretty sure the attribute is 'reviews\_allowed' and the type is bool. I'm new to this, so I hope/expect this is an easy problem.
Thanks,
John | If you prefer more control in coding, you may use
* [request hook](https://developer.wordpress.org/reference/hooks/request/) - test the WordPress query after it is being setup
* [preg\_match()](https://www.php.net/manual/en/function.preg-match.php) - match `/product/` keyword
* [url\_to\_postid()](https://developer.wordpress.org/reference/functions/url_to_postid/) - test if product url exists
to build a checking when `WordPress query is being setup`. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.
The following code is placed in theme functions.php and proved to work in a testing site.
```
add_filter( 'request', 'ws365986_check_request' );
function ws365986_check_request( $query ) {
// var_dump($_SERVER['REQUEST_URI']); // for debug
// only check for product url if /product/ is found in URL
if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\/product\//', $_SERVER['REQUEST_URI'], $matches ) ) {
// check if url product exist
if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {
// redirect if return is 0 (empty)
$url = home_url( '/sample-page' );
// wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough
wp_safe_redirect( $url );
exit(); // exit script after redirect
}
}
// default
return $query;
}
``` |
366,017 | <p>I want to set post title for alt and title Attribute in this code</p>
<p>what should I do?</p>
<pre><code><?php
if ( true == get_theme_mod( 'archive_featured_images', true ) ) :
if ( has_post_thumbnail() && ( get_the_post_thumbnail() != '' ) ) :
echo '<a class="featured-image" href="'. esc_url( get_permalink() ) .'" title="'. the_title_attribute( 'echo=0' ) .'">';
echo '<span itemprop="image" itemscope itemtype="https://schema.org/ImageObject">';
the_post_thumbnail( 'mudra-featured-image' );
$mudra_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'mudra-featured-image' );
echo '<meta itemprop="url" content="' . esc_url( $mudra_image[0] ) . '">';
echo '<meta itemprop="width" content="' . esc_attr( $mudra_image[1] ) . '">';
echo '<meta itemprop="height" content="' . esc_attr( $mudra_image[2] ) . '">';
echo '</span>';
echo '</a>';
endif;
endif;
?>
</code></pre>
| [
{
"answer_id": 366034,
"author": "Aboelabbas",
"author_id": 119142,
"author_profile": "https://wordpress.stackexchange.com/users/119142",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the second parameter of <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">the_post_thumbnail()</a> function.</p>\n\n<pre><code>the_post_thumbnail( 'mudra-featured-image', ['alt' => get_the_title()] );\n</code></pre>\n\n<p>Another option, you can do this using the filter <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/\" rel=\"nofollow noreferrer\">wp_get_attachment_image_attributes</a> </p>\n\n<pre><code>add_filter('wp_get_attachment_image_attributes', function($attr){\n $attr['alt'] = get_the_title();\n return $attr;\n});\n</code></pre>\n\n<p>Note, using the filter will affect other images printed using any function that depends on <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\" rel=\"nofollow noreferrer\">wp_get_attachment_image()</a></p>\n\n<p>So, you may use the other two attributes passed to the callback function for more control.\nExample, if you want apply this only on the size \"mudra-featured-image\", your code will be something like this</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment, $size ){\n\n // Return the current $attr array as it is if the size is not \"mudra-featured-image\"\n if( 'mudra-featured-image' !== $size ){\n return $attr;\n }\n // If it is our targeted size then, change the \"alt\" attribute\n $attr['alt'] = get_the_title();\n return $attr;\n\n}, 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 408814,
"author": "Michel Moraes",
"author_id": 109142,
"author_profile": "https://wordpress.stackexchange.com/users/109142",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the third parameter of the function:</p>\n<pre><code>get_the_post_thumbnail($post, $size, $attr);\n</code></pre>\n<p>Example:</p>\n<pre><code>get_the_post_thumbnail(\n $post,\n '',\n array(\n 'alt' => 'anything',\n 'title' => 'anything',\n )\n);\n</code></pre>\n<p><strong>Parameters</strong></p>\n<p><strong>$post</strong></p>\n<p>(int|WP_Post) (Optional)\nPost ID or WP_Post object. Default is global $post.\nDefault value: null</p>\n<p><strong>$size</strong></p>\n<p>(string|int[]) (Optional) Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order).\nDefault value: 'post-thumbnail'</p>\n<p><strong>$attr</strong>\n(string|array) (Optional) Query string or array of attributes.\nDefault value: ''</p>\n<p>You can get more details here: <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/</a></p>\n"
}
] | 2020/05/07 | [
"https://wordpress.stackexchange.com/questions/366017",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115412/"
] | I want to set post title for alt and title Attribute in this code
what should I do?
```
<?php
if ( true == get_theme_mod( 'archive_featured_images', true ) ) :
if ( has_post_thumbnail() && ( get_the_post_thumbnail() != '' ) ) :
echo '<a class="featured-image" href="'. esc_url( get_permalink() ) .'" title="'. the_title_attribute( 'echo=0' ) .'">';
echo '<span itemprop="image" itemscope itemtype="https://schema.org/ImageObject">';
the_post_thumbnail( 'mudra-featured-image' );
$mudra_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'mudra-featured-image' );
echo '<meta itemprop="url" content="' . esc_url( $mudra_image[0] ) . '">';
echo '<meta itemprop="width" content="' . esc_attr( $mudra_image[1] ) . '">';
echo '<meta itemprop="height" content="' . esc_attr( $mudra_image[2] ) . '">';
echo '</span>';
echo '</a>';
endif;
endif;
?>
``` | You can use the second parameter of [the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/the_post_thumbnail/) function.
```
the_post_thumbnail( 'mudra-featured-image', ['alt' => get_the_title()] );
```
Another option, you can do this using the filter [wp\_get\_attachment\_image\_attributes](https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/)
```
add_filter('wp_get_attachment_image_attributes', function($attr){
$attr['alt'] = get_the_title();
return $attr;
});
```
Note, using the filter will affect other images printed using any function that depends on [wp\_get\_attachment\_image()](https://developer.wordpress.org/reference/functions/wp_get_attachment_image/)
So, you may use the other two attributes passed to the callback function for more control.
Example, if you want apply this only on the size "mudra-featured-image", your code will be something like this
```
add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment, $size ){
// Return the current $attr array as it is if the size is not "mudra-featured-image"
if( 'mudra-featured-image' !== $size ){
return $attr;
}
// If it is our targeted size then, change the "alt" attribute
$attr['alt'] = get_the_title();
return $attr;
}, 10, 3 );
``` |
366,033 | <p>How do I change a parameter/text that are specified in the core without editing the core?</p>
<p>For example, this is a part of of comment-template.php from the wp-includes directory:</p>
<pre><code>$fields = apply_filters( 'comment_form_default_fields', $fields );
$defaults = array(
'fields' => $fields,
'comment_field' => sprintf(
'<p class="comment-form-comment">%s %s</p>',
sprintf(
'<label for="comment">%s</label>',
_x( 'Comment', 'noun' )
),
'<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
),
</code></pre>
<p>That's a part of the thingie that displays the comment form, and writes the word "<strong>Comment</strong>" above the text field.</p>
<p>Now, if I want to change the word <strong>Comment</strong> to <strong>Please leave a comment...</strong>, How do I do it?</p>
<p>I understand that some kind of hook need to be used and placed in the functions.php file, but there ends my knowledge, and just change the core file is a big NO-NO!</p>
<p>Edit:</p>
<p>On line 2433 (wp 5.4.2)</p>
<pre><code>'title_reply' => __( 'Leave a Reply' ),
</code></pre>
<p>I just changed it to;</p>
<pre><code> 'title_reply
' => __( '' ),
</code></pre>
<p>I just don't want to show it..</p>
<p>Line 2441</p>
<pre><code>'label_submit' => __( 'Post Comment' ),
</code></pre>
<p>changed it to:</p>
<pre><code>'label_submit' => __( ' Submit your thoughts...' ),
</code></pre>
<p>And finally (almost), line 2531</p>
<pre><code>echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity );
</code></pre>
<p>Changed it to</p>
<pre><code>echo apply_filters( 'comment_form_logged_in', '' );
</code></pre>
<p>Don't want to display this either..</p>
<p>And on line 2420</p>
<pre><code>sprintf(
'<span id="email-notes">%s</span>',
__( 'Your email address will not be published.' )
),
</code></pre>
<p>That one I don't want to be shown at all..</p>
<p>That's how I previously has changed the core comment-temple.php file.</p>
<p>How do I do it in the functions.php</p>
<p>(It will affect pages like: <a href="https://rainbowpets.org/rasmus/" rel="nofollow noreferrer">https://rainbowpets.org/rasmus/</a> )</p>
| [
{
"answer_id": 366147,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 2,
"selected": true,
"text": "<p>If you scroll further down the comment-template.php file, you'll notice that the next available filter you can use is <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_defaults/\" rel=\"nofollow noreferrer\"><code>comment_form_defaults</code></a>. With this filter you can change the default comment form configuration. </p>\n\n<pre><code>add_filter( 'comment_form_defaults', 'filter_comment_form_defaults' );\nfunction filter_comment_form_defaults( $defaults ) {\n\n $defaults['comment_field'] = sprintf(\n '<p class=\"comment-form-comment\">%s %s</p>',\n sprintf(\n '<label for=\"comment\">%s</label>',\n _x( 'Please leave a comment...', 'Comment field label', 'textdomain' )\n ),\n '<textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" maxlength=\"65525\" required=\"required\"></textarea>'\n );\n\n return $defaults;\n} \n</code></pre>\n\n<p>But your (parent) theme might also make some modifications to the fields so the default values might get overwritten. So just keep scrolling down and you'll eventually see <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_fields/\" rel=\"nofollow noreferrer\"><code>comment_form_fields</code></a> filter. This filters the comment form fields, including the textarea.</p>\n\n<pre><code>add_filter( 'comment_form_fields', 'filter_comment_form_fields' );\nfunction filter_comment_form_fields( $fields ) {\n\n $fields['comment'] = sprintf(\n '<p class=\"comment-form-comment\">%s %s</p>',\n sprintf(\n '<label for=\"comment\">%s</label>',\n _x( 'Please leave a comment...', 'Comment field label', 'textdomain' )\n ),\n '<textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" maxlength=\"65525\" required=\"required\"></textarea>'\n );\n\n return $fields;\n} \n</code></pre>\n\n<p>If you only want to target the comment field, then below the previous filter, you can see in a foreach loop the <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_field_comment/\" rel=\"nofollow noreferrer\"><code>comment_form_field_comment</code></a> filter.</p>\n\n<pre><code>add_filter( 'comment_form_field_comment', 'filter_comment_form_field_comment' );\nfunction filter_comment_form_field_comment( $field ) {\n\n return sprintf(\n '<p class=\"comment-form-comment\">%s %s</p>',\n sprintf(\n '<label for=\"comment\">%s</label>',\n _x( 'Please leave a comment...', 'Comment field label', 'textdomain' )\n ),\n '<textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" maxlength=\"65525\" required=\"required\"></textarea>'\n );\n\n} \n</code></pre>\n\n<p>Please refer to the WP code reference (links) for more details about the filters.</p>\n"
},
{
"answer_id": 366149,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, You can customize the comment form without affecting the core file.</p>\n\n<p>You just need to replace the code of comment form with the below code inside the comments.php in the activated theme.</p>\n\n<pre><code>$args = array(\n 'comment_field' => '<p class=\"comment-form-comment\"><label for=\"comment\">' . _x( 'Please leave a comment...', 'noun' ) . '</label><textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" aria-required=\"true\"></textarea></p>'\n 'fields' => apply_filters( 'comment_form_default_fields', array(\n\n 'author' =>\n '<p class=\"comment-form-author\">' .\n '<label for=\"author\">' . __( 'Name', 'domainreference' ) . '</label> ' .\n ( $req ? '<span class=\"required\">*</span>' : '' ) .\n '<input id=\"author\" name=\"author\" type=\"text\" value=\"' . esc_attr( $commenter['comment_author'] ) .\n '\" size=\"30\"' . $aria_req . ' /></p>',\n\n 'email' =>\n '<p class=\"comment-form-email\"><label for=\"email\">' . __( 'Email', 'domainreference' ) . '</label> ' .\n ( $req ? '<span class=\"required\">*</span>' : '' ) .\n '<input id=\"email\" name=\"email\" type=\"text\" value=\"' . esc_attr( $commenter['comment_author_email'] ) .\n '\" size=\"30\"' . $aria_req . ' /></p>',\n\n 'url' =>\n '<p class=\"comment-form-url\"><label for=\"url\">' .\n __( 'Website', 'domainreference' ) . '</label>' .\n '<input id=\"url\" name=\"url\" type=\"text\" value=\"' . esc_attr( $commenter['comment_author_url'] ) .\n '\" size=\"30\" /></p>'\n )\n\n);\ncomment_form( $args );\n</code></pre>\n"
}
] | 2020/05/07 | [
"https://wordpress.stackexchange.com/questions/366033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185417/"
] | How do I change a parameter/text that are specified in the core without editing the core?
For example, this is a part of of comment-template.php from the wp-includes directory:
```
$fields = apply_filters( 'comment_form_default_fields', $fields );
$defaults = array(
'fields' => $fields,
'comment_field' => sprintf(
'<p class="comment-form-comment">%s %s</p>',
sprintf(
'<label for="comment">%s</label>',
_x( 'Comment', 'noun' )
),
'<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
),
```
That's a part of the thingie that displays the comment form, and writes the word "**Comment**" above the text field.
Now, if I want to change the word **Comment** to **Please leave a comment...**, How do I do it?
I understand that some kind of hook need to be used and placed in the functions.php file, but there ends my knowledge, and just change the core file is a big NO-NO!
Edit:
On line 2433 (wp 5.4.2)
```
'title_reply' => __( 'Leave a Reply' ),
```
I just changed it to;
```
'title_reply
' => __( '' ),
```
I just don't want to show it..
Line 2441
```
'label_submit' => __( 'Post Comment' ),
```
changed it to:
```
'label_submit' => __( ' Submit your thoughts...' ),
```
And finally (almost), line 2531
```
echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity );
```
Changed it to
```
echo apply_filters( 'comment_form_logged_in', '' );
```
Don't want to display this either..
And on line 2420
```
sprintf(
'<span id="email-notes">%s</span>',
__( 'Your email address will not be published.' )
),
```
That one I don't want to be shown at all..
That's how I previously has changed the core comment-temple.php file.
How do I do it in the functions.php
(It will affect pages like: <https://rainbowpets.org/rasmus/> ) | If you scroll further down the comment-template.php file, you'll notice that the next available filter you can use is [`comment_form_defaults`](https://developer.wordpress.org/reference/hooks/comment_form_defaults/). With this filter you can change the default comment form configuration.
```
add_filter( 'comment_form_defaults', 'filter_comment_form_defaults' );
function filter_comment_form_defaults( $defaults ) {
$defaults['comment_field'] = sprintf(
'<p class="comment-form-comment">%s %s</p>',
sprintf(
'<label for="comment">%s</label>',
_x( 'Please leave a comment...', 'Comment field label', 'textdomain' )
),
'<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
);
return $defaults;
}
```
But your (parent) theme might also make some modifications to the fields so the default values might get overwritten. So just keep scrolling down and you'll eventually see [`comment_form_fields`](https://developer.wordpress.org/reference/hooks/comment_form_fields/) filter. This filters the comment form fields, including the textarea.
```
add_filter( 'comment_form_fields', 'filter_comment_form_fields' );
function filter_comment_form_fields( $fields ) {
$fields['comment'] = sprintf(
'<p class="comment-form-comment">%s %s</p>',
sprintf(
'<label for="comment">%s</label>',
_x( 'Please leave a comment...', 'Comment field label', 'textdomain' )
),
'<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
);
return $fields;
}
```
If you only want to target the comment field, then below the previous filter, you can see in a foreach loop the [`comment_form_field_comment`](https://developer.wordpress.org/reference/hooks/comment_form_field_comment/) filter.
```
add_filter( 'comment_form_field_comment', 'filter_comment_form_field_comment' );
function filter_comment_form_field_comment( $field ) {
return sprintf(
'<p class="comment-form-comment">%s %s</p>',
sprintf(
'<label for="comment">%s</label>',
_x( 'Please leave a comment...', 'Comment field label', 'textdomain' )
),
'<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
);
}
```
Please refer to the WP code reference (links) for more details about the filters. |
366,037 | <p>i'm working on a music plugin.</p>
<p>It uses a custom table <em>tracklist_items</em> to store every tracks of a playlist; which has a structure like this :</p>
<pre><code>|id| |track_id| |tracklist_id| |order| |time|
</code></pre>
<p>So if I want to count the total tracks of a tracklist, I have this function :</p>
<pre><code>function get_subtracks_count(){
global $wpdb;
if (!$this->post_id) return false;
$querystr = $wpdb->prepare( "SELECT COUNT(*) FROM `tracklist_items` WHERE tracklist_id = %d", $this->post_id );
return $wpdb->get_var($querystr);
}
</code></pre>
<p>But now, I would like to be able to <strong>sort</strong> the tracklists by tracks count when doing a query.</p>
<p>How should I achieve that ?</p>
<p>+: I see that people usually sort that kind of stuff using meta values. This query above is fairly simple so I guess it fast. But shouldl I consider rather storing a meta value attached to the tracklist every time I add or remove a track to a tracklist (a process that seems more complex to me thus that I would like to avoid)</p>
<p>Thanks</p>
| [
{
"answer_id": 366039,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>function get_subtracks_count(){\n global $wpdb;\n if (!$this->post_id) return false;\n $querystr = $wpdb->prepare( \"SELECT COUNT(*) FROM `tracklist_items` WHERE tracklist_id = %d\", $this->post_id ORDER BY count(*) DESC);\n return $wpdb->get_var($querystr);\n}\n</code></pre>\n"
},
{
"answer_id": 366322,
"author": "vguerrero",
"author_id": 56470,
"author_profile": "https://wordpress.stackexchange.com/users/56470",
"pm_score": 3,
"selected": true,
"text": "<p>The way to go is apply custom filters to the <code>WP_Query</code> you are running.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('posts_clauses', function ($clauses, $query) {\n global $wpdb;\n\n // only run the filter for a given query\n // do your checks and return early\n if (!$query->is_main_query() || !$query->is_post_type_archive('tracklist')) {\n return $clauses;\n }\n\n $clauses['fields'] .= \", COUNT(items.id) AS track_count\";\n $clauses['join'] .= \" LEFT JOIN tracklist_items AS items ON {$wpdb->posts}.ID = items.tracklist_id\";\n $clauses['groupby'] = \"{$wpdb->posts}.ID\";\n $clauses['orderby'] = \"track_count DESC\";\n\n return $clauses;\n}, 2, 10);\n</code></pre>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/20119901/counting-number-of-joined-rows-in-left-join\">https://stackoverflow.com/questions/20119901/counting-number-of-joined-rows-in-left-join</a></p>\n"
}
] | 2020/05/07 | [
"https://wordpress.stackexchange.com/questions/366037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70449/"
] | i'm working on a music plugin.
It uses a custom table *tracklist\_items* to store every tracks of a playlist; which has a structure like this :
```
|id| |track_id| |tracklist_id| |order| |time|
```
So if I want to count the total tracks of a tracklist, I have this function :
```
function get_subtracks_count(){
global $wpdb;
if (!$this->post_id) return false;
$querystr = $wpdb->prepare( "SELECT COUNT(*) FROM `tracklist_items` WHERE tracklist_id = %d", $this->post_id );
return $wpdb->get_var($querystr);
}
```
But now, I would like to be able to **sort** the tracklists by tracks count when doing a query.
How should I achieve that ?
+: I see that people usually sort that kind of stuff using meta values. This query above is fairly simple so I guess it fast. But shouldl I consider rather storing a meta value attached to the tracklist every time I add or remove a track to a tracklist (a process that seems more complex to me thus that I would like to avoid)
Thanks | The way to go is apply custom filters to the `WP_Query` you are running.
```php
add_filter('posts_clauses', function ($clauses, $query) {
global $wpdb;
// only run the filter for a given query
// do your checks and return early
if (!$query->is_main_query() || !$query->is_post_type_archive('tracklist')) {
return $clauses;
}
$clauses['fields'] .= ", COUNT(items.id) AS track_count";
$clauses['join'] .= " LEFT JOIN tracklist_items AS items ON {$wpdb->posts}.ID = items.tracklist_id";
$clauses['groupby'] = "{$wpdb->posts}.ID";
$clauses['orderby'] = "track_count DESC";
return $clauses;
}, 2, 10);
```
See also <https://stackoverflow.com/questions/20119901/counting-number-of-joined-rows-in-left-join> |
366,046 | <p>When I use Advanced Custom Fields I can return the full image array of an upload. Is there a native WordPress way to get the full image array for any image in the Media Library by image ID? I can find ways to get the alt text and a specific image size, but not the array itself... </p>
| [
{
"answer_id": 366051,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>The \"full array\" is constructed by Advanced Custom Fields from various sources. It's not a format that occurs natively in WordPress.</p>\n\n<p>If you want to output an image tag for an image with all the correct attributes, just use the ID with <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_image()</code></a>. That returns an HTML <code><img></code> tag with the <code>src</code>, <code>width</code>, <code>height</code>, <code>alt</code>, <code>srcset</code>, <code>sizes</code> and <code>class</code> all populated. You can add or change attributes to the tag using the 4th argument:</p>\n\n<pre><code>echo wp_get_attachment_image(\n $attachment_id,\n 'large',\n false\n [\n 'class' => 'custom-class',\n 'data-attribute' => 'custom-attribute-value',\n ]\n);\n</code></pre>\n\n<p>To be honest, if your goal is to ultimately get an <code><img></code> tag, then even with ACF you should return an ID and use this function.</p>\n"
},
{
"answer_id": 384430,
"author": "Chaser",
"author_id": 198849,
"author_profile": "https://wordpress.stackexchange.com/users/198849",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using Autoload/Composer you can use <code>$image = \\acf_get_attachment( $attachment_id );</code> to get an acf image array. If not I guess you can use <code>require_once()</code> to load your <code>plugins/advanced-custom-fields-pro/includes/api/api-helpers.php</code>, however I haven't tested this yet.</p>\n"
}
] | 2020/05/07 | [
"https://wordpress.stackexchange.com/questions/366046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121694/"
] | When I use Advanced Custom Fields I can return the full image array of an upload. Is there a native WordPress way to get the full image array for any image in the Media Library by image ID? I can find ways to get the alt text and a specific image size, but not the array itself... | The "full array" is constructed by Advanced Custom Fields from various sources. It's not a format that occurs natively in WordPress.
If you want to output an image tag for an image with all the correct attributes, just use the ID with [`wp_get_attachment_image()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image/). That returns an HTML `<img>` tag with the `src`, `width`, `height`, `alt`, `srcset`, `sizes` and `class` all populated. You can add or change attributes to the tag using the 4th argument:
```
echo wp_get_attachment_image(
$attachment_id,
'large',
false
[
'class' => 'custom-class',
'data-attribute' => 'custom-attribute-value',
]
);
```
To be honest, if your goal is to ultimately get an `<img>` tag, then even with ACF you should return an ID and use this function. |
366,055 | <p>Is there any hook for when any plugin update is found to trigger a mail using PHP?
I found reference to upgrader_process_complete hook, but that is called after plugins are updated and not before.</p>
<p>Also, how can I fetch the list of plugins which have updates pending at a given time?</p>
| [
{
"answer_id": 366067,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": false,
"text": "<p>The relevant code is <a href=\"https://github.com/WordPress/WordPress/blob/5.4.1/wp-includes/update.php#L258\" rel=\"nofollow noreferrer\">wp_update_plugins()</a>. You can see that it stores its state in a site transient called 'update_plugins':</p>\n\n<pre><code>set_site_transient( 'update_plugins', $new_option );\n</code></pre>\n\n<p>and <a href=\"https://github.com/WordPress/WordPress/blob/5.4.1/wp-includes/option.php#L1820\" rel=\"nofollow noreferrer\">we can hook that</a>:</p>\n\n<ul>\n<li>pre_set_site_transient_update_plugins - called at the start of set_site_transient()</li>\n<li>set_site_transient_update_plugins - called at the end, if the value was changed</li>\n</ul>\n\n<p>Note that</p>\n\n<ul>\n<li><code>set_site_transient( 'update_plugins', ... )</code> is called twice as part of the update: once to update the last_checked timestamp, and once with the new-plugins-to-update list; the first call will always therefore have a changed value without necessarily having the list of updated plugins changed</li>\n<li>it can also be called when deleting plugins, to remove the update flag for any deleted plugin, but only once in this case.</li>\n</ul>\n\n<p>I appreciate that hooking the site transient updates seems a bit of a hack, but there's no other obvious place to hook that the update check is complete. I have seen pay-for plugins hook these too as a way of generating update-needed for plugins hosted elsewhere.</p>\n\n<hr>\n\n<p>Alternatively of course you don't need to hook the actual update, but you can instead schedule a cron job that checks <code>get_site_transient( 'update_plugins' )</code> (and <code>update_themes</code> and <code>update_core</code>) to generate the notification email.</p>\n"
},
{
"answer_id": 366073,
"author": "jasper_prikr",
"author_id": 172271,
"author_profile": "https://wordpress.stackexchange.com/users/172271",
"pm_score": 0,
"selected": false,
"text": "<p>With the answer of Rup, you can create a simple mail with the wp_mail function.</p>\n\n<p>It would look like this:</p>\n\n<pre><code> wp_mail( get_bloginfo( 'admin_email' ), 'Subject title here', 'Text for mail here'); \n</code></pre>\n\n<p>With <code>get_bloginfo( 'admin_email' )</code> you'll retrieve the admin's email you filled in during installation.</p>\n"
}
] | 2020/05/07 | [
"https://wordpress.stackexchange.com/questions/366055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143161/"
] | Is there any hook for when any plugin update is found to trigger a mail using PHP?
I found reference to upgrader\_process\_complete hook, but that is called after plugins are updated and not before.
Also, how can I fetch the list of plugins which have updates pending at a given time? | The relevant code is [wp\_update\_plugins()](https://github.com/WordPress/WordPress/blob/5.4.1/wp-includes/update.php#L258). You can see that it stores its state in a site transient called 'update\_plugins':
```
set_site_transient( 'update_plugins', $new_option );
```
and [we can hook that](https://github.com/WordPress/WordPress/blob/5.4.1/wp-includes/option.php#L1820):
* pre\_set\_site\_transient\_update\_plugins - called at the start of set\_site\_transient()
* set\_site\_transient\_update\_plugins - called at the end, if the value was changed
Note that
* `set_site_transient( 'update_plugins', ... )` is called twice as part of the update: once to update the last\_checked timestamp, and once with the new-plugins-to-update list; the first call will always therefore have a changed value without necessarily having the list of updated plugins changed
* it can also be called when deleting plugins, to remove the update flag for any deleted plugin, but only once in this case.
I appreciate that hooking the site transient updates seems a bit of a hack, but there's no other obvious place to hook that the update check is complete. I have seen pay-for plugins hook these too as a way of generating update-needed for plugins hosted elsewhere.
---
Alternatively of course you don't need to hook the actual update, but you can instead schedule a cron job that checks `get_site_transient( 'update_plugins' )` (and `update_themes` and `update_core`) to generate the notification email. |
366,118 | <p>I am adding a "Conversations" endpoint so that it appears in my account in woocommerce</p>
<pre><code>add_action( 'init', array($this, 'custom_endpoints') );
function custom_endpoints() {
add_rewrite_endpoint( 'conversations', EP_PERMALINK | EP_PAGES );
}
</code></pre>
<p>It will work just fine with a "plain" permalink structure, but with a post name structure the link in my account goes to <code>my-account/conversations.</code>That says "page not found". However <code>my-account/?conversations</code> does work. </p>
<p>What's causing this?</p>
<p>This is the code for the WooCommerce menu items:</p>
<pre><code>add_filter( 'woocommerce_account_menu_items', array($this, 'custom_items'), 10, 1 );
function custom_items( $items ) {
$items = array_slice($items, 0, 2, true) +
array("conversations" => esc_html__( 'Conversations', 'domain' )) +
array_slice($items, 2, count($items)-2, true);
return $items;
}
</code></pre>
| [
{
"answer_id": 366120,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>I would avoid using <code>add_rewrite_endpoint()</code> directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to <code>is_wc_endpoint_url()</code>.</p>\n\n<p>So add the endpoint with the <code>woocommerce_get_query_vars</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_get_query_vars',\n function( $query_vars ) {\n $query_vars['conversations'] = 'conversations';\n\n return $query_vars;\n }\n);\n</code></pre>\n\n<p>Note that unlike the <code>query_vars</code> filter, you need to use a key when adding to the array.</p>\n\n<p>Now you can set the page contents with the <code>woocommerce_account_conversations_endpoint</code> hook:</p>\n\n<pre><code>add_action(\n 'woocommerce_account_conversations_endpoint',\n function() {\n // Page content here.\n }\n);\n</code></pre>\n\n<p>And the title with the <code>woocommerce_endpoint_conversations_title</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_endpoint_conversations_title',\n function( $title ) {\n $title = 'Conversations';\n\n return $title;\n }\n);\n</code></pre>\n\n<p>And you can continue adding it to the account menu the way you are.</p>\n"
},
{
"answer_id": 366228,
"author": "Stefan S",
"author_id": 184978,
"author_profile": "https://wordpress.stackexchange.com/users/184978",
"pm_score": 0,
"selected": false,
"text": "<p>I figured it out. Even if I was saving permalinks, that wasn't actually flushing the rewrite rules.</p>\n\n<p>I was flushing rewrite rules on activation but I was doing it incorrectly.</p>\n\n<p>If you are adding custom endpoints, you need to call the function that adds the custom endpoint in the activation file, before the flush_rewrite_rules() call.</p>\n\n<p>This is in my activation function now and it works:</p>\n\n<pre><code>require_once ( PLUGIN_DIR . 'public/class-plugin-public.php' );\n\n $publicobj = new Plugin_Public;\n $publicobj->custom_endpoints();\n\n // Flush rewrite rules\n flush_rewrite_rules();\n</code></pre>\n\n<p>Now I'm instantiating the public class and calling the endpoints() method in the activation, before the rules flush.</p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184978/"
] | I am adding a "Conversations" endpoint so that it appears in my account in woocommerce
```
add_action( 'init', array($this, 'custom_endpoints') );
function custom_endpoints() {
add_rewrite_endpoint( 'conversations', EP_PERMALINK | EP_PAGES );
}
```
It will work just fine with a "plain" permalink structure, but with a post name structure the link in my account goes to `my-account/conversations.`That says "page not found". However `my-account/?conversations` does work.
What's causing this?
This is the code for the WooCommerce menu items:
```
add_filter( 'woocommerce_account_menu_items', array($this, 'custom_items'), 10, 1 );
function custom_items( $items ) {
$items = array_slice($items, 0, 2, true) +
array("conversations" => esc_html__( 'Conversations', 'domain' )) +
array_slice($items, 2, count($items)-2, true);
return $items;
}
``` | I would avoid using `add_rewrite_endpoint()` directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to `is_wc_endpoint_url()`.
So add the endpoint with the `woocommerce_get_query_vars` filter:
```
add_filter(
'woocommerce_get_query_vars',
function( $query_vars ) {
$query_vars['conversations'] = 'conversations';
return $query_vars;
}
);
```
Note that unlike the `query_vars` filter, you need to use a key when adding to the array.
Now you can set the page contents with the `woocommerce_account_conversations_endpoint` hook:
```
add_action(
'woocommerce_account_conversations_endpoint',
function() {
// Page content here.
}
);
```
And the title with the `woocommerce_endpoint_conversations_title` filter:
```
add_filter(
'woocommerce_endpoint_conversations_title',
function( $title ) {
$title = 'Conversations';
return $title;
}
);
```
And you can continue adding it to the account menu the way you are. |
366,125 | <p>I created an installation of my multisite ecommerce to differentiate the men's and women's departments. Often, however, it happens that in the men's department they do research related to women's articles or vice versa. Consequently, my site says it cannot find an article, obviously it is not so.
How can I implement a global search function? I tried with switch_to_blog on this function that I paste, unfortunately I can't make it go. Could anyone help me out?
This is code i tried...but DIE does it stop and work only on site 1...any ideas?
Thanks in advance</p>
<pre><code> switch_to_blog(1);
$results = new WP_Query( apply_filters( 'basel_ajax_search_args', $query_args ) );
if ( basel_get_opt( 'relevanssi_search' ) && function_exists( 'relevanssi_do_query' ) ) {
relevanssi_do_query( $results );
}
$suggestions = array();
if ( $results->have_posts() ) {
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$factory = new WC_Product_Factory();
}
while ( $results->have_posts() ) {
$results->the_post();
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$product = $factory->get_product( get_the_ID() );
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'price' => $product->get_price_html(),
'thumbnail' => $product->get_image(),
'sku' => $product->get_sku() ? esc_html__( 'SKU:', 'basel' ) . ' ' . $product->get_sku() : '',
);
} else {
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail( null, 'medium', '' ),
);
}
}
wp_reset_postdata();
restore_current_blog();
} else {
$suggestions[] = array(
'value' => ( $post_type == 'product' ) ? esc_html__( 'No products found', 'basel' ) : esc_html__( 'No posts found', 'basel' ),
'no_found' => true,
'permalink' => ''
);
}
switch_to_blog(2);
$results = new WP_Query( apply_filters( 'basel_ajax_search_args', $query_args ) );
if ( basel_get_opt( 'relevanssi_search' ) && function_exists( 'relevanssi_do_query' ) ) {
relevanssi_do_query( $results );
}
//$suggestions = array();
if ( $results->have_posts() ) {
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$factory = new WC_Product_Factory();
}
while ( $results->have_posts() ) {
$results->the_post();
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$product = $factory->get_product( get_the_ID() );
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'price' => $product->get_price_html(),
'thumbnail' => $product->get_image(),
'sku' => $product->get_sku() ? esc_html__( 'SKU:', 'basel' ) . ' ' . $product->get_sku() : '',
);
} else {
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail( null, 'medium', '' ),
);
}
}
wp_reset_postdata();
restore_current_blog();
} else {
$suggestions[] = array(
'value' => ( $post_type == 'product' ) ? esc_html__( 'No products found', 'basel' ) : esc_html__( 'No posts found', 'basel' ),
'no_found' => true,
'permalink' => ''
);
}
//$my_array2 = array('suggestions' => $suggestions);
//$my_array1 = array('suggestions' => $suggestions1);
//$res = array_merge($my_array2, $my_array1);
// echo json_encode($res);
echo json_encode(array('suggestions' => $suggestions));
die();
}
</code></pre>
| [
{
"answer_id": 366120,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>I would avoid using <code>add_rewrite_endpoint()</code> directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to <code>is_wc_endpoint_url()</code>.</p>\n\n<p>So add the endpoint with the <code>woocommerce_get_query_vars</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_get_query_vars',\n function( $query_vars ) {\n $query_vars['conversations'] = 'conversations';\n\n return $query_vars;\n }\n);\n</code></pre>\n\n<p>Note that unlike the <code>query_vars</code> filter, you need to use a key when adding to the array.</p>\n\n<p>Now you can set the page contents with the <code>woocommerce_account_conversations_endpoint</code> hook:</p>\n\n<pre><code>add_action(\n 'woocommerce_account_conversations_endpoint',\n function() {\n // Page content here.\n }\n);\n</code></pre>\n\n<p>And the title with the <code>woocommerce_endpoint_conversations_title</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_endpoint_conversations_title',\n function( $title ) {\n $title = 'Conversations';\n\n return $title;\n }\n);\n</code></pre>\n\n<p>And you can continue adding it to the account menu the way you are.</p>\n"
},
{
"answer_id": 366228,
"author": "Stefan S",
"author_id": 184978,
"author_profile": "https://wordpress.stackexchange.com/users/184978",
"pm_score": 0,
"selected": false,
"text": "<p>I figured it out. Even if I was saving permalinks, that wasn't actually flushing the rewrite rules.</p>\n\n<p>I was flushing rewrite rules on activation but I was doing it incorrectly.</p>\n\n<p>If you are adding custom endpoints, you need to call the function that adds the custom endpoint in the activation file, before the flush_rewrite_rules() call.</p>\n\n<p>This is in my activation function now and it works:</p>\n\n<pre><code>require_once ( PLUGIN_DIR . 'public/class-plugin-public.php' );\n\n $publicobj = new Plugin_Public;\n $publicobj->custom_endpoints();\n\n // Flush rewrite rules\n flush_rewrite_rules();\n</code></pre>\n\n<p>Now I'm instantiating the public class and calling the endpoints() method in the activation, before the rules flush.</p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167366/"
] | I created an installation of my multisite ecommerce to differentiate the men's and women's departments. Often, however, it happens that in the men's department they do research related to women's articles or vice versa. Consequently, my site says it cannot find an article, obviously it is not so.
How can I implement a global search function? I tried with switch\_to\_blog on this function that I paste, unfortunately I can't make it go. Could anyone help me out?
This is code i tried...but DIE does it stop and work only on site 1...any ideas?
Thanks in advance
```
switch_to_blog(1);
$results = new WP_Query( apply_filters( 'basel_ajax_search_args', $query_args ) );
if ( basel_get_opt( 'relevanssi_search' ) && function_exists( 'relevanssi_do_query' ) ) {
relevanssi_do_query( $results );
}
$suggestions = array();
if ( $results->have_posts() ) {
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$factory = new WC_Product_Factory();
}
while ( $results->have_posts() ) {
$results->the_post();
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$product = $factory->get_product( get_the_ID() );
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'price' => $product->get_price_html(),
'thumbnail' => $product->get_image(),
'sku' => $product->get_sku() ? esc_html__( 'SKU:', 'basel' ) . ' ' . $product->get_sku() : '',
);
} else {
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail( null, 'medium', '' ),
);
}
}
wp_reset_postdata();
restore_current_blog();
} else {
$suggestions[] = array(
'value' => ( $post_type == 'product' ) ? esc_html__( 'No products found', 'basel' ) : esc_html__( 'No posts found', 'basel' ),
'no_found' => true,
'permalink' => ''
);
}
switch_to_blog(2);
$results = new WP_Query( apply_filters( 'basel_ajax_search_args', $query_args ) );
if ( basel_get_opt( 'relevanssi_search' ) && function_exists( 'relevanssi_do_query' ) ) {
relevanssi_do_query( $results );
}
//$suggestions = array();
if ( $results->have_posts() ) {
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$factory = new WC_Product_Factory();
}
while ( $results->have_posts() ) {
$results->the_post();
if ( $post_type == 'product' && basel_woocommerce_installed() ) {
$product = $factory->get_product( get_the_ID() );
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'price' => $product->get_price_html(),
'thumbnail' => $product->get_image(),
'sku' => $product->get_sku() ? esc_html__( 'SKU:', 'basel' ) . ' ' . $product->get_sku() : '',
);
} else {
$suggestions[] = array(
'value' => get_the_title(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail( null, 'medium', '' ),
);
}
}
wp_reset_postdata();
restore_current_blog();
} else {
$suggestions[] = array(
'value' => ( $post_type == 'product' ) ? esc_html__( 'No products found', 'basel' ) : esc_html__( 'No posts found', 'basel' ),
'no_found' => true,
'permalink' => ''
);
}
//$my_array2 = array('suggestions' => $suggestions);
//$my_array1 = array('suggestions' => $suggestions1);
//$res = array_merge($my_array2, $my_array1);
// echo json_encode($res);
echo json_encode(array('suggestions' => $suggestions));
die();
}
``` | I would avoid using `add_rewrite_endpoint()` directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to `is_wc_endpoint_url()`.
So add the endpoint with the `woocommerce_get_query_vars` filter:
```
add_filter(
'woocommerce_get_query_vars',
function( $query_vars ) {
$query_vars['conversations'] = 'conversations';
return $query_vars;
}
);
```
Note that unlike the `query_vars` filter, you need to use a key when adding to the array.
Now you can set the page contents with the `woocommerce_account_conversations_endpoint` hook:
```
add_action(
'woocommerce_account_conversations_endpoint',
function() {
// Page content here.
}
);
```
And the title with the `woocommerce_endpoint_conversations_title` filter:
```
add_filter(
'woocommerce_endpoint_conversations_title',
function( $title ) {
$title = 'Conversations';
return $title;
}
);
```
And you can continue adding it to the account menu the way you are. |
366,142 | <p>Is there any filter or hook to print a script or add in the footer some content? I'm not talking about <code>wp_enqueue_</code> function, I'm creating a plugin that will show a banner for privacy and cookie info and I want to append it to the footer. I'm using at the moment this code, but I hope that there is a more clean wey to do it:</p>
<pre><code>
function cookie_privacy_script()
{
<script>
// js code here
</script>
}
add_action('wp_enqueue_scripts', 'cookie_privacy_script');
</code></pre>
| [
{
"answer_id": 366120,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>I would avoid using <code>add_rewrite_endpoint()</code> directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to <code>is_wc_endpoint_url()</code>.</p>\n\n<p>So add the endpoint with the <code>woocommerce_get_query_vars</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_get_query_vars',\n function( $query_vars ) {\n $query_vars['conversations'] = 'conversations';\n\n return $query_vars;\n }\n);\n</code></pre>\n\n<p>Note that unlike the <code>query_vars</code> filter, you need to use a key when adding to the array.</p>\n\n<p>Now you can set the page contents with the <code>woocommerce_account_conversations_endpoint</code> hook:</p>\n\n<pre><code>add_action(\n 'woocommerce_account_conversations_endpoint',\n function() {\n // Page content here.\n }\n);\n</code></pre>\n\n<p>And the title with the <code>woocommerce_endpoint_conversations_title</code> filter:</p>\n\n<pre><code>add_filter(\n 'woocommerce_endpoint_conversations_title',\n function( $title ) {\n $title = 'Conversations';\n\n return $title;\n }\n);\n</code></pre>\n\n<p>And you can continue adding it to the account menu the way you are.</p>\n"
},
{
"answer_id": 366228,
"author": "Stefan S",
"author_id": 184978,
"author_profile": "https://wordpress.stackexchange.com/users/184978",
"pm_score": 0,
"selected": false,
"text": "<p>I figured it out. Even if I was saving permalinks, that wasn't actually flushing the rewrite rules.</p>\n\n<p>I was flushing rewrite rules on activation but I was doing it incorrectly.</p>\n\n<p>If you are adding custom endpoints, you need to call the function that adds the custom endpoint in the activation file, before the flush_rewrite_rules() call.</p>\n\n<p>This is in my activation function now and it works:</p>\n\n<pre><code>require_once ( PLUGIN_DIR . 'public/class-plugin-public.php' );\n\n $publicobj = new Plugin_Public;\n $publicobj->custom_endpoints();\n\n // Flush rewrite rules\n flush_rewrite_rules();\n</code></pre>\n\n<p>Now I'm instantiating the public class and calling the endpoints() method in the activation, before the rules flush.</p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366142",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177581/"
] | Is there any filter or hook to print a script or add in the footer some content? I'm not talking about `wp_enqueue_` function, I'm creating a plugin that will show a banner for privacy and cookie info and I want to append it to the footer. I'm using at the moment this code, but I hope that there is a more clean wey to do it:
```
function cookie_privacy_script()
{
<script>
// js code here
</script>
}
add_action('wp_enqueue_scripts', 'cookie_privacy_script');
``` | I would avoid using `add_rewrite_endpoint()` directly to register account page endpoints in WooCommerce. WooCommerce has a filter that you can use that make sure everything else works properly, like the endpoint title filter and calls to `is_wc_endpoint_url()`.
So add the endpoint with the `woocommerce_get_query_vars` filter:
```
add_filter(
'woocommerce_get_query_vars',
function( $query_vars ) {
$query_vars['conversations'] = 'conversations';
return $query_vars;
}
);
```
Note that unlike the `query_vars` filter, you need to use a key when adding to the array.
Now you can set the page contents with the `woocommerce_account_conversations_endpoint` hook:
```
add_action(
'woocommerce_account_conversations_endpoint',
function() {
// Page content here.
}
);
```
And the title with the `woocommerce_endpoint_conversations_title` filter:
```
add_filter(
'woocommerce_endpoint_conversations_title',
function( $title ) {
$title = 'Conversations';
return $title;
}
);
```
And you can continue adding it to the account menu the way you are. |
366,150 | <p>I am working with a child theme from 'Astra'. I am editing 'style.css' of my child theme for styling my website. I added this code to my child's functions.php' file to enqueue the father-child styles.</p>
<pre><code><?php
add_action('wp_enqueue_scripts', 'example_enqueue_styles');
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'astra';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
</code></pre>
<p>Although the browser is painting the styles of my child theme as I intend, it also happens to do it twice in different versions of the same code:</p>
<p><a href="https://i.stack.imgur.com/wI7iv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wI7iv.png" alt="snippet of the issue"></a></p>
<p>It causes styling issues with some elements. I believe the source of the problem is my enqueuing code but I don't know what it is.</p>
<p>Thank you.</p>
| [
{
"answer_id": 366152,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>Need to remove this first : add_action('wp_enqueue_scripts', 'example_enqueue_styles');</p>\n\n<p>And, please try this:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'astra'; \n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n"
},
{
"answer_id": 366154,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 1,
"selected": true,
"text": "<p>The problem comes from that the parent style is loaded twice : </p>\n\n<ol>\n<li>one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> ), </li>\n<li>another without (the second on your picture, called by your function php). </li>\n</ol>\n\n<p>To solve this : remove </p>\n\n<pre><code>wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n</code></pre>\n\n<p>As it is already loaded by your parent theme and described as a dependency of your child style. </p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163826/"
] | I am working with a child theme from 'Astra'. I am editing 'style.css' of my child theme for styling my website. I added this code to my child's functions.php' file to enqueue the father-child styles.
```
<?php
add_action('wp_enqueue_scripts', 'example_enqueue_styles');
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'astra';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
```
Although the browser is painting the styles of my child theme as I intend, it also happens to do it twice in different versions of the same code:
[](https://i.stack.imgur.com/wI7iv.png)
It causes styling issues with some elements. I believe the source of the problem is my enqueuing code but I don't know what it is.
Thank you. | The problem comes from that the parent style is loaded twice :
1. one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) ),
2. another without (the second on your picture, called by your function php).
To solve this : remove
```
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
```
As it is already loaded by your parent theme and described as a dependency of your child style. |
366,160 | <p>Basically I am struggling to display the author list in a grid: </p>
<pre><code><div class="container">
<div class="row">
<div class="col-lg-4">
<?php
wp_list_authors( array(
'show_fullname' => 1,
'optioncount' => 1,
'exclude' => 4,
'orderby' => 'post_count',
'order' => 'DESC',
'number' => 60
) ); ?>
</div>
</div>
</div>
</code></pre>
<p>Should I use the user table instead of is there a loop I can use against the author list?</p>
<p>Thank you</p>
| [
{
"answer_id": 366152,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>Need to remove this first : add_action('wp_enqueue_scripts', 'example_enqueue_styles');</p>\n\n<p>And, please try this:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'astra'; \n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n"
},
{
"answer_id": 366154,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 1,
"selected": true,
"text": "<p>The problem comes from that the parent style is loaded twice : </p>\n\n<ol>\n<li>one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> ), </li>\n<li>another without (the second on your picture, called by your function php). </li>\n</ol>\n\n<p>To solve this : remove </p>\n\n<pre><code>wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n</code></pre>\n\n<p>As it is already loaded by your parent theme and described as a dependency of your child style. </p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187686/"
] | Basically I am struggling to display the author list in a grid:
```
<div class="container">
<div class="row">
<div class="col-lg-4">
<?php
wp_list_authors( array(
'show_fullname' => 1,
'optioncount' => 1,
'exclude' => 4,
'orderby' => 'post_count',
'order' => 'DESC',
'number' => 60
) ); ?>
</div>
</div>
</div>
```
Should I use the user table instead of is there a loop I can use against the author list?
Thank you | The problem comes from that the parent style is loaded twice :
1. one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) ),
2. another without (the second on your picture, called by your function php).
To solve this : remove
```
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
```
As it is already loaded by your parent theme and described as a dependency of your child style. |
366,167 | <p>I have searched for lot of stuff but could not get any help.</p>
<p>I am new to WP.</p>
<p>I am working with the ‘DremeTheme – the7’ theme for the past 4 weeks. I have had set the front page since the beginning, but today my front page is not showing.</p>
<p>If I set any one of the pages as a front page, it does not work.
When I view other pages from Admin Dashboard using View Button it is showing contents but when I want to view my Home page, it is showing me blank screen, even If i set any other page as FrontPage or HomePage, it still display blank screen.
I am not getting why.</p>
<p>Ps:- the site is in under construction mode (i have used a plugin for that for the last 2 weeks). Today I also had a theme update, maybe that is the reason behind it.</p>
<p>Kindly help.
Any help will be appreciated.</p>
| [
{
"answer_id": 366152,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>Need to remove this first : add_action('wp_enqueue_scripts', 'example_enqueue_styles');</p>\n\n<p>And, please try this:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'astra'; \n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n"
},
{
"answer_id": 366154,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 1,
"selected": true,
"text": "<p>The problem comes from that the parent style is loaded twice : </p>\n\n<ol>\n<li>one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> ), </li>\n<li>another without (the second on your picture, called by your function php). </li>\n</ol>\n\n<p>To solve this : remove </p>\n\n<pre><code>wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n</code></pre>\n\n<p>As it is already loaded by your parent theme and described as a dependency of your child style. </p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187691/"
] | I have searched for lot of stuff but could not get any help.
I am new to WP.
I am working with the ‘DremeTheme – the7’ theme for the past 4 weeks. I have had set the front page since the beginning, but today my front page is not showing.
If I set any one of the pages as a front page, it does not work.
When I view other pages from Admin Dashboard using View Button it is showing contents but when I want to view my Home page, it is showing me blank screen, even If i set any other page as FrontPage or HomePage, it still display blank screen.
I am not getting why.
Ps:- the site is in under construction mode (i have used a plugin for that for the last 2 weeks). Today I also had a theme update, maybe that is the reason behind it.
Kindly help.
Any help will be appreciated. | The problem comes from that the parent style is loaded twice :
1. one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) ),
2. another without (the second on your picture, called by your function php).
To solve this : remove
```
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
```
As it is already loaded by your parent theme and described as a dependency of your child style. |
366,184 | <p>I've inherited a wordpress site using the Avada theme and page loads seems to be exceptionally slow, anywhere from seven seconds to 30 seconds. It looks to me like one or more of the queries are doing something very strange, since there's a long list in the slow query monitor.</p>
<p>It's WordPress 5.2.6 running Avada theme.</p>
<p>Here is an example of some of the query data:</p>
<p>UPDATE <code>wp_options</code>
SET <code>option_value</code> = 'a:8:{s:28:\"enable_builder_ui_by_default\";s:1:\"1\";s:15:\"fusion_elements\";a:40:{i:0;s:11:\"fusion_blog\";i:1;s:13:\"fusion_button\";i:2;s:11:\"fusion_code\";i:3;s:20:\"fusion_content_boxes\";i:4;s:13:\"fusion_events\";i:5;s:18:\"fusion_fontawesome\";i:6;s:14:\"fusion_gallery\";i:7;s:16:\"fusion_highlight\";i:8;s:17:\"fusion_imageframe\";i:9;s:25:\"fusion_</p>
<p>Then enormous amounts of this:</p>
<p>i:147662;s:20:\"fbmlg_mobile_layouts\";i:147663;s:20:\"fbmlg_mobile_layouts\";i:147664;s:20:\"fbmlg_mobile_layouts\";i:147665;s:20:\"fbmlg_mobile_layouts\";i:147666;s:20:\"fbmlg_mobile_layouts\";i:147667;s:20:\"fbmlg_mobile_layouts\";i:147668;s:20:\"fbmlg_mobile_layouts\";i:147669;s:20:\"fbmlg_mobile_layouts\";i:147670;s:20:\"fbmlg_mobile_layouts\";i:147671;s:20:\"fbmlg_mobile_layouts\";i:147672;s:20:\"fbmlg_mobile_layouts\";i:147673;s:20:\"fbmlg_mobile_layouts\";i:147674;s:20:\"fbmlg_mobile_layouts\";i:147675;s:20:\"fbmlg_mobile_layouts\";i:147676;s:20:\"fbmlg_mobile_layouts\";i:147677;</p>
<p>The incrementing number goes to 652628 and it says update_option() is calling Plugin: fusion-builder-mobile-layout-creator to create this query.</p>
<p>Any help appreciated.</p>
| [
{
"answer_id": 366152,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>Need to remove this first : add_action('wp_enqueue_scripts', 'example_enqueue_styles');</p>\n\n<p>And, please try this:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'astra'; \n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n"
},
{
"answer_id": 366154,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 1,
"selected": true,
"text": "<p>The problem comes from that the parent style is loaded twice : </p>\n\n<ol>\n<li>one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> ), </li>\n<li>another without (the second on your picture, called by your function php). </li>\n</ol>\n\n<p>To solve this : remove </p>\n\n<pre><code>wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n</code></pre>\n\n<p>As it is already loaded by your parent theme and described as a dependency of your child style. </p>\n"
}
] | 2020/05/08 | [
"https://wordpress.stackexchange.com/questions/366184",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187704/"
] | I've inherited a wordpress site using the Avada theme and page loads seems to be exceptionally slow, anywhere from seven seconds to 30 seconds. It looks to me like one or more of the queries are doing something very strange, since there's a long list in the slow query monitor.
It's WordPress 5.2.6 running Avada theme.
Here is an example of some of the query data:
UPDATE `wp_options`
SET `option_value` = 'a:8:{s:28:\"enable\_builder\_ui\_by\_default\";s:1:\"1\";s:15:\"fusion\_elements\";a:40:{i:0;s:11:\"fusion\_blog\";i:1;s:13:\"fusion\_button\";i:2;s:11:\"fusion\_code\";i:3;s:20:\"fusion\_content\_boxes\";i:4;s:13:\"fusion\_events\";i:5;s:18:\"fusion\_fontawesome\";i:6;s:14:\"fusion\_gallery\";i:7;s:16:\"fusion\_highlight\";i:8;s:17:\"fusion\_imageframe\";i:9;s:25:\"fusion\_
Then enormous amounts of this:
i:147662;s:20:\"fbmlg\_mobile\_layouts\";i:147663;s:20:\"fbmlg\_mobile\_layouts\";i:147664;s:20:\"fbmlg\_mobile\_layouts\";i:147665;s:20:\"fbmlg\_mobile\_layouts\";i:147666;s:20:\"fbmlg\_mobile\_layouts\";i:147667;s:20:\"fbmlg\_mobile\_layouts\";i:147668;s:20:\"fbmlg\_mobile\_layouts\";i:147669;s:20:\"fbmlg\_mobile\_layouts\";i:147670;s:20:\"fbmlg\_mobile\_layouts\";i:147671;s:20:\"fbmlg\_mobile\_layouts\";i:147672;s:20:\"fbmlg\_mobile\_layouts\";i:147673;s:20:\"fbmlg\_mobile\_layouts\";i:147674;s:20:\"fbmlg\_mobile\_layouts\";i:147675;s:20:\"fbmlg\_mobile\_layouts\";i:147676;s:20:\"fbmlg\_mobile\_layouts\";i:147677;
The incrementing number goes to 652628 and it says update\_option() is calling Plugin: fusion-builder-mobile-layout-creator to create this query.
Any help appreciated. | The problem comes from that the parent style is loaded twice :
1. one with version ('?ver=1.0 etc, first on your picture and loaded by your parent theme with versionning on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) ),
2. another without (the second on your picture, called by your function php).
To solve this : remove
```
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
```
As it is already loaded by your parent theme and described as a dependency of your child style. |
366,282 | <p>I wish to limit the possibility to use a specific template page only for post id x</p>
<p>I have created a page-blog.php template and I want it usable only for the post id 115 (id of my blog page).</p>
<p>Actually, in administration, all posts have the template on the models list native metabox, so perhaps we can limit or filter this models list ?</p>
<p>I checked this wordpress page but impossible to achieve my goal by using the slug method =>
<a href="https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-a-custom-page-template-for-one-specific-page" rel="nofollow noreferrer">https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-a-custom-page-template-for-one-specific-page</a></p>
<p>Thanks</p>
| [
{
"answer_id": 366284,
"author": "Himad",
"author_id": 158512,
"author_profile": "https://wordpress.stackexchange.com/users/158512",
"pm_score": 1,
"selected": false,
"text": "<pre><code>/**\n * Filters list of page templates for a theme.\n * @param string[] $post_templates Array of template header names keyed by the template file name.\n * @param WP_Theme $this The theme object.\n * @param WP_Post|null $post The post being edited, provided for context, or null.\n * @param string $post_type Post type to get the templates for.\n*/\n\nadd_filter('theme_templates', function($post_templates, $this, $post, $post_type){\n // Unless post is 115, filter your custom template from the dropdown.\n if(!empty($post) && $post->ID != '150'){\n return array_filter($post_templates, function($template_name){\n return $template_name !== 'your_template_name';\n });\n }\n return $post_templates;\n}, 20, 4);\n</code></pre>\n"
},
{
"answer_id": 366310,
"author": "WolwX",
"author_id": 187802,
"author_profile": "https://wordpress.stackexchange.com/users/187802",
"pm_score": 0,
"selected": false,
"text": "<p>I finally found a way to do it, based on the fact templates are stored as array (as Himad show me), we can filter this array and remove my template_name with array_diff php function =></p>\n\n<pre><code> function n1_filter_template_pageblog($post_templates, $this, $post, $post_type) {\n $template_tofiltrate = 'Blog';\n $postid_exception = '115';\n if(get_the_ID() != $postid_exception){\n return array_diff($post_templates, array($template_tofiltrate));\n }\n return $post_templates;\n }\n add_filter('theme_page_templates', 'n1_filter_template_pageblog', 10, 4);\n</code></pre>\n\n<p>This one worked fine for me, all page won't see the template named \"Blog\" excepted the page with postid 115.</p>\n"
}
] | 2020/05/10 | [
"https://wordpress.stackexchange.com/questions/366282",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187802/"
] | I wish to limit the possibility to use a specific template page only for post id x
I have created a page-blog.php template and I want it usable only for the post id 115 (id of my blog page).
Actually, in administration, all posts have the template on the models list native metabox, so perhaps we can limit or filter this models list ?
I checked this wordpress page but impossible to achieve my goal by using the slug method =>
<https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-a-custom-page-template-for-one-specific-page>
Thanks | ```
/**
* Filters list of page templates for a theme.
* @param string[] $post_templates Array of template header names keyed by the template file name.
* @param WP_Theme $this The theme object.
* @param WP_Post|null $post The post being edited, provided for context, or null.
* @param string $post_type Post type to get the templates for.
*/
add_filter('theme_templates', function($post_templates, $this, $post, $post_type){
// Unless post is 115, filter your custom template from the dropdown.
if(!empty($post) && $post->ID != '150'){
return array_filter($post_templates, function($template_name){
return $template_name !== 'your_template_name';
});
}
return $post_templates;
}, 20, 4);
``` |
366,371 | <p>I am using Wordpress and Buddypress and i am trying to remove or hide the username that is being displayed in the autocomplete field of messages in Buddypress. Tried some tests from <a href="https://buddypress.org/support/topic/autocomplete-shows-both-names/" rel="nofollow noreferrer">this</a> post and also <a href="https://buddypress.org/support/topic/hide-username-in-autocomplete-send-to/" rel="nofollow noreferrer">this</a> , but with no luck. Did someone run into this issue? </p>
<p>I was also looking around if i could just hide it with some css, but i think is not possible since the html is like that :</p>
<pre><code><li class="ac_event ac_over"><span id="link-username" href="#"></span>
<img src="https://www.test.com/wp-content/uploads/avatars/23/user-bpthumb.jpg" style="width: 15px"> &nbsp; User (<strong>U</strong>sername)</li>
</code></pre>
<p>and need to remove <code>(<strong>U</strong>sername)</code>
I have also tried to remove or add some html span inside the native bp code </p>
<pre><code>'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s (%s)' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name ),
esc_html( $user->ID )
</code></pre>
<p>but when i try to remove (%s) it just breaks the displayed result. </p>
| [
{
"answer_id": 366386,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 1,
"selected": false,
"text": "<p>Try this but note that it may not send the message:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ), \n ' '\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ) \n</code></pre>\n"
},
{
"answer_id": 366438,
"author": "Honoluluman",
"author_id": 129972,
"author_profile": "https://wordpress.stackexchange.com/users/129972",
"pm_score": 0,
"selected": false,
"text": "<p>So i managed to solve this problem with some CSS, unfortunately there is no possibility to wrap with any html element around <code>(%s)</code> , BUT there is possibility to wrap with html the rest. So i did this </p>\n\n<pre><code>printf( '<span id=\"keep\"><span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> &nbsp; %s</span> (%s)' . \"\\n\",\n</code></pre>\n\n<p>with out removing nothing from the original code, just adding the span 'keep' and then with the classic css <code>visibility:hidden;</code> <a href=\"https://stackoverflow.com/a/48591995/8827124\">trick</a> i managed to hide it simple.</p>\n"
}
] | 2020/05/11 | [
"https://wordpress.stackexchange.com/questions/366371",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129972/"
] | I am using Wordpress and Buddypress and i am trying to remove or hide the username that is being displayed in the autocomplete field of messages in Buddypress. Tried some tests from [this](https://buddypress.org/support/topic/autocomplete-shows-both-names/) post and also [this](https://buddypress.org/support/topic/hide-username-in-autocomplete-send-to/) , but with no luck. Did someone run into this issue?
I was also looking around if i could just hide it with some css, but i think is not possible since the html is like that :
```
<li class="ac_event ac_over"><span id="link-username" href="#"></span>
<img src="https://www.test.com/wp-content/uploads/avatars/23/user-bpthumb.jpg" style="width: 15px"> User (<strong>U</strong>sername)</li>
```
and need to remove `(<strong>U</strong>sername)`
I have also tried to remove or add some html span inside the native bp code
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s (%s)' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name ),
esc_html( $user->ID )
```
but when i try to remove (%s) it just breaks the displayed result. | Try this but note that it may not send the message:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name ),
' '
```
Or this:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name )
``` |
366,380 | <p>I am using this function to notify users when their post is published. However, repeated emails are being sent when the post is updated. I only want to send 1 email when the post is published first and then not sent more emails if the post is subsequently updated. </p>
<pre><code>function notifyauthor($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";
$message = "
Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."
"
;
wp_mail($author->user_email, $subject, $message);
}
add_action('publish_post', 'notifyauthor');
</code></pre>
| [
{
"answer_id": 366386,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 1,
"selected": false,
"text": "<p>Try this but note that it may not send the message:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ), \n ' '\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ) \n</code></pre>\n"
},
{
"answer_id": 366438,
"author": "Honoluluman",
"author_id": 129972,
"author_profile": "https://wordpress.stackexchange.com/users/129972",
"pm_score": 0,
"selected": false,
"text": "<p>So i managed to solve this problem with some CSS, unfortunately there is no possibility to wrap with any html element around <code>(%s)</code> , BUT there is possibility to wrap with html the rest. So i did this </p>\n\n<pre><code>printf( '<span id=\"keep\"><span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> &nbsp; %s</span> (%s)' . \"\\n\",\n</code></pre>\n\n<p>with out removing nothing from the original code, just adding the span 'keep' and then with the classic css <code>visibility:hidden;</code> <a href=\"https://stackoverflow.com/a/48591995/8827124\">trick</a> i managed to hide it simple.</p>\n"
}
] | 2020/05/11 | [
"https://wordpress.stackexchange.com/questions/366380",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this function to notify users when their post is published. However, repeated emails are being sent when the post is updated. I only want to send 1 email when the post is published first and then not sent more emails if the post is subsequently updated.
```
function notifyauthor($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";
$message = "
Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."
"
;
wp_mail($author->user_email, $subject, $message);
}
add_action('publish_post', 'notifyauthor');
``` | Try this but note that it may not send the message:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name ),
' '
```
Or this:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name )
``` |
366,431 | <p>I'm new to CSS so forgive me if this is obvious.</p>
<p>I have the following code for aligning my site logo to the left-hand side. And it works exactly as I want it to.</p>
<pre><code> /* Align site logo to the left */
.site-logo {
float: left !important;
padding-top: 15px;
}
</code></pre>
<p>However, I have read that it is (usually) bad practice to make use of !important and that it may create problems at a later date.</p>
<p>When should !important be used? In the example above, how would you achieve the desired result without using it? (I've tried various things all to no avail ;-) )</p>
<p>Thanks</p>
| [
{
"answer_id": 366386,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 1,
"selected": false,
"text": "<p>Try this but note that it may not send the message:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ), \n ' '\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>'<span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> %s' . \"\\n\", \n esc_attr( 'link-' . $user->ID ), \n esc_url( $user->image ), \n esc_html( $user->name ) \n</code></pre>\n"
},
{
"answer_id": 366438,
"author": "Honoluluman",
"author_id": 129972,
"author_profile": "https://wordpress.stackexchange.com/users/129972",
"pm_score": 0,
"selected": false,
"text": "<p>So i managed to solve this problem with some CSS, unfortunately there is no possibility to wrap with any html element around <code>(%s)</code> , BUT there is possibility to wrap with html the rest. So i did this </p>\n\n<pre><code>printf( '<span id=\"keep\"><span id=\"%s\" href=\"#\"></span><img src=\"%s\" style=\"width: 15px\"> &nbsp; %s</span> (%s)' . \"\\n\",\n</code></pre>\n\n<p>with out removing nothing from the original code, just adding the span 'keep' and then with the classic css <code>visibility:hidden;</code> <a href=\"https://stackoverflow.com/a/48591995/8827124\">trick</a> i managed to hide it simple.</p>\n"
}
] | 2020/05/12 | [
"https://wordpress.stackexchange.com/questions/366431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187719/"
] | I'm new to CSS so forgive me if this is obvious.
I have the following code for aligning my site logo to the left-hand side. And it works exactly as I want it to.
```
/* Align site logo to the left */
.site-logo {
float: left !important;
padding-top: 15px;
}
```
However, I have read that it is (usually) bad practice to make use of !important and that it may create problems at a later date.
When should !important be used? In the example above, how would you achieve the desired result without using it? (I've tried various things all to no avail ;-) )
Thanks | Try this but note that it may not send the message:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name ),
' '
```
Or this:
```
'<span id="%s" href="#"></span><img src="%s" style="width: 15px"> %s' . "\n",
esc_attr( 'link-' . $user->ID ),
esc_url( $user->image ),
esc_html( $user->name )
``` |
366,489 | <p>For a marketing reason, my client needs a standalone HTML Page as the "temporary homepage" </p>
<p>What I would like to do is redirect the homepage to a page OUTSIDE of the WordPress ecosystem - I guess this is done using HTACCESS rules...</p>
<p>Can I even do this without breaking WordPress? </p>
<p>Thanks</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/13 | [
"https://wordpress.stackexchange.com/questions/366489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | For a marketing reason, my client needs a standalone HTML Page as the "temporary homepage"
What I would like to do is redirect the homepage to a page OUTSIDE of the WordPress ecosystem - I guess this is done using HTACCESS rules...
Can I even do this without breaking WordPress?
Thanks | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,493 | <p>I'm looking for a way to disable Rest API for a user role called 'external_user' (disable wp-json queries.)</p>
<p>This user role can see right now alot of posts and pages information with when we put wp-json on the URL (users, pages, posts...)</p>
<p>I use actually the plugin <a href="https://fr.wordpress.org/plugins/disable-json-api/" rel="nofollow noreferrer">DISABLE REST API</a> but it prevent only not logged users to see json informations. i need to do the same thing with <strong>external_user</strong> role.</p>
<p>If it's not possible, can I redirect this user role <strong>(and only external_user role)</strong> to 404 pages if he try to put an URL with wp-json ? </p>
<p>Thanks.</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/13 | [
"https://wordpress.stackexchange.com/questions/366493",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] | I'm looking for a way to disable Rest API for a user role called 'external\_user' (disable wp-json queries.)
This user role can see right now alot of posts and pages information with when we put wp-json on the URL (users, pages, posts...)
I use actually the plugin [DISABLE REST API](https://fr.wordpress.org/plugins/disable-json-api/) but it prevent only not logged users to see json informations. i need to do the same thing with **external\_user** role.
If it's not possible, can I redirect this user role **(and only external\_user role)** to 404 pages if he try to put an URL with wp-json ?
Thanks. | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,509 | <p>I'm making a review widget that comes as a shortcode and Gutenberg block. The shortcode part was easy as I have built many shortcodes before, but I'm stuck on building my first Gutenberg block.</p>
<p>More specifically, I've learned how to build a block that outputs div with custom class, but I can't find how to add a custom div attribute anywhere...</p>
<p>Here's the code responsible for block output:</p>
<pre><code>return el( 'div',
{
className: 'review-widget',
}
); // End return
</code></pre>
<p>and this outputs</p>
<p><code><div class="review-widget"></div></code></p>
<p>properly.</p>
<p>However, I need to output a div like this:</p>
<p><code><div class="review-widget" data-limit="10"></div></code></p>
<p>but I'm having a hard time adding the data-limit="10" to the div.</p>
<p>I've tried:</p>
<pre><code>return el( 'div',
{
className: 'review-widget',
data-limit: 10
}
); // End return
</code></pre>
<p>but it doesn't work...</p>
<p>Any ideas would be appreciated :)</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/13 | [
"https://wordpress.stackexchange.com/questions/366509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/173962/"
] | I'm making a review widget that comes as a shortcode and Gutenberg block. The shortcode part was easy as I have built many shortcodes before, but I'm stuck on building my first Gutenberg block.
More specifically, I've learned how to build a block that outputs div with custom class, but I can't find how to add a custom div attribute anywhere...
Here's the code responsible for block output:
```
return el( 'div',
{
className: 'review-widget',
}
); // End return
```
and this outputs
`<div class="review-widget"></div>`
properly.
However, I need to output a div like this:
`<div class="review-widget" data-limit="10"></div>`
but I'm having a hard time adding the data-limit="10" to the div.
I've tried:
```
return el( 'div',
{
className: 'review-widget',
data-limit: 10
}
); // End return
```
but it doesn't work...
Any ideas would be appreciated :) | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,530 | <p>I am using this code for a meta_query</p>
<pre><code> $values = shortcode_atts( array('category' => 'Test',), $atts );
$args = array(
'post_type' => 'mytype',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => esc_attr($values['category']),
'compare' => '='
),
),
);
$query = new WP_Query( $args );
</code></pre>
<p>How could I assign the result of <code>br_type</code> to a php variable?</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/13 | [
"https://wordpress.stackexchange.com/questions/366530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this code for a meta\_query
```
$values = shortcode_atts( array('category' => 'Test',), $atts );
$args = array(
'post_type' => 'mytype',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => esc_attr($values['category']),
'compare' => '='
),
),
);
$query = new WP_Query( $args );
```
How could I assign the result of `br_type` to a php variable? | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,563 | <p>I'm adding a custom column to the admin display for a custom post type. The custom column should display the selected options from an ACF Pro select field. Instead, it always triggers as containing the value, which suggests to me that instead of pulling only the selected options for each post, it's pulling all available values for the ACF Pro select field. </p>
<p>I'm just... not sure how to solve this. What am I getting wrong here? </p>
<pre><code>add_action( 'manage_asgallery_posts_custom_column', 'asgallery_new_column', 10, 2);
function asgallery_new_column( $column_name, $post_id ) {
if( $column_name == 'featured_posts' ) {
$a = get_field_object('field_5dbcb72cad947', $post_id);
$a_value = $a['value'];
//$case_study = get_post_meta( $post_id, 'case_study_category' );
if(strpos($a_value, 'Repair') !== false) {
echo 'Repair';
}
else { echo 'None'; }
}
}
</code></pre>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/14 | [
"https://wordpress.stackexchange.com/questions/366563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160880/"
] | I'm adding a custom column to the admin display for a custom post type. The custom column should display the selected options from an ACF Pro select field. Instead, it always triggers as containing the value, which suggests to me that instead of pulling only the selected options for each post, it's pulling all available values for the ACF Pro select field.
I'm just... not sure how to solve this. What am I getting wrong here?
```
add_action( 'manage_asgallery_posts_custom_column', 'asgallery_new_column', 10, 2);
function asgallery_new_column( $column_name, $post_id ) {
if( $column_name == 'featured_posts' ) {
$a = get_field_object('field_5dbcb72cad947', $post_id);
$a_value = $a['value'];
//$case_study = get_post_meta( $post_id, 'case_study_category' );
if(strpos($a_value, 'Repair') !== false) {
echo 'Repair';
}
else { echo 'None'; }
}
}
``` | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,570 | <p>I have a custom post type called 'Inspections'</p>
<p>Doing this, you can access an inspection record by going to <code>example.com/inspections/inspection-slug-here</code></p>
<p>However, I want to add some 'sub-pages' if you will:</p>
<pre><code>/inspections/<inspection-slug-here>/sub-page1
/inspections/<inspection-slug-here>/sub-page2
</code></pre>
<p>In this case, I would really like <code>sub-page1</code> and <code>sub-page2</code> to be templates that I can author in elementor, or something similar.</p>
<p>In a perfect scenario, I would like to pass the details of the parent (inspection-slug-here) to be loaded in this sub section so I can use custom fields or something of the likes.</p>
<p>Is there anything out there that does this? I am using elementor and an elementor templates tool, but cannot find any ways to do what i want.</p>
<p>Thanks!</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/14 | [
"https://wordpress.stackexchange.com/questions/366570",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123076/"
] | I have a custom post type called 'Inspections'
Doing this, you can access an inspection record by going to `example.com/inspections/inspection-slug-here`
However, I want to add some 'sub-pages' if you will:
```
/inspections/<inspection-slug-here>/sub-page1
/inspections/<inspection-slug-here>/sub-page2
```
In this case, I would really like `sub-page1` and `sub-page2` to be templates that I can author in elementor, or something similar.
In a perfect scenario, I would like to pass the details of the parent (inspection-slug-here) to be loaded in this sub section so I can use custom fields or something of the likes.
Is there anything out there that does this? I am using elementor and an elementor templates tool, but cannot find any ways to do what i want.
Thanks! | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,574 | <p>I do have a problem on my WordPress site. In the frontend there is a spam post (not a comment, a post) visible to everybody. I don't know where it comes from and all malware scans were negative so far. However, in order to solve this problem I will need to delete this post. But it can't be seen in the backend.</p>
<p><a href="https://i.stack.imgur.com/5iK6c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5iK6c.png" alt="enter image description here"></a></p>
<p>As you can see on the given screenshot the posts area shows "all posts" with the number of 58. However, when going through them via the pagination there are only 57. As I can't find the spam post via normal search methods I assume the spam post has somehow been hidden. There are no posts in the trash or whatsoever. I also checked pages, categories, tags, etc. but nothing.</p>
<p>Is there a way to remove it eventually?</p>
| [
{
"answer_id": 366507,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>As @JacobPeattie suggested in comments:</p>\n\n<blockquote>\n <p>If you just add <code>index.html</code> to the root of your WordPress installation that should become the homepage.</p>\n</blockquote>\n\n<p>This does, however, require that the <code>DirectoryIndex</code> is set appropriately. For example:</p>\n\n<pre><code>DirectoryIndex index.html\n</code></pre>\n\n<p>The <code>DirectoryIndex</code> is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.</p>\n\n<p>Or, to have multiple directory index documents (that are tried in turn):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>(<code>index.php</code> would ordinarily be required for WordPress.)</p>\n\n<p>You can change <code>index.html</code> to anything you like.</p>\n\n<p>You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:</p>\n\n<pre><code>DirectoryIndex /path/to/alternative/homepage.php\n</code></pre>\n\n<p>But this will mean that if you request <code>/path/to/any-directory/</code> then it will also serve <code>/path/to/alternative/homepage.php</code> (via an internal subrequest).</p>\n\n<p>The default WordPress front-controller (directives in <code>.htaccess</code>) don't do anything when you request the homepage (or any directory for that matter). It relies on mod_dir (ie. <code>DirectoryIndex</code>) to make the internal subrequest for <code>index.php</code>. Only when you request <code>/<something></code> might the request be manually rewritten to <code>index.php</code>.</p>\n\n<hr>\n\n<p>Alternately, you can use mod_rewrite, <em>before</em> the WordPress front-controller to internally rewrite the request for the homepage (<code>/</code>) to your alternative homepage.</p>\n\n<p>For example:</p>\n\n<pre><code># Internal rewrite to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<hr>\n\n<p>If you did literally want to \"redirect\" to a temporary homepage then you just need to add the <code>R</code> flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)</p>\n\n<p>For example:</p>\n\n<pre><code># External \"redirect\" to alternative homepage\nRewriteRule ^$ /path/to/alternative/homepage.php [R,L]\n\n# BEGIN WordPress\n# : (WordPress front-controller goes here)\n</code></pre>\n\n<p>Note that this is a 302 (temporary) redirect.</p>\n"
},
{
"answer_id": 366541,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to redirect the one page to another page then it is possible with the <code>.htaccess</code> file, add the below rule in the <code>.htaccess</code>:</p>\n\n<pre><code>Redirect 301 https://example1.com/ https://example2.com/\n</code></pre>\n\n<p>Don't forget to change the example URLs.</p>\n"
}
] | 2020/05/14 | [
"https://wordpress.stackexchange.com/questions/366574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136979/"
] | I do have a problem on my WordPress site. In the frontend there is a spam post (not a comment, a post) visible to everybody. I don't know where it comes from and all malware scans were negative so far. However, in order to solve this problem I will need to delete this post. But it can't be seen in the backend.
[](https://i.stack.imgur.com/5iK6c.png)
As you can see on the given screenshot the posts area shows "all posts" with the number of 58. However, when going through them via the pagination there are only 57. As I can't find the spam post via normal search methods I assume the spam post has somehow been hidden. There are no posts in the trash or whatsoever. I also checked pages, categories, tags, etc. but nothing.
Is there a way to remove it eventually? | As @JacobPeattie suggested in comments:
>
> If you just add `index.html` to the root of your WordPress installation that should become the homepage.
>
>
>
This does, however, require that the `DirectoryIndex` is set appropriately. For example:
```
DirectoryIndex index.html
```
The `DirectoryIndex` is the document that Apache tries to serve when you request a directory. In this case, the document root. Specifying a relative URL-path will look for that file relative to the directory being requested.
Or, to have multiple directory index documents (that are tried in turn):
```
DirectoryIndex index.html index.php
```
(`index.php` would ordinarily be required for WordPress.)
You can change `index.html` to anything you like.
You can also specify a file in a specific location elsewhere on the filesystem (providing it is publicly accessible). For example:
```
DirectoryIndex /path/to/alternative/homepage.php
```
But this will mean that if you request `/path/to/any-directory/` then it will also serve `/path/to/alternative/homepage.php` (via an internal subrequest).
The default WordPress front-controller (directives in `.htaccess`) don't do anything when you request the homepage (or any directory for that matter). It relies on mod\_dir (ie. `DirectoryIndex`) to make the internal subrequest for `index.php`. Only when you request `/<something>` might the request be manually rewritten to `index.php`.
---
Alternately, you can use mod\_rewrite, *before* the WordPress front-controller to internally rewrite the request for the homepage (`/`) to your alternative homepage.
For example:
```
# Internal rewrite to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
---
If you did literally want to "redirect" to a temporary homepage then you just need to add the `R` flag to the above directive. (Although the internal rewrite/subrequest, as mention above, would be preferable in most scenarios.)
For example:
```
# External "redirect" to alternative homepage
RewriteRule ^$ /path/to/alternative/homepage.php [R,L]
# BEGIN WordPress
# : (WordPress front-controller goes here)
```
Note that this is a 302 (temporary) redirect. |
366,584 | <p>I am new to wp, fair warning :) </p>
<p>I have added a new blank page by adding a php file in the twentytwenty theme folder with: </p>
<pre><code><?php
/* Template Name: charles */
?>
</code></pre>
<p>Then, I have created a new page by choosing the charles template in the admin. </p>
<p>Now In my new blank page I can see the contents of the new plugin I am creating which is what I want. So great till here. </p>
<p>But now, I need to add a css custom file, a js custom file and a call to the jquery cdn url. I've tried by changing twentytwenty <code>functions.php</code> adding: </p>
<pre><code>function wpdocs_charles_scripts() {
wp_enqueue_style( 'myStyle', get_stylesheet_uri() );
wp_enqueue_script( 'myScript', get_template_directory_uri() . '/myFiles/myScript.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_charles_scripts' );
</code></pre>
<p>But it does not work for my <a href="http://localhost/wordpress/charles/" rel="nofollow noreferrer">http://localhost/wordpress/charles/</a>
Also I've tried using Simple Custom CSS and JS but this changes the styles of the whole page but not the styles in charles. </p>
<p>My last try in my new plugin php:</p>
<pre><code>add_action('init', 'register_script');
function register_script() {
wp_register_script( 'myScript', plugins_url('/myFiles/myScript.js', __FILE__), array('jquery'), '2.5.1' );
wp_register_style( 'myStyle', plugins_url('/myFiles/myStyle.css', __FILE__), false, '1.0.0', 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
wp_enqueue_script('myScript');
wp_enqueue_style( 'myStyle' );
}
</code></pre>
<p>Please, help I think I am missing something basic. </p>
<p>Thanks a lot </p>
| [
{
"answer_id": 366590,
"author": "made2popular",
"author_id": 173347,
"author_profile": "https://wordpress.stackexchange.com/users/173347",
"pm_score": -1,
"selected": false,
"text": "<p>You should try this function. This will run only when the page template is charles.</p>\n\n<pre><code>if ( is_page_template( 'charles.php' ) ) {\n // Enqueue the script and CSS here\n}\n</code></pre>\n\n<p>Please try this and let me know.</p>\n"
},
{
"answer_id": 366610,
"author": "ADM",
"author_id": 188063,
"author_profile": "https://wordpress.stackexchange.com/users/188063",
"pm_score": 0,
"selected": false,
"text": "<p>In my theme functions.php at the end works for me: </p>\n\n<pre><code>function themesCharles_enqueue_style() {\n wp_enqueue_style( 'my-theme', get_template_directory_uri() .'/myFiles/myStyle.css', false );\n}\n\nfunction themesCharles_enqueue_script() {\n wp_enqueue_script( 'my-js', get_template_directory_uri() .'/myFiles/myScript.js', false );\n}\n\nadd_action( 'wp_enqueue_scripts', 'themesCharles_enqueue_style' );\nadd_action( 'wp_enqueue_scripts', 'themesCharles_enqueue_script' );\n</code></pre>\n"
}
] | 2020/05/14 | [
"https://wordpress.stackexchange.com/questions/366584",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188063/"
] | I am new to wp, fair warning :)
I have added a new blank page by adding a php file in the twentytwenty theme folder with:
```
<?php
/* Template Name: charles */
?>
```
Then, I have created a new page by choosing the charles template in the admin.
Now In my new blank page I can see the contents of the new plugin I am creating which is what I want. So great till here.
But now, I need to add a css custom file, a js custom file and a call to the jquery cdn url. I've tried by changing twentytwenty `functions.php` adding:
```
function wpdocs_charles_scripts() {
wp_enqueue_style( 'myStyle', get_stylesheet_uri() );
wp_enqueue_script( 'myScript', get_template_directory_uri() . '/myFiles/myScript.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_charles_scripts' );
```
But it does not work for my <http://localhost/wordpress/charles/>
Also I've tried using Simple Custom CSS and JS but this changes the styles of the whole page but not the styles in charles.
My last try in my new plugin php:
```
add_action('init', 'register_script');
function register_script() {
wp_register_script( 'myScript', plugins_url('/myFiles/myScript.js', __FILE__), array('jquery'), '2.5.1' );
wp_register_style( 'myStyle', plugins_url('/myFiles/myStyle.css', __FILE__), false, '1.0.0', 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
wp_enqueue_script('myScript');
wp_enqueue_style( 'myStyle' );
}
```
Please, help I think I am missing something basic.
Thanks a lot | In my theme functions.php at the end works for me:
```
function themesCharles_enqueue_style() {
wp_enqueue_style( 'my-theme', get_template_directory_uri() .'/myFiles/myStyle.css', false );
}
function themesCharles_enqueue_script() {
wp_enqueue_script( 'my-js', get_template_directory_uri() .'/myFiles/myScript.js', false );
}
add_action( 'wp_enqueue_scripts', 'themesCharles_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'themesCharles_enqueue_script' );
``` |
366,595 | <p>Thanks to the German language, I happen to have some really long words in my WordPress 5.4.1 content.
I need to decide <strong>where exactly to hyphenate</strong>, as the standard hyphenation is dumb.<br></p>
<p>If I enter <code>Wachstums&shy;förderung</code> in the Gutenberg block editor in a headline (e.g. h2), I do not get the expected <code>Wachstums-förderung</code> in the website - it outputs <code>Wachstums&shy;förderung</code>.<br>
(This does work, though, in the page title, outside of the block editor)!</p>
<p>My web search yielded an open issue on GitHub: <a href="https://github.com/WordPress/gutenberg/issues/12872" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg/issues/12872</a><br>
It is open since Dec 2018 and nothing seems to happen soon :-/</p>
<p>Does anybody have an idea, how to solve that problem? (No, putting a hard dash is not an option.)</p>
| [
{
"answer_id": 372154,
"author": "Buglover",
"author_id": 192501,
"author_profile": "https://wordpress.stackexchange.com/users/192501",
"pm_score": 1,
"selected": false,
"text": "<p>You can change the block to "edit as html" via "more options" and set the soft hyphen, then switch back to "Edit visualy".</p>\n"
},
{
"answer_id": 391427,
"author": "Larzan",
"author_id": 34517,
"author_profile": "https://wordpress.stackexchange.com/users/34517",
"pm_score": 2,
"selected": false,
"text": "<p>With the 'new' Gutenberg editor the previously working solution using the <em>tiny_mce_before_init</em> hook does not work anymore, but there is the possibility to define a new shortcode in your theme / plugin as a workaround.</p>\n<p><strong>Solution for Gutenberg</strong></p>\n<pre><code>add_shortcode('shy', 'my_shy_shortcode');\nfunction my_shy_shortcode($atts) {\n return '&shy;';\n}\n</code></pre>\n<p>This simply adds a new shortcode to WordPress with a <em>&shy;</em> entity as output, so you can just write [shy] anywhere in your text and it will be translated to the HTML entity;</p>\n<p>There is currently no 'cleaner' solution and it seems that none is planned, at least not before 5.8 (Github <a href=\"https://github.com/WordPress/gutenberg/issues/12872\" rel=\"nofollow noreferrer\">issue 1</a>, <a href=\"https://github.com/WordPress/gutenberg/issues/23509\" rel=\"nofollow noreferrer\">issue 2</a>)</p>\n<p><strong>Solution for the Classic Editor (no Gutenberg)</strong></p>\n<pre><code>function override_mce_options($initArray) {\n $initArray['entities'] = 'shy';\n\n return $initArray;\n}\nadd_filter('tiny_mce_before_init', 'override_mce_options');\n</code></pre>\n<p>This should prevent TinyMCE from filtering out the shy tag, for more information on how to fine-tune this and keep other entities as well read here: <a href=\"https://stackoverflow.com/a/29261339/826194\">https://stackoverflow.com/a/29261339/826194</a></p>\n"
},
{
"answer_id": 413538,
"author": "23b",
"author_id": 139963,
"author_profile": "https://wordpress.stackexchange.com/users/139963",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a invisible soft hyphen for you to copy: "".</p>\n<p>Unlike the HTML entity <code>&shy;</code> which gets filtered out the second time you edit your content, I am able to insert the invisible soft hyphen character.\nUnfortunately you can visually not tell when it's present. You can identify a invisible character because the cursor won't move when you hit arrow key.</p>\n<p>I am using macOS and configured the [fn] key on my keyboard to show the character/emoji picker. There you can search for "soft hyphen"; it appears as a normal hyphen, but when you double click it, it will be inserted into you document.</p>\n"
}
] | 2020/05/14 | [
"https://wordpress.stackexchange.com/questions/366595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124308/"
] | Thanks to the German language, I happen to have some really long words in my WordPress 5.4.1 content.
I need to decide **where exactly to hyphenate**, as the standard hyphenation is dumb.
If I enter `Wachstums­förderung` in the Gutenberg block editor in a headline (e.g. h2), I do not get the expected `Wachstums-förderung` in the website - it outputs `Wachstums­förderung`.
(This does work, though, in the page title, outside of the block editor)!
My web search yielded an open issue on GitHub: <https://github.com/WordPress/gutenberg/issues/12872>
It is open since Dec 2018 and nothing seems to happen soon :-/
Does anybody have an idea, how to solve that problem? (No, putting a hard dash is not an option.) | With the 'new' Gutenberg editor the previously working solution using the *tiny\_mce\_before\_init* hook does not work anymore, but there is the possibility to define a new shortcode in your theme / plugin as a workaround.
**Solution for Gutenberg**
```
add_shortcode('shy', 'my_shy_shortcode');
function my_shy_shortcode($atts) {
return '­';
}
```
This simply adds a new shortcode to WordPress with a *­* entity as output, so you can just write [shy] anywhere in your text and it will be translated to the HTML entity;
There is currently no 'cleaner' solution and it seems that none is planned, at least not before 5.8 (Github [issue 1](https://github.com/WordPress/gutenberg/issues/12872), [issue 2](https://github.com/WordPress/gutenberg/issues/23509))
**Solution for the Classic Editor (no Gutenberg)**
```
function override_mce_options($initArray) {
$initArray['entities'] = 'shy';
return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');
```
This should prevent TinyMCE from filtering out the shy tag, for more information on how to fine-tune this and keep other entities as well read here: <https://stackoverflow.com/a/29261339/826194> |
366,680 | <p>I'm using <code>wp_get_archives</code> but I cannot prepend any text inside the links. I want code like this:</p>
<pre><code><a href="archive link">[my custom prepend] 2020<a/>
</code></pre>
<p>But the 'before' option will prepend the passed string before the <code><a></code> tag.</p>
<p>Current code is the following:</p>
<pre><code>$archives = wp_get_archives(array(
'type' => 'yearly'
,'echo' => false
,'format' => 'custom'
,'before' => 'News'
));
</code></pre>
<p>So I really would like to get a list of only years and urls, without any markup, so I can build it by myself. Thus maybe without <code>wp_get_archives()</code>.</p>
<p>Maybe the best thing would be have a simple array like:</p>
<pre><code>array(
array('year' => 2020, 'url' => 'https://www.....')
)
</code></pre>
<p>How to?</p>
| [
{
"answer_id": 366702,
"author": "Bob",
"author_id": 188151,
"author_profile": "https://wordpress.stackexchange.com/users/188151",
"pm_score": 1,
"selected": false,
"text": "<p>I was going to suggest creating a regex to parse it but if you look at <a href=\"https://developer.wordpress.org/reference/functions/wp_get_archives/#comment-3570\" rel=\"nofollow noreferrer\">this comment</a> on the Wordpress wp_get_archives() docs it looks like someone has gotten there before us.</p>\n"
},
{
"answer_id": 366784,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>I maneged to do like this:</p>\n\n<p>First, get simply the years:</p>\n\n<pre><code>// this is a multipurpose function I made, and it's quite self explanatory\nfunction get_years($post_type, $order = \"ASC\", $exclude = array(), $future = true, $taxonomy = null, $term = null){\n global $wpdb;\n $type = ($post_type) ? $post_type : 'post';\n $status = ($future) ? \" ('publish', 'future') \" : \" ('publish') \";\n $exclude = (!empty($exclude)) ? \" AND YEAR(post_date) NOT IN (\" . implode(',',$exclude) . \") \" : \"\";\n\n return $wpdb->get_results($wpdb->prepare(\"\n SELECT YEAR(post_date) AS `y`, count(ID) as posts_count\n FROM $wpdb->posts p\n INNER JOIN $wpdb->term_relationships rel ON p.ID = rel.object_id\n INNER JOIN $wpdb->term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id\n INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id\n WHERE\n p.post_type = %s\n AND tt.taxonomy = %s\n AND t.slug = %s\n AND post_status IN \" . $status . \"\n $exclude\n GROUP BY y\n ORDER BY post_date \" . $order,\n $post_type,\n $taxonomy,\n $term\n ),OBJECT_K);\n}\n</code></pre>\n\n<p>Then, cicle through the years and build the permalinks:</p>\n\n<pre><code>get_year_link($year); // this is wp. \n</code></pre>\n\n<p>It works for posts, otherwise one could build the likes in a more 'manual' way:</p>\n\n<pre><code>home_url(user_trailingslashit('write some path here' . $year));\n</code></pre>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | I'm using `wp_get_archives` but I cannot prepend any text inside the links. I want code like this:
```
<a href="archive link">[my custom prepend] 2020<a/>
```
But the 'before' option will prepend the passed string before the `<a>` tag.
Current code is the following:
```
$archives = wp_get_archives(array(
'type' => 'yearly'
,'echo' => false
,'format' => 'custom'
,'before' => 'News'
));
```
So I really would like to get a list of only years and urls, without any markup, so I can build it by myself. Thus maybe without `wp_get_archives()`.
Maybe the best thing would be have a simple array like:
```
array(
array('year' => 2020, 'url' => 'https://www.....')
)
```
How to? | I maneged to do like this:
First, get simply the years:
```
// this is a multipurpose function I made, and it's quite self explanatory
function get_years($post_type, $order = "ASC", $exclude = array(), $future = true, $taxonomy = null, $term = null){
global $wpdb;
$type = ($post_type) ? $post_type : 'post';
$status = ($future) ? " ('publish', 'future') " : " ('publish') ";
$exclude = (!empty($exclude)) ? " AND YEAR(post_date) NOT IN (" . implode(',',$exclude) . ") " : "";
return $wpdb->get_results($wpdb->prepare("
SELECT YEAR(post_date) AS `y`, count(ID) as posts_count
FROM $wpdb->posts p
INNER JOIN $wpdb->term_relationships rel ON p.ID = rel.object_id
INNER JOIN $wpdb->term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id
WHERE
p.post_type = %s
AND tt.taxonomy = %s
AND t.slug = %s
AND post_status IN " . $status . "
$exclude
GROUP BY y
ORDER BY post_date " . $order,
$post_type,
$taxonomy,
$term
),OBJECT_K);
}
```
Then, cicle through the years and build the permalinks:
```
get_year_link($year); // this is wp.
```
It works for posts, otherwise one could build the likes in a more 'manual' way:
```
home_url(user_trailingslashit('write some path here' . $year));
``` |
366,689 | <p>I have a query string added to some urls which isn't pretty:</p>
<pre><code>?city=Amsterdam
</code></pre>
<p>So i'd like to structure the url like: <strong><a href="https://example.com/realpage1/realpage2/amsterdam/" rel="nofollow noreferrer">https://example.com/realpage1/realpage2/amsterdam/</a> or <a href="https://example.com/realpage1/amsterdam/" rel="nofollow noreferrer">https://example.com/realpage1/amsterdam/</a></strong> depending on the type of content.</p>
<p>And then get the variable with some htaccess like:</p>
<pre><code>RewriteRule ^/(.*)/(.*)/(.*)$ ?city=$3
</code></pre>
<p>The page /aaa/bbb/ does exits. But the above gives a 404.</p>
<p>How can i achieve this in Wordpress? Thanks.</p>
<p><strong>UPDATE:</strong>
Following @pat's suggestion, and the code form the user-contributed-notes, i now have the below code. But, still a 404 is returned. What am i missing?
Code is added to my child-theme functions.php by the way.</p>
<pre><code>function wpdocs_flush_rules() {
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
add_action( 'wp_loaded','wpdocs_flush_rules' );
function wpdocs_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] = 'index.php?stad=$matches[3]';
return $newrules + $rules;
}
add_filter( 'page_rewrite_rules', 'wpdocs_insert_rewrite_rules' );
function wpdocs_insert_query_vars( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'wpdocs_insert_query_vars' );
</code></pre>
| [
{
"answer_id": 366759,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few points to share because I could foresee that the comment will be very long and I post some suggestion here for reference and hopefully could fix it up.</p>\n\n<h3>1st point about the rewrite</h3>\n\n<pre><code>$newrules['/(\\d*)$'] = 'index.php?city=$matches[1]';\n</code></pre>\n\n<p>I guess you expect to use a url like <code>https://example.com/new_york/</code> to the path so city will take up <code>new_york</code> like city=new_york.\nHowever, the rule <code>(\\d*)</code> which expect to screen out only digits so character other than 0-9 will be ignored.</p>\n\n<p>Just guessing that it would be ([^/]+) </p>\n\n<ul>\n<li>([^/]+) excluding slash '/', + match any characters 1 to unlimited times</li>\n<li>() means for capturing group</li>\n</ul>\n\n<pre><code>$newrules['([^/]+)/?$'] = 'index.php?city=$matches[1]';\n</code></pre>\n\n<p>Please try the regex in this <a href=\"https://regex101.com/r/uasJdc/1\" rel=\"nofollow noreferrer\">tool</a>\n(the tool requires escape of <code>/</code> => written as <code>\\/</code>, in php code, it is not necessary in your case)</p>\n\n<h3>2nd point about the priority</h3>\n\n<p>The <code>rewrite_rules_array</code> is used so the rule above will be added to the end (or near end if there is any other plugins doing the same) of the rule. The rewrite rule is matching sequentially. So, there is chance that the 404 is being determined before the rule is being matched with similar patterns.</p>\n\n<p>The rule could be put in higher priority by a number of ways such as putting in other earlier rule filters or using add_rewrite_rule() with <code>top</code> attribute to make it matching in higher priority. In other words, the possibility of this rule is being matched first is heightened and might result in other undesired effect. So a thorough test to match your needs is necessary. <strong>Please expect testing and adjustment to be made before it comes to satisfaction.</strong></p>\n\n<p>Please refer to docs for different filters:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/rewrite_rules_array/\" rel=\"nofollow noreferrer\">rewrite_rules_array</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/page_rewrite_rules/\" rel=\"nofollow noreferrer\">page_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/author_rewrite_rules/\" rel=\"nofollow noreferrer\">author_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/search_rewrite_rules/\" rel=\"nofollow noreferrer\">search_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/comments_rewrite_rules/\" rel=\"nofollow noreferrer\">comments_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/root_rewrite_rules/\" rel=\"nofollow noreferrer\">root_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/date_rewrite_rules/\" rel=\"nofollow noreferrer\">date_rewrite_rules</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/post_rewrite_rules/\" rel=\"nofollow noreferrer\">post_rewrite_rules</a></li>\n</ul>\n\n<pre><code>function wpdocs_insert_rewrite_rules( $rules ) {\n\n $newrules = array();\n $newrules['([^/]+)/?$'] = 'index.php?city=$matches[1]';\n return $newrules + $rules;\n}\nadd_filter( 'TRY_CHANGING_FILER_HERE_IF_LOADING_PRIORITY_MATTERS','wpdocs_insert_rewrite_rules' );\n</code></pre>\n\n<p>An alternative way to using the above filters using <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">add_rewrite_rule()</a></p>\n\n<pre><code>add_action('init', 'ws366689_insert_rewrite_rules' );\nfunction ws366689_insert_rewrite_rules() {\n add_rewrite_rule('([^/]+)/?$', 'index.php?city=$matches[1]', 'top');\n}\n</code></pre>\n\n<h3>about the writing format</h3>\n\n<p>Just a personal opinion that you could use the format shown in the docs to write the array for simplicity and clarity.</p>\n\n<pre><code>function wpdocs_insert_query_vars( $vars ) {\n\n $vars[] = 'city';\n return $vars;\n\n}\nadd_filter( 'query_vars','wpdocs_insert_query_vars' );\n</code></pre>\n\n<p>The rules inside wpdocs_flush_rules() is also needed to be updated.</p>\n"
},
{
"answer_id": 367156,
"author": "Peps",
"author_id": 188144,
"author_profile": "https://wordpress.stackexchange.com/users/188144",
"pm_score": 1,
"selected": true,
"text": "<p>Oke, so after days of digging I finally found the answer. The problem was:</p>\n\n<pre><code>index.php?pagename=$matches[1]/$matches[2]&city=$matches[3]\n</code></pre>\n\n<p>The 'pagename' parameter had to be set and filled too, with both 'slugs'.</p>\n\n<p>The complete code I ended up with:</p>\n\n<pre><code>function custom_rewrite_rule() {\n add_rewrite_rule( '(.*)/(.*)/([a-z-]{4,20})[/]?$', 'index.php?pagename=$matches[1]/$matches[2]&city=$matches[3]', 'top' );\n}\nadd_action('init', 'custom_rewrite_rule', 10, 0);\n\nfunction insert_custom_query_vars ( $vars ) {\n\n $vars[] = 'city';\n return $vars;\n\n}\nadd_filter( 'query_vars', 'insert_custom_query_vars' );\n</code></pre>\n\n<p>Happy blogging ;)</p>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188144/"
] | I have a query string added to some urls which isn't pretty:
```
?city=Amsterdam
```
So i'd like to structure the url like: **<https://example.com/realpage1/realpage2/amsterdam/> or <https://example.com/realpage1/amsterdam/>** depending on the type of content.
And then get the variable with some htaccess like:
```
RewriteRule ^/(.*)/(.*)/(.*)$ ?city=$3
```
The page /aaa/bbb/ does exits. But the above gives a 404.
How can i achieve this in Wordpress? Thanks.
**UPDATE:**
Following @pat's suggestion, and the code form the user-contributed-notes, i now have the below code. But, still a 404 is returned. What am i missing?
Code is added to my child-theme functions.php by the way.
```
function wpdocs_flush_rules() {
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
add_action( 'wp_loaded','wpdocs_flush_rules' );
function wpdocs_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] = 'index.php?stad=$matches[3]';
return $newrules + $rules;
}
add_filter( 'page_rewrite_rules', 'wpdocs_insert_rewrite_rules' );
function wpdocs_insert_query_vars( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'wpdocs_insert_query_vars' );
``` | Oke, so after days of digging I finally found the answer. The problem was:
```
index.php?pagename=$matches[1]/$matches[2]&city=$matches[3]
```
The 'pagename' parameter had to be set and filled too, with both 'slugs'.
The complete code I ended up with:
```
function custom_rewrite_rule() {
add_rewrite_rule( '(.*)/(.*)/([a-z-]{4,20})[/]?$', 'index.php?pagename=$matches[1]/$matches[2]&city=$matches[3]', 'top' );
}
add_action('init', 'custom_rewrite_rule', 10, 0);
function insert_custom_query_vars ( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'insert_custom_query_vars' );
```
Happy blogging ;) |
366,708 | <p>I am using this code but it seems that ordering by meta_keys <code>br_category</code> first and <code>br_name</code> second, doesn't produce the correct results</p>
<pre><code>$args = array(
'post_type' => 'brands',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => 'Aviation'
),
array(
'key' => 'br_category'
),
array(
'key' => 'br_name'
)
),
'posts_per_page' => -1,
'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ],
'order' => 'ASC',
'fields' => 'ids'
);
</code></pre>
<p>Is the syntax I am using incorrect?</p>
| [
{
"answer_id": 366733,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code>'orderby' => array( 'br_category' => 'ASC', 'br_name' => 'ASC' ), \n</code></pre>\n"
},
{
"answer_id": 366743,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<h3>Current Query</h3>\n\n<pre><code>$args = array(\n 'post_type' => 'brands',\n 'meta_query' => array( \n array( \n 'key' => 'br_type', \n 'value' => 'Aviation'\n ), \n array( \n 'key' => 'br_category' \n ), \n array( \n 'key' => 'br_name' \n ) \n ), \n 'posts_per_page' => -1, \n 'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ], \n 'order' => 'ASC', \n 'fields' => 'ids'\n);\n</code></pre>\n\n<p>produce this SQL query</p>\n\n<pre><code>'SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1 \n AND ( \n ( wp_postmeta.meta_key = \\'br_type\\' AND wp_postmeta.meta_value = \\'Aviation\\' ) \n AND \n mt1.meta_key = \\'br_category\\' \n AND \n mt2.meta_key = \\'br_name\\'\n ) AND wp_posts.post_type = \\'brands\\' AND (wp_posts.post_status = \\'publish\\' OR wp_posts.post_status = \\'acf-disabled\\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \\'private\\') GROUP BY wp_posts.ID '\n</code></pre>\n\n<p>It means it does not add any order by clause because it does not understand.</p>\n\n<h3>Here is the correct way to order by multiple meta key value</h3>\n\n<pre><code>$args = array(\n 'post_type' => 'brands',\n 'meta_query' => array( \n // 'relation' => 'AND', // default is AND\n 'br_type_clause' => array( \n 'key' => 'br_type', \n 'value' => 'Aviation',\n ), \n 'br_category_clause' => array( \n 'key' => 'br_category',\n ), \n 'br_name_clause' => array( \n 'key' => 'br_name',\n ) \n ), \n 'posts_per_page' => -1, \n\n 'meta_key' => array( 'br_category', 'br_name', 'br_type' ),\n // add sql: wp_postmeta.meta_key IN ('br_category','br_name','br_type') \n\n 'orderby' => array(\n 'br_type_clause' => 'ASC', \n 'br_category_clause' => 'ASC',\n 'br_name_clause' => 'ASC',\n 'name' => 'ASC', // illustrative purpose, could use post key\n ), \n // 'order' => 'ASC', // it is ignored with above orderby override\n 'fields' => 'ids'\n ),\n</code></pre>\n\n<p>which produce the SQL</p>\n\n<pre><code>SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND ( \n wp_postmeta.meta_key IN ('br_category','br_name','br_type') \n AND \n ( \n ( mt1.meta_key = 'br_type' AND mt1.meta_value = 'Aviation' ) \n AND \n mt2.meta_key = 'br_category' \n AND \n mt3.meta_key = 'br_name'\n )\n) AND wp_posts.post_type = 'brands' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC, CAST(mt3.meta_value AS CHAR) ASC, wp_posts.post_name ASC \n</code></pre>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a> with section <code>‘orderby’ with multiple ‘meta_key’s</code></p>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this code but it seems that ordering by meta\_keys `br_category` first and `br_name` second, doesn't produce the correct results
```
$args = array(
'post_type' => 'brands',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => 'Aviation'
),
array(
'key' => 'br_category'
),
array(
'key' => 'br_name'
)
),
'posts_per_page' => -1,
'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ],
'order' => 'ASC',
'fields' => 'ids'
);
```
Is the syntax I am using incorrect? | ### Current Query
```
$args = array(
'post_type' => 'brands',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => 'Aviation'
),
array(
'key' => 'br_category'
),
array(
'key' => 'br_name'
)
),
'posts_per_page' => -1,
'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ],
'order' => 'ASC',
'fields' => 'ids'
);
```
produce this SQL query
```
'SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1
AND (
( wp_postmeta.meta_key = \'br_type\' AND wp_postmeta.meta_value = \'Aviation\' )
AND
mt1.meta_key = \'br_category\'
AND
mt2.meta_key = \'br_name\'
) AND wp_posts.post_type = \'brands\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'acf-disabled\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \'private\') GROUP BY wp_posts.ID '
```
It means it does not add any order by clause because it does not understand.
### Here is the correct way to order by multiple meta key value
```
$args = array(
'post_type' => 'brands',
'meta_query' => array(
// 'relation' => 'AND', // default is AND
'br_type_clause' => array(
'key' => 'br_type',
'value' => 'Aviation',
),
'br_category_clause' => array(
'key' => 'br_category',
),
'br_name_clause' => array(
'key' => 'br_name',
)
),
'posts_per_page' => -1,
'meta_key' => array( 'br_category', 'br_name', 'br_type' ),
// add sql: wp_postmeta.meta_key IN ('br_category','br_name','br_type')
'orderby' => array(
'br_type_clause' => 'ASC',
'br_category_clause' => 'ASC',
'br_name_clause' => 'ASC',
'name' => 'ASC', // illustrative purpose, could use post key
),
// 'order' => 'ASC', // it is ignored with above orderby override
'fields' => 'ids'
),
```
which produce the SQL
```
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND (
wp_postmeta.meta_key IN ('br_category','br_name','br_type')
AND
(
( mt1.meta_key = 'br_type' AND mt1.meta_value = 'Aviation' )
AND
mt2.meta_key = 'br_category'
AND
mt3.meta_key = 'br_name'
)
) AND wp_posts.post_type = 'brands' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC, CAST(mt3.meta_value AS CHAR) ASC, wp_posts.post_name ASC
```
Reference: [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/) with section `‘orderby’ with multiple ‘meta_key’s` |
366,715 | <p>I’m wondering if you could help with some code I’m struggling with.</p>
<p>I’ve got an ACF Image Field on the Post Category Taxonomy. I need to add it into the post loop so the category image shows up instead of the featured image. Here’s the code that I have in:</p>
<pre><code>$current_term = get_queried_object();
$author_image = get_field('author_image', $current_term );
echo do_shortcode('[image_shortcode id="'.$author_image.'" image_size="original"]');
</code></pre>
<p>It’s working on the Category Archive page, but not on the Tags Archive page. Let me know your thoughts.</p>
| [
{
"answer_id": 366733,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code>'orderby' => array( 'br_category' => 'ASC', 'br_name' => 'ASC' ), \n</code></pre>\n"
},
{
"answer_id": 366743,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<h3>Current Query</h3>\n\n<pre><code>$args = array(\n 'post_type' => 'brands',\n 'meta_query' => array( \n array( \n 'key' => 'br_type', \n 'value' => 'Aviation'\n ), \n array( \n 'key' => 'br_category' \n ), \n array( \n 'key' => 'br_name' \n ) \n ), \n 'posts_per_page' => -1, \n 'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ], \n 'order' => 'ASC', \n 'fields' => 'ids'\n);\n</code></pre>\n\n<p>produce this SQL query</p>\n\n<pre><code>'SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1 \n AND ( \n ( wp_postmeta.meta_key = \\'br_type\\' AND wp_postmeta.meta_value = \\'Aviation\\' ) \n AND \n mt1.meta_key = \\'br_category\\' \n AND \n mt2.meta_key = \\'br_name\\'\n ) AND wp_posts.post_type = \\'brands\\' AND (wp_posts.post_status = \\'publish\\' OR wp_posts.post_status = \\'acf-disabled\\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \\'private\\') GROUP BY wp_posts.ID '\n</code></pre>\n\n<p>It means it does not add any order by clause because it does not understand.</p>\n\n<h3>Here is the correct way to order by multiple meta key value</h3>\n\n<pre><code>$args = array(\n 'post_type' => 'brands',\n 'meta_query' => array( \n // 'relation' => 'AND', // default is AND\n 'br_type_clause' => array( \n 'key' => 'br_type', \n 'value' => 'Aviation',\n ), \n 'br_category_clause' => array( \n 'key' => 'br_category',\n ), \n 'br_name_clause' => array( \n 'key' => 'br_name',\n ) \n ), \n 'posts_per_page' => -1, \n\n 'meta_key' => array( 'br_category', 'br_name', 'br_type' ),\n // add sql: wp_postmeta.meta_key IN ('br_category','br_name','br_type') \n\n 'orderby' => array(\n 'br_type_clause' => 'ASC', \n 'br_category_clause' => 'ASC',\n 'br_name_clause' => 'ASC',\n 'name' => 'ASC', // illustrative purpose, could use post key\n ), \n // 'order' => 'ASC', // it is ignored with above orderby override\n 'fields' => 'ids'\n ),\n</code></pre>\n\n<p>which produce the SQL</p>\n\n<pre><code>SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND ( \n wp_postmeta.meta_key IN ('br_category','br_name','br_type') \n AND \n ( \n ( mt1.meta_key = 'br_type' AND mt1.meta_value = 'Aviation' ) \n AND \n mt2.meta_key = 'br_category' \n AND \n mt3.meta_key = 'br_name'\n )\n) AND wp_posts.post_type = 'brands' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC, CAST(mt3.meta_value AS CHAR) ASC, wp_posts.post_name ASC \n</code></pre>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a> with section <code>‘orderby’ with multiple ‘meta_key’s</code></p>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73096/"
] | I’m wondering if you could help with some code I’m struggling with.
I’ve got an ACF Image Field on the Post Category Taxonomy. I need to add it into the post loop so the category image shows up instead of the featured image. Here’s the code that I have in:
```
$current_term = get_queried_object();
$author_image = get_field('author_image', $current_term );
echo do_shortcode('[image_shortcode id="'.$author_image.'" image_size="original"]');
```
It’s working on the Category Archive page, but not on the Tags Archive page. Let me know your thoughts. | ### Current Query
```
$args = array(
'post_type' => 'brands',
'meta_query' => array(
array(
'key' => 'br_type',
'value' => 'Aviation'
),
array(
'key' => 'br_category'
),
array(
'key' => 'br_name'
)
),
'posts_per_page' => -1,
'orderby' => [ 'br_category' => 'ASC', 'br_name' => 'ASC' ],
'order' => 'ASC',
'fields' => 'ids'
);
```
produce this SQL query
```
'SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1
AND (
( wp_postmeta.meta_key = \'br_type\' AND wp_postmeta.meta_value = \'Aviation\' )
AND
mt1.meta_key = \'br_category\'
AND
mt2.meta_key = \'br_name\'
) AND wp_posts.post_type = \'brands\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'acf-disabled\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \'private\') GROUP BY wp_posts.ID '
```
It means it does not add any order by clause because it does not understand.
### Here is the correct way to order by multiple meta key value
```
$args = array(
'post_type' => 'brands',
'meta_query' => array(
// 'relation' => 'AND', // default is AND
'br_type_clause' => array(
'key' => 'br_type',
'value' => 'Aviation',
),
'br_category_clause' => array(
'key' => 'br_category',
),
'br_name_clause' => array(
'key' => 'br_name',
)
),
'posts_per_page' => -1,
'meta_key' => array( 'br_category', 'br_name', 'br_type' ),
// add sql: wp_postmeta.meta_key IN ('br_category','br_name','br_type')
'orderby' => array(
'br_type_clause' => 'ASC',
'br_category_clause' => 'ASC',
'br_name_clause' => 'ASC',
'name' => 'ASC', // illustrative purpose, could use post key
),
// 'order' => 'ASC', // it is ignored with above orderby override
'fields' => 'ids'
),
```
which produce the SQL
```
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND (
wp_postmeta.meta_key IN ('br_category','br_name','br_type')
AND
(
( mt1.meta_key = 'br_type' AND mt1.meta_value = 'Aviation' )
AND
mt2.meta_key = 'br_category'
AND
mt3.meta_key = 'br_name'
)
) AND wp_posts.post_type = 'brands' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC, CAST(mt3.meta_value AS CHAR) ASC, wp_posts.post_name ASC
```
Reference: [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/) with section `‘orderby’ with multiple ‘meta_key’s` |
366,719 | <p>This is my code:</p>
<pre><code> $wpdb->insert(
'wpbi_contacts',
array(
'regname' => $formData['regname'],
'razon' => $formData['razon'],
'email-1' => $formData['email-1'],
'descripcion' => $formData['descripcion'],
'categoria' => $formData['categoria'],
'nit' => $formData['nit'],
'telefono' => $formData['telefono'],
'departamento' => $formData['departamento'],
'ciudad' => $formData['ciudad'],
'direccion' => $formData['direccion'],
'lineanegocios' => $formData['lineanegocios'],
'paginaweb' => $formData['paginaweb'],
'facebook' => $formData['facebook'],
'instagram' => $formData['instagram'],
'productosyservicios' => $formData['productosyservicios'],
'certificaciones' => $formData['certificaciones'],
'esecologica' => $formData['esecologica'],
'nombreencargado' => $formData['nombreencargado'],
'telefonoencargado' => $formData['telefonoencargado'],
'emailencargado' => $formData['emailencargado'],
'departamentoencargado' => $formData['departamentoencargado'],
'ciudadencargado' => $formData['ciudadencargado'],
'direccionencargado' => $formData['direccionencargado'],
array('%s')
)
);
</code></pre>
<p>This is my log no errors:</p>
<pre><code>[15-May-2020 17:52:59 UTC] Array
(
[_wpcf7] => 2802
[_wpcf7_version] => 5.1.7
[_wpcf7_locale] => en_US
[_wpcf7_unit_tag] => wpcf7-f2802-p2718-o1
[_wpcf7_container_post] => 2718
[regname] => Precisoft Inc
[razon] => Diego Bonilla
[nit] => 8004561465
[telefono] => 4256873105
[email-1] => [email protected]
[departamento] => Granda
[ciudad] => ISSAQUAH
[direccion] => 20045 SE 127TH ST
[categoria] => Alimentos
[lineanegocios] => Productos
[descripcion] => xx
[paginaweb] => http://www.agro-vida.com
[facebook] => http://www.agro-vidfa.com
[instagram] => http://www.agro-vidfa.com
[productosyservicios] => xxx
[certificaciones] => xxxx
[esecologica] => xxxxx
[nombreencargado] => BONILLA DIEGO F (INT)
[telefonoencargado] => 14256873105
[emailencargado] => [email protected]
[departamentoencargado] => granda
[ciudadencargado] => ISSAQUAH
[direccionencargado] => 20045 SE 127TH ST
)
</code></pre>
<p>the row don't store in the table. all columns are varchar.
It worked at some point but stopped workng,</p>
<p>THANK YOU</p>
| [
{
"answer_id": 366720,
"author": "Bob",
"author_id": 188151,
"author_profile": "https://wordpress.stackexchange.com/users/188151",
"pm_score": -1,
"selected": false,
"text": "<p>Firstly what does it return? 0 for no rows inserted? or <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">false for error</a>?</p>\n\n<pre><code>$return_value = $wpdb->insert( ... );\nvar_dump($return_value);\n</code></pre>\n\n<p>Secondly, it looks malformed to me <code>array('%s')</code> is in your second argument but should be your third.</p>\n\n<pre><code>$wpdb->insert(\n 'wpbi_contacts',\n array(\n 'regname' => $formData['regname'],\n 'razon' => $formData['razon'],\n 'email-1' => $formData['email-1'],\n 'descripcion' => $formData['descripcion'],\n 'categoria' => $formData['categoria'],\n 'nit' => $formData['nit'],\n 'telefono' => $formData['telefono'], \n 'departamento' => $formData['departamento'],\n 'ciudad' => $formData['ciudad'],\n 'direccion' => $formData['direccion'],\n 'lineanegocios' => $formData['lineanegocios'],\n 'paginaweb' => $formData['paginaweb'],\n 'facebook' => $formData['facebook'],\n 'instagram' => $formData['instagram'], \n 'productosyservicios' => $formData['productosyservicios'],\n 'certificaciones' => $formData['certificaciones'],\n 'esecologica' => $formData['esecologica'],\n 'nombreencargado' => $formData['nombreencargado'],\n 'telefonoencargado' => $formData['telefonoencargado'], \n 'emailencargado' => $formData['emailencargado'],\n 'departamentoencargado' => $formData['departamentoencargado'],\n 'ciudadencargado' => $formData['ciudadencargado'],\n 'direccionencargado' => $formData['direccionencargado'],\n array('%s')\n )\n);\n</code></pre>\n"
},
{
"answer_id": 366724,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<p>It could also be the result of this known bug:</p>\n\n<p><a href=\"https://core.trac.wordpress.org/ticket/32315\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/32315</a></p>\n\n<p>If your data is larger than the varchar field length then $wpdb->insert will fail and produce no errors.</p>\n\n<p>If you don't mind data being truncated if it's larger than the field length, switch to $wpdb->query($wpdb->prepare(..)).</p>\n\n<p>Because of this stupid bug I haven't used insert in years.</p>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188172/"
] | This is my code:
```
$wpdb->insert(
'wpbi_contacts',
array(
'regname' => $formData['regname'],
'razon' => $formData['razon'],
'email-1' => $formData['email-1'],
'descripcion' => $formData['descripcion'],
'categoria' => $formData['categoria'],
'nit' => $formData['nit'],
'telefono' => $formData['telefono'],
'departamento' => $formData['departamento'],
'ciudad' => $formData['ciudad'],
'direccion' => $formData['direccion'],
'lineanegocios' => $formData['lineanegocios'],
'paginaweb' => $formData['paginaweb'],
'facebook' => $formData['facebook'],
'instagram' => $formData['instagram'],
'productosyservicios' => $formData['productosyservicios'],
'certificaciones' => $formData['certificaciones'],
'esecologica' => $formData['esecologica'],
'nombreencargado' => $formData['nombreencargado'],
'telefonoencargado' => $formData['telefonoencargado'],
'emailencargado' => $formData['emailencargado'],
'departamentoencargado' => $formData['departamentoencargado'],
'ciudadencargado' => $formData['ciudadencargado'],
'direccionencargado' => $formData['direccionencargado'],
array('%s')
)
);
```
This is my log no errors:
```
[15-May-2020 17:52:59 UTC] Array
(
[_wpcf7] => 2802
[_wpcf7_version] => 5.1.7
[_wpcf7_locale] => en_US
[_wpcf7_unit_tag] => wpcf7-f2802-p2718-o1
[_wpcf7_container_post] => 2718
[regname] => Precisoft Inc
[razon] => Diego Bonilla
[nit] => 8004561465
[telefono] => 4256873105
[email-1] => [email protected]
[departamento] => Granda
[ciudad] => ISSAQUAH
[direccion] => 20045 SE 127TH ST
[categoria] => Alimentos
[lineanegocios] => Productos
[descripcion] => xx
[paginaweb] => http://www.agro-vida.com
[facebook] => http://www.agro-vidfa.com
[instagram] => http://www.agro-vidfa.com
[productosyservicios] => xxx
[certificaciones] => xxxx
[esecologica] => xxxxx
[nombreencargado] => BONILLA DIEGO F (INT)
[telefonoencargado] => 14256873105
[emailencargado] => [email protected]
[departamentoencargado] => granda
[ciudadencargado] => ISSAQUAH
[direccionencargado] => 20045 SE 127TH ST
)
```
the row don't store in the table. all columns are varchar.
It worked at some point but stopped workng,
THANK YOU | It could also be the result of this known bug:
<https://core.trac.wordpress.org/ticket/32315>
If your data is larger than the varchar field length then $wpdb->insert will fail and produce no errors.
If you don't mind data being truncated if it's larger than the field length, switch to $wpdb->query($wpdb->prepare(..)).
Because of this stupid bug I haven't used insert in years. |
366,737 | <p>I have two functions displaying a term list of the selected taxonomy:</p>
<p>First function:</p>
<pre><code>$terms = get_the_terms(get_the_ID(), 'MY_TAXONOMY');
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms AS $term) {
$name = $term->name;
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.MYWEBSITE.com/');
echo "<a href='$link'>$name</a><br />";
}
}
</code></pre>
<p>Second function:</p>
<pre><code> global $post;
$taxonomy = 'MY_TAXONOMY';
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
</code></pre>
<p>The first one ignores the hierarchy, but transforms the links as I need, i.e. so that they lead to queries of the WP's Facet Plugin. I understand that this line is key here:</p>
<pre><code>$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.MYWEBSITE.com/');
</code></pre>
<p>The second one includes the hierarchy, but the links don't lead where I would like. How do I make this second function transform links like the first one?</p>
| [
{
"answer_id": 366742,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>This can be achieved multiple ways. One of them is to filter term link with your desired structure.</p>\n\n<p>Following is a function that can convert a term link as per your structure. Ignore the first argument, it is there as we will be using this function as a filter callback.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * @param string $termlink Term link.\n * @param WP_Term $term Term object.\n */\nfunction wpse366737_pre_term_link( $termlink, $term ) {\n return add_query_arg(\n 'fwp_typ', \n FWP()->helper->safe_value( $term->slug ), \n 'https://www.MYWEBSITE.com/'\n );\n}\n</code></pre>\n\n<p>Now, we have a function that we can use at appropriate place to modify term link. Once we are done, we will remove the filter so that other scripts using term link does not gets affected.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $post;\n\n$taxonomy = 'MY_TAXONOMY';\n\n$terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n\nif ( $terms ) {\n echo '<ul>';\n\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n\n // as we needed.\n add_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10, 2 );\n\n // this list will display the filtered url for term.\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n\n // remove the filter so other script doesn't get affected.\n remove_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10 );\n\n echo '</ul>';\n}\n</code></pre>\n"
},
{
"answer_id": 367007,
"author": "reti",
"author_id": 178440,
"author_profile": "https://wordpress.stackexchange.com/users/178440",
"pm_score": 1,
"selected": true,
"text": "<p>Solved ugly, but works. General form of the filter:</p>\n\n<pre><code><?php\nadd_filter('term_link', function ($termlink, $term, $taxonomy) {\n if ('CPT-TAXONOMY-NAME' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;\n }\n return $termlink;\n}, 10, 3);\n</code></pre>\n\n<p>The function in fuctions.php:</p>\n\n<pre><code><?php\nfunction list_hierarchical_terms($taxonomy) {\n global $post;\n $terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n if( $terms ) {\n echo '<?ul>';\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n echo '<?/ul>';\n }\n}\n</code></pre>\n\n<p>Now I don't know how to write it simpler. The functions for filter in functions.php:</p>\n\n<pre><code><?php\nfunction termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)\n{\n if ('freuciv_post_type' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_category($termlink, $term, $taxonomy)\n{\n if ('category' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)\n{\n if ('hierarchical_tags' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;\n }\n return $termlink;\n}\n</code></pre>\n\n<p>And in template-part:</p>\n\n<pre><code><?php\nadd_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);\nlist_hierarchical_terms('freuciv_post_type', '<h5 style=\"margin-bottom: 5px\">Typ: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );\n\nadd_filter('term_link', 'termlink_transformation_category', 10, 3);\nlist_hierarchical_terms('category', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Kategorien: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_category', 10 );\n\nadd_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);\nlist_hierarchical_terms('hierarchical_tags', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Tags: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 ); \n</code></pre>\n\n<p>There's too much repetition here. I have no idea how to simplify it.</p>\n"
}
] | 2020/05/15 | [
"https://wordpress.stackexchange.com/questions/366737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178440/"
] | I have two functions displaying a term list of the selected taxonomy:
First function:
```
$terms = get_the_terms(get_the_ID(), 'MY_TAXONOMY');
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms AS $term) {
$name = $term->name;
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.MYWEBSITE.com/');
echo "<a href='$link'>$name</a><br />";
}
}
```
Second function:
```
global $post;
$taxonomy = 'MY_TAXONOMY';
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
```
The first one ignores the hierarchy, but transforms the links as I need, i.e. so that they lead to queries of the WP's Facet Plugin. I understand that this line is key here:
```
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.MYWEBSITE.com/');
```
The second one includes the hierarchy, but the links don't lead where I would like. How do I make this second function transform links like the first one? | Solved ugly, but works. General form of the filter:
```
<?php
add_filter('term_link', function ($termlink, $term, $taxonomy) {
if ('CPT-TAXONOMY-NAME' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;
}
return $termlink;
}, 10, 3);
```
The function in fuctions.php:
```
<?php
function list_hierarchical_terms($taxonomy) {
global $post;
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
}
```
Now I don't know how to write it simpler. The functions for filter in functions.php:
```
<?php
function termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)
{
if ('freuciv_post_type' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_category($termlink, $term, $taxonomy)
{
if ('category' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)
{
if ('hierarchical_tags' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;
}
return $termlink;
}
```
And in template-part:
```
<?php
add_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);
list_hierarchical_terms('freuciv_post_type', '<h5 style="margin-bottom: 5px">Typ: </h5>');
remove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );
add_filter('term_link', 'termlink_transformation_category', 10, 3);
list_hierarchical_terms('category', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Kategorien: </h5>');
remove_filter( 'term_link', 'termlink_transformation_category', 10 );
add_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);
list_hierarchical_terms('hierarchical_tags', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Tags: </h5>');
remove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 );
```
There's too much repetition here. I have no idea how to simplify it. |
366,772 | <p>I have custom template and i need get og:image url in header.
Class image location in DB wp_postmeta - meta_value
i try with functions.php</p>
<pre><code>function getOgImage()
{
global $wpdb;
$ogimage = $wpdb->get_results("SELECT DISTINCT post_id FROM wp_postmeta WHERE meta_value", OBJECT);
echo '<meta property="og:image" content="'.$ogimage.'"/>';
}
add_action('wp_head', 'getOgImage');
</code></pre>
<p>Im geting out:</p>
<pre><code><meta property="og:image" content="Array" />
</code></pre>
| [
{
"answer_id": 366742,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>This can be achieved multiple ways. One of them is to filter term link with your desired structure.</p>\n\n<p>Following is a function that can convert a term link as per your structure. Ignore the first argument, it is there as we will be using this function as a filter callback.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * @param string $termlink Term link.\n * @param WP_Term $term Term object.\n */\nfunction wpse366737_pre_term_link( $termlink, $term ) {\n return add_query_arg(\n 'fwp_typ', \n FWP()->helper->safe_value( $term->slug ), \n 'https://www.MYWEBSITE.com/'\n );\n}\n</code></pre>\n\n<p>Now, we have a function that we can use at appropriate place to modify term link. Once we are done, we will remove the filter so that other scripts using term link does not gets affected.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $post;\n\n$taxonomy = 'MY_TAXONOMY';\n\n$terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n\nif ( $terms ) {\n echo '<ul>';\n\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n\n // as we needed.\n add_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10, 2 );\n\n // this list will display the filtered url for term.\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n\n // remove the filter so other script doesn't get affected.\n remove_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10 );\n\n echo '</ul>';\n}\n</code></pre>\n"
},
{
"answer_id": 367007,
"author": "reti",
"author_id": 178440,
"author_profile": "https://wordpress.stackexchange.com/users/178440",
"pm_score": 1,
"selected": true,
"text": "<p>Solved ugly, but works. General form of the filter:</p>\n\n<pre><code><?php\nadd_filter('term_link', function ($termlink, $term, $taxonomy) {\n if ('CPT-TAXONOMY-NAME' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;\n }\n return $termlink;\n}, 10, 3);\n</code></pre>\n\n<p>The function in fuctions.php:</p>\n\n<pre><code><?php\nfunction list_hierarchical_terms($taxonomy) {\n global $post;\n $terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n if( $terms ) {\n echo '<?ul>';\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n echo '<?/ul>';\n }\n}\n</code></pre>\n\n<p>Now I don't know how to write it simpler. The functions for filter in functions.php:</p>\n\n<pre><code><?php\nfunction termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)\n{\n if ('freuciv_post_type' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_category($termlink, $term, $taxonomy)\n{\n if ('category' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)\n{\n if ('hierarchical_tags' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;\n }\n return $termlink;\n}\n</code></pre>\n\n<p>And in template-part:</p>\n\n<pre><code><?php\nadd_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);\nlist_hierarchical_terms('freuciv_post_type', '<h5 style=\"margin-bottom: 5px\">Typ: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );\n\nadd_filter('term_link', 'termlink_transformation_category', 10, 3);\nlist_hierarchical_terms('category', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Kategorien: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_category', 10 );\n\nadd_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);\nlist_hierarchical_terms('hierarchical_tags', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Tags: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 ); \n</code></pre>\n\n<p>There's too much repetition here. I have no idea how to simplify it.</p>\n"
}
] | 2020/05/16 | [
"https://wordpress.stackexchange.com/questions/366772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188203/"
] | I have custom template and i need get og:image url in header.
Class image location in DB wp\_postmeta - meta\_value
i try with functions.php
```
function getOgImage()
{
global $wpdb;
$ogimage = $wpdb->get_results("SELECT DISTINCT post_id FROM wp_postmeta WHERE meta_value", OBJECT);
echo '<meta property="og:image" content="'.$ogimage.'"/>';
}
add_action('wp_head', 'getOgImage');
```
Im geting out:
```
<meta property="og:image" content="Array" />
``` | Solved ugly, but works. General form of the filter:
```
<?php
add_filter('term_link', function ($termlink, $term, $taxonomy) {
if ('CPT-TAXONOMY-NAME' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;
}
return $termlink;
}, 10, 3);
```
The function in fuctions.php:
```
<?php
function list_hierarchical_terms($taxonomy) {
global $post;
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
}
```
Now I don't know how to write it simpler. The functions for filter in functions.php:
```
<?php
function termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)
{
if ('freuciv_post_type' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_category($termlink, $term, $taxonomy)
{
if ('category' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)
{
if ('hierarchical_tags' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;
}
return $termlink;
}
```
And in template-part:
```
<?php
add_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);
list_hierarchical_terms('freuciv_post_type', '<h5 style="margin-bottom: 5px">Typ: </h5>');
remove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );
add_filter('term_link', 'termlink_transformation_category', 10, 3);
list_hierarchical_terms('category', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Kategorien: </h5>');
remove_filter( 'term_link', 'termlink_transformation_category', 10 );
add_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);
list_hierarchical_terms('hierarchical_tags', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Tags: </h5>');
remove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 );
```
There's too much repetition here. I have no idea how to simplify it. |
366,792 | <p>I'm trying to give guest users "not logged in" a role.</p>
<p>I searched everywhere and I could not find a single solution that can make that happen. All what I found is to make an if statement in the <code>functions.php</code> file to give access to certain things, like for example post a comment without logging in.</p>
<p>However when there are a lot of roles it's hard to make it that way and it starts to be complicated. </p>
<p>Is there any way that I can achieve that?</p>
<p>Things that I have used</p>
<pre><code>add_role( 'custom_role', 'Custom Role', array( 'read' => true ) );
</code></pre>
<p>and</p>
<pre><code> <?php
global $user_login;
if( $user_login ) {
echo 'user logged in';
} else {
echo 'user not logged in';
}
?>
</code></pre>
| [
{
"answer_id": 366742,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>This can be achieved multiple ways. One of them is to filter term link with your desired structure.</p>\n\n<p>Following is a function that can convert a term link as per your structure. Ignore the first argument, it is there as we will be using this function as a filter callback.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * @param string $termlink Term link.\n * @param WP_Term $term Term object.\n */\nfunction wpse366737_pre_term_link( $termlink, $term ) {\n return add_query_arg(\n 'fwp_typ', \n FWP()->helper->safe_value( $term->slug ), \n 'https://www.MYWEBSITE.com/'\n );\n}\n</code></pre>\n\n<p>Now, we have a function that we can use at appropriate place to modify term link. Once we are done, we will remove the filter so that other scripts using term link does not gets affected.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $post;\n\n$taxonomy = 'MY_TAXONOMY';\n\n$terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n\nif ( $terms ) {\n echo '<ul>';\n\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n\n // as we needed.\n add_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10, 2 );\n\n // this list will display the filtered url for term.\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n\n // remove the filter so other script doesn't get affected.\n remove_filter( 'pre_term_link', 'wpse366737_pre_term_link', 10 );\n\n echo '</ul>';\n}\n</code></pre>\n"
},
{
"answer_id": 367007,
"author": "reti",
"author_id": 178440,
"author_profile": "https://wordpress.stackexchange.com/users/178440",
"pm_score": 1,
"selected": true,
"text": "<p>Solved ugly, but works. General form of the filter:</p>\n\n<pre><code><?php\nadd_filter('term_link', function ($termlink, $term, $taxonomy) {\n if ('CPT-TAXONOMY-NAME' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;\n }\n return $termlink;\n}, 10, 3);\n</code></pre>\n\n<p>The function in fuctions.php:</p>\n\n<pre><code><?php\nfunction list_hierarchical_terms($taxonomy) {\n global $post;\n $terms = wp_get_post_terms( $post->ID, $taxonomy, array( \"fields\" => \"ids\" ) );\n if( $terms ) {\n echo '<?ul>';\n $terms = trim( implode( ',', (array) $terms ), ' ,' );\n wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );\n echo '<?/ul>';\n }\n}\n</code></pre>\n\n<p>Now I don't know how to write it simpler. The functions for filter in functions.php:</p>\n\n<pre><code><?php\nfunction termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)\n{\n if ('freuciv_post_type' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_category($termlink, $term, $taxonomy)\n{\n if ('category' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;\n }\n return $termlink;\n}\n\nfunction termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)\n{\n if ('hierarchical_tags' == $taxonomy) {\n $termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;\n }\n return $termlink;\n}\n</code></pre>\n\n<p>And in template-part:</p>\n\n<pre><code><?php\nadd_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);\nlist_hierarchical_terms('freuciv_post_type', '<h5 style=\"margin-bottom: 5px\">Typ: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );\n\nadd_filter('term_link', 'termlink_transformation_category', 10, 3);\nlist_hierarchical_terms('category', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Kategorien: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_category', 10 );\n\nadd_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);\nlist_hierarchical_terms('hierarchical_tags', '<h5 style=\"margin-bottom: 5px; margin-top: 10px;\">Tags: </h5>');\nremove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 ); \n</code></pre>\n\n<p>There's too much repetition here. I have no idea how to simplify it.</p>\n"
}
] | 2020/05/16 | [
"https://wordpress.stackexchange.com/questions/366792",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188227/"
] | I'm trying to give guest users "not logged in" a role.
I searched everywhere and I could not find a single solution that can make that happen. All what I found is to make an if statement in the `functions.php` file to give access to certain things, like for example post a comment without logging in.
However when there are a lot of roles it's hard to make it that way and it starts to be complicated.
Is there any way that I can achieve that?
Things that I have used
```
add_role( 'custom_role', 'Custom Role', array( 'read' => true ) );
```
and
```
<?php
global $user_login;
if( $user_login ) {
echo 'user logged in';
} else {
echo 'user not logged in';
}
?>
``` | Solved ugly, but works. General form of the filter:
```
<?php
add_filter('term_link', function ($termlink, $term, $taxonomy) {
if ('CPT-TAXONOMY-NAME' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?FACETWP-FACET-NAME=' . $term->slug;
}
return $termlink;
}, 10, 3);
```
The function in fuctions.php:
```
<?php
function list_hierarchical_terms($taxonomy) {
global $post;
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
}
```
Now I don't know how to write it simpler. The functions for filter in functions.php:
```
<?php
function termlink_transformation_freuciv_post_type($termlink, $term, $taxonomy)
{
if ('freuciv_post_type' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_typ=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_category($termlink, $term, $taxonomy)
{
if ('category' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_categories=' . $term->slug;
}
return $termlink;
}
function termlink_transformation_hierarchical_tags($termlink, $term, $taxonomy)
{
if ('hierarchical_tags' == $taxonomy) {
$termlink = trailingslashit(get_home_url()) . '?fwp_tags=' . $term->slug;
}
return $termlink;
}
```
And in template-part:
```
<?php
add_filter('term_link', 'termlink_transformation_freuciv_post_type', 10, 3);
list_hierarchical_terms('freuciv_post_type', '<h5 style="margin-bottom: 5px">Typ: </h5>');
remove_filter( 'term_link', 'termlink_transformation_freuciv_post_type', 10 );
add_filter('term_link', 'termlink_transformation_category', 10, 3);
list_hierarchical_terms('category', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Kategorien: </h5>');
remove_filter( 'term_link', 'termlink_transformation_category', 10 );
add_filter('term_link', 'termlink_transformation_hierarchical_tags', 10, 3);
list_hierarchical_terms('hierarchical_tags', '<h5 style="margin-bottom: 5px; margin-top: 10px;">Tags: </h5>');
remove_filter( 'term_link', 'termlink_transformation_hierarchical_tags', 10 );
```
There's too much repetition here. I have no idea how to simplify it. |
366,798 | <p><strong>What I'm trying to do</strong></p>
<ol>
<li>Changing the login-URL from <code>https://example.org/wp-login</code> to <code>https://example.org/mellon</code></li>
<li>Making <code>https://example.org/wp-login</code> redirect to the 404-page. </li>
</ol>
<hr>
<p><strong>Considerations</strong></p>
<p>If I Google it, then I find a <a href="https://www.elegantthemes.com/blog/resources/how-to-obscure-your-sites-login-page-without-a-plugin" rel="nofollow noreferrer">couple of suggestions</a>, where <code>/wp-admin/wp-login.php</code> is renamed/changed. Which obviously is a terrible idea (reasons: Never change core! + It will reset upon updating WordPress). </p>
<p>I'm currently using <a href="https://wordpress.org/plugins/wp-cerber/" rel="nofollow noreferrer">WP Cerber</a> which has it as an option to change the login-URL. But for some reason, then the option doesn't work. </p>
<p>I know that can most likely find a plugin that does this. But I hate installing plugins for simple things, to avoid having a bazillion plugins.</p>
<p>I would prefer not to do it in the <code>.htaccess</code>-file, since I don't commit that to my code-respository. </p>
<p>Can it be done from <code>functions.php</code>? </p>
| [
{
"answer_id": 366803,
"author": "rank",
"author_id": 178642,
"author_profile": "https://wordpress.stackexchange.com/users/178642",
"pm_score": 0,
"selected": false,
"text": "<p>It is not a good idea to change your login url without a plugin, because you will need to have to mess around with WP core files. So changing the login url is not a \"simple thing\" as you call it, but pretty complex.</p>\n\n<p>I guess there is a reason WP shows you a way to create a new login form, but does not tell you how to change it completely. If you are interested: <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Make_a_Custom_Login_Page\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Customizing_the_Login_Form#Make_a_Custom_Login_Page</a></p>\n\n<p><strong>Using a plugin is the safer way to change the login url of wordpress.</strong></p>\n\n<p>So there is a great plugin for this: <a href=\"https://wordpress.org/plugins/wps-hide-login/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wps-hide-login/</a></p>\n\n<p>It is very lightweight and does the one and only thing you want: Hide the wp-login and wp-admin and use a name you choose. Not bloating your installation with unneeded things, but doing a good job for the one use it was made for.</p>\n\n<p>Go to Settings -> Gerneral, or alternatively to Settings -> WPS Hide Login to change the login url.</p>\n\n<p>It is important that you remember your new url or set a bookmark, otherwise you will not be able to find your new login page.</p>\n\n<p>I know you wanted a solution for your functions.php. I don't think there is one, and I also would recommend to use a plugin because it will solve the issue in a better and safer way.</p>\n"
},
{
"answer_id": 366839,
"author": "Ujjawal Poonia",
"author_id": 187916,
"author_profile": "https://wordpress.stackexchange.com/users/187916",
"pm_score": 2,
"selected": false,
"text": "<p>You should change the login url from default than it'll hard for hackers to find the login page so it'll be safe for you.</p>\n\n<p>Here is the code to change the url.</p>\n\n<pre><code>\n// Add rewrite rule and flush on plugin activation\nregister_activation_hook( __FILE__, 'NLURL_activate' );\nfunction NLURL_activate() {\n NLURL_rewrite();\n flush_rewrite_rules();\n}\n\n// Flush on plugin deactivation\nregister_deactivation_hook( __FILE__, 'NLURL_deactivate' );\nfunction NLURL_deactivate() {\n flush_rewrite_rules();\n}\n\n// Create new rewrite rule\nadd_action( 'init', 'NLURL_rewrite' );\nfunction NLURL_rewrite() {\n add_rewrite_rule( 'login/?$', 'wp-login.php', 'top' );\n add_rewrite_rule( 'register/?$', 'wp-login.php?action=register', 'top' );\n add_rewrite_rule( 'forgot/?$', 'wp-login.php?action=lostpassword', 'top' );\n}\n\n\n//register url fix\nadd_filter('register','fix_register_url');\nfunction fix_register_url($link){\n return str_replace(site_url('wp-login.php?action=register', 'login'),site_url('register', 'login'),$link);\n}\n\n//login url fix\nadd_filter('login_url','fix_login_url');\nfunction fix_login_url($link){\n return str_replace(site_url('wp-login.php', 'login'),site_url('login', 'login'),$link);\n}\n\n//forgot password url fix\nadd_filter('lostpassword_url','fix_lostpass_url');\nfunction fix_lostpass_url($link){\n return str_replace('?action=lostpassword','',str_replace(network_site_url('wp-login.php', 'login'),site_url('forgot', 'login'),$link));\n}\n\n//Site URL hack to overwrite register url\nadd_filter('site_url','fix_urls',10,3);\nfunction fix_urls($url, $path, $orig_scheme){\n if ($orig_scheme !== 'login')\n return $url;\n if ($path == 'wp-login.php?action=register')\n return site_url('register', 'login');\n\n return $url;\n}\n</code></pre>\n"
}
] | 2020/05/16 | [
"https://wordpress.stackexchange.com/questions/366798",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | **What I'm trying to do**
1. Changing the login-URL from `https://example.org/wp-login` to `https://example.org/mellon`
2. Making `https://example.org/wp-login` redirect to the 404-page.
---
**Considerations**
If I Google it, then I find a [couple of suggestions](https://www.elegantthemes.com/blog/resources/how-to-obscure-your-sites-login-page-without-a-plugin), where `/wp-admin/wp-login.php` is renamed/changed. Which obviously is a terrible idea (reasons: Never change core! + It will reset upon updating WordPress).
I'm currently using [WP Cerber](https://wordpress.org/plugins/wp-cerber/) which has it as an option to change the login-URL. But for some reason, then the option doesn't work.
I know that can most likely find a plugin that does this. But I hate installing plugins for simple things, to avoid having a bazillion plugins.
I would prefer not to do it in the `.htaccess`-file, since I don't commit that to my code-respository.
Can it be done from `functions.php`? | You should change the login url from default than it'll hard for hackers to find the login page so it'll be safe for you.
Here is the code to change the url.
```
// Add rewrite rule and flush on plugin activation
register_activation_hook( __FILE__, 'NLURL_activate' );
function NLURL_activate() {
NLURL_rewrite();
flush_rewrite_rules();
}
// Flush on plugin deactivation
register_deactivation_hook( __FILE__, 'NLURL_deactivate' );
function NLURL_deactivate() {
flush_rewrite_rules();
}
// Create new rewrite rule
add_action( 'init', 'NLURL_rewrite' );
function NLURL_rewrite() {
add_rewrite_rule( 'login/?$', 'wp-login.php', 'top' );
add_rewrite_rule( 'register/?$', 'wp-login.php?action=register', 'top' );
add_rewrite_rule( 'forgot/?$', 'wp-login.php?action=lostpassword', 'top' );
}
//register url fix
add_filter('register','fix_register_url');
function fix_register_url($link){
return str_replace(site_url('wp-login.php?action=register', 'login'),site_url('register', 'login'),$link);
}
//login url fix
add_filter('login_url','fix_login_url');
function fix_login_url($link){
return str_replace(site_url('wp-login.php', 'login'),site_url('login', 'login'),$link);
}
//forgot password url fix
add_filter('lostpassword_url','fix_lostpass_url');
function fix_lostpass_url($link){
return str_replace('?action=lostpassword','',str_replace(network_site_url('wp-login.php', 'login'),site_url('forgot', 'login'),$link));
}
//Site URL hack to overwrite register url
add_filter('site_url','fix_urls',10,3);
function fix_urls($url, $path, $orig_scheme){
if ($orig_scheme !== 'login')
return $url;
if ($path == 'wp-login.php?action=register')
return site_url('register', 'login');
return $url;
}
``` |
366,867 | <p>How do I add some guiding text under the 'Featured Image'. </p>
<p>Right here: </p>
<p><a href="https://i.stack.imgur.com/02KfA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/02KfA.png" alt="Guiding text for featured image"></a></p>
<p>I have experienced several times now that people don't get where and what this is. So it could be nice to be able to add a line or two. </p>
<hr>
<p>If I Google it, then I just get a bazillion pages about how to display the caption in the frontend. :-/ </p>
| [
{
"answer_id": 366870,
"author": "rank",
"author_id": 178642,
"author_profile": "https://wordpress.stackexchange.com/users/178642",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using the Classic Editor of wordpress, there is a function for this:\n<a href=\"https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_html/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_html/</a></p>\n\n<p>So the code would be (example from link):</p>\n\n<pre><code>function filter_featured_image_admin_text( $content, $post_id, $thumbnail_id ){\n $help_text = '<p>' . __( 'Please use an image that is 1170 pixels wide x 658\n pixels tall.', 'my_textdomain' ) . '</p>';\n return $help_text . $content;\n}\nadd_filter( 'admin_post_thumbnail_html', 'filter_featured_image_admin_text', 10, 3 );\n</code></pre>\n\n<p>Remember to set the textdomain of your theme.</p>\n\n<hr>\n\n<p>If you are using the Gutenberg editor, this is a litte more complex. The filter does not seem to work for gutenberg. \nAs it is made with React JS, I assume it is working differently. Maybe this link can help you:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image#postfeaturedimage\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image#postfeaturedimage</a></p>\n\n<p>Moreover I found something that can really help you:</p>\n\n<p><a href=\"https://thatdevgirl.com/blog/wordpress-featured-image-and-gutenberg\" rel=\"nofollow noreferrer\">https://thatdevgirl.com/blog/wordpress-featured-image-and-gutenberg</a></p>\n\n<p>This tutorial can guide you how to adjust the featured image box with filters for gutenberg editor.</p>\n\n<p>Hope this is a starting point for you, if you want to use Gutenberg.</p>\n\n<hr>\n\n<p>You can also create a custom field of the type of image (Plugin -> Advanced Custom Fields) and use this for the image output in your template. This way you can style the box as you want, add description or whatever you like.</p>\n"
},
{
"answer_id": 366871,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using the classic editor you could try this function:</p>\n\n<pre><code>function custom_admin_post_thumbnail_html( $content ) {\n return $content = str_replace( __( 'Set featured image' ), __( 'better feature image guide text' ), $content); \n}\nadd_filter( 'admin_post_thumbnail_html', 'custom_admin_post_thumbnail_html' );\n</code></pre>\n\n<p>Just replace the \"better feature image guide text\" with whatever you want.</p>\n"
}
] | 2020/05/17 | [
"https://wordpress.stackexchange.com/questions/366867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | How do I add some guiding text under the 'Featured Image'.
Right here:
[](https://i.stack.imgur.com/02KfA.png)
I have experienced several times now that people don't get where and what this is. So it could be nice to be able to add a line or two.
---
If I Google it, then I just get a bazillion pages about how to display the caption in the frontend. :-/ | Are you using the classic editor you could try this function:
```
function custom_admin_post_thumbnail_html( $content ) {
return $content = str_replace( __( 'Set featured image' ), __( 'better feature image guide text' ), $content);
}
add_filter( 'admin_post_thumbnail_html', 'custom_admin_post_thumbnail_html' );
```
Just replace the "better feature image guide text" with whatever you want. |
366,881 | <p>I have followed the instructions for internationalization on: <a href="https://developer.wordpress.org/block-editor/developers/internationalization/" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/developers/internationalization/</a>, but it doesn't seem to play well with the development tools for Gutenberg. It will find all the translations in the <code>src</code> directory in the multiple <code>js</code> files and will use that as the relative paths while the <code>npm run build</code> will make one <code>build/index.js</code> file which I am enqueueing. The <code>wp i18n make-json languages --no-purge</code> will create multiple files which the MD5 won't work (probably because of the relative paths) and I can't name them al <code>${domain}-${local}-${handler}.json</code>.</p>
<hr>
<p>To have a better understanding what I mean. I now have the following:</p>
<pre><code>npm init
npm i --save-dev --save-exact @wordpress/scripts
mkdir build
mkdir src
cd src
touch index.js
touch edit.js
</code></pre>
<p><strong>index.js</strong></p>
<pre><code>import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import edit from './edit.js';
registerBlockType( 'gbg/myguten', {
title: __( "My Gutenberg Example", "gbg" ),
category: "widgets",
edit
} );
</code></pre>
<p><strong>edit.js</strong></p>
<pre><code>import { __ } from '@wordpress/i18n';
export default () => (<h1>{ __( "Hello World", "gbg" ) }</h1>);
</code></pre>
<p>I then generate the translations:</p>
<pre><code>mkdir lang
wp i18n make-pot ./ lang/myguten.pot
cp myguten.pot myguten-en_US.po
wp i18n make-json myguten-en_US.po --no-purge
</code></pre>
<p>This will generate multiple json files, while I rather have one combined json file. <code>npm run build</code> will generate one index.js file which I use to register in WordPress.</p>
<pre><code>/**
* Plugin Name: My Guten
* Text Domain: gbg
*/
function gbg_myguten_block_init() {
load_plugin_textdomain( 'gbg', false, dirname( plugin_basename(__FILE__) ) . '/lang/' );
wp_register_script(
'gbg-myguten-script',
plugins_url( 'build/index.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-i18n' ),
time(),
true
);
register_block_type(
'gbg/myguten',
array(
'editor_script' => 'gbg-myguten-script',
)
);
wp_set_script_translations( 'gbg-myguten-script', 'gbg', plugin_dir_path( __FILE__ ) . 'lang' );
}
add_action( 'init', 'gbg_myguten_block_init' );
</code></pre>
<p>Now it will search for <code>${domain}-${locale}-${handle}.json</code> while multiple json files exist.</p>
| [
{
"answer_id": 367910,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p><em>(I revised this answer mainly to let other readers and you know the issues I originally noticed in your steps as shown in the question.)</em></p>\n\n<p>So in my original answer, I was focused on suggesting you to just go with the multiple script translation files, but I thought I should clarify the three things below:</p>\n\n<blockquote>\n <p>It will find all the translations in the <code>src</code> directory in the multiple <code>js</code> files and will use that as the relative paths while the <code>npm run build</code> will make one <code>build/index.js</code> file which I am enqueueing.</p>\n</blockquote>\n\n<ul>\n<li><p>Yes, <a href=\"https://developer.wordpress.org/cli/commands/i18n/make-json/\" rel=\"nofollow noreferrer\"><code>wp i18n make-json</code></a> will create one <a href=\"https://messageformat.github.io/Jed/\" rel=\"nofollow noreferrer\">JED</a>-formatted JSON file <em>per JavaScript source file</em> — <a href=\"https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/\" rel=\"nofollow noreferrer\">more details on Make WordPress</a>.</p></li>\n<li><p>As with the <code>npm run build</code> (which uses the <a href=\"https://developer.wordpress.org/block-editor/packages/packages-scripts/\" rel=\"nofollow noreferrer\"><code>wp-scripts</code> package</a>), it — as far as I know — only builds JavaScript source files (<code>.js</code>) and not JED files which are JSON files. (There is a JS linter and other tools, though.)</p></li>\n</ul>\n\n<blockquote>\n <p>The <code>wp i18n make-json</code> will create multiple files which the MD5 won't work (probably because of the relative paths)</p>\n</blockquote>\n\n<ul>\n<li><p>The files would work so long as you give the proper file name to your PO files where the format is <code>${domain}-${locale}.po</code> (see <a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/#loading-text-domain\" rel=\"nofollow noreferrer\">Plugin Handbook » Loading Text Domain</a>) — e.g. <code>my-plugin-it_IT.po</code> if the <em>text domain</em> is <code>my-plugin</code> and the <em>locale</em> is set to <code>it_IT</code> (Italiano).</p>\n\n<p>But then, you used the wrong text domain, e.g. with the command <code>wp i18n make-pot ./ lang/myguten.pot</code>, you should've used <code>gbg</code> and not <code>myguten</code> because the <code>Text Domain</code> in your plugin header is <code>gbg</code> (i.e. <code>Text Domain: gbg</code>).</p>\n\n<p>Additionally, your <code>cp</code> (\"copy\") command should have been preceded by <code>cd lang</code>.</p></li>\n<li><p>As with the MD5 thing, it is the MD5 hash of the JS source file path as you can see in the PO file — so the path is (or <em>should be</em>) relative to the plugin folder.</p>\n\n<p>E.g. Structure of my sample plugin:</p>\n\n<pre><code>wpse-366881/\n build/\n index.js <- relative path = build/index.js\n lang/\n src/\n edit.js <- relative path = src/edit.js\n index.js <- relative path = src/index.js\n index.php\n package.json\n</code></pre></li>\n</ul>\n\n<blockquote>\n <p>I rather have one combined JSON file.</p>\n</blockquote>\n\n<ul>\n<li>In that case, you can use <a href=\"https://github.com/mikeedwards/po2json\" rel=\"nofollow noreferrer\"><code>po2json</code></a> and <a href=\"https://www.npmjs.com/package/npx\" rel=\"nofollow noreferrer\"><code>npx</code></a> to run the executable <code>po2json</code> file.</li>\n</ul>\n\n<h2>So how should you internationalize JavaScript spread in multiple files but <em>build in one</em>?</h2>\n\n<p>Just follow the steps in the question, except:</p>\n\n<ol>\n<li><p>Make sure the translation files (POT, PO, MO and JED/JSON) — i.e. the code inside and the file names — are using the text domain as defined in the <em>plugin header</em>. Additionally, put all the translation files in the correct directory.</p>\n\n<p>E.g. <code>wp i18n make-pot ./ lang/gbg.pot</code></p></li>\n<li><p>There's no need to run the <code>wp i18n make-json</code> command which creates the multiple files, and just use <code>po2json</code> to create a single JED/JSON file from a PO file.</p>\n\n<p>And the command for that is: (Note that as of writing, WordPress uses JED 1.x)</p>\n\n<p><code>npx po2json <path to PO file> <path to JSON file> -f jed1.x</code></p>\n\n<p>E.g. <code>npx po2json lang/gbg-en_US.po lang/gbg-en_US-gbg-myguten-script.json -f jed1.x</code></p></li>\n</ol>\n\n<h2>Sample Plugin I used for testing purposes (and for other readers to try)</h2>\n\n<p>You can find it <a href=\"https://github.com/5ally/wpse-366881\" rel=\"nofollow noreferrer\">on GitHub</a> — <em>tried & tested working on WordPress 5.4.1, with the site locale/language set to <code>it_IT</code>/Italiano.</em> And the code are basically all based on your code, except in <code>index.php</code>, I used the <code>build/index.asset.php</code> file to <a href=\"https://developer.wordpress.org/block-editor/tutorials/javascript/js-build-setup/#dependency-management\" rel=\"nofollow noreferrer\">automatically load dependencies and version</a>.</p>\n\n<p>And btw, the plugin was initially based on <a href=\"https://github.com/WordPress/gutenberg-examples/tree/master/01-basic-esnext\" rel=\"nofollow noreferrer\">the example here</a>.</p>\n"
},
{
"answer_id": 367935,
"author": "Mark",
"author_id": 8757,
"author_profile": "https://wordpress.stackexchange.com/users/8757",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>With the help I got from the marked answer written by Sally CJ I was\n able to write this answer which is a more compact version of what I\n was looking for as an answer.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>I am using the dutch locale (nl_NL) in the samples below,\n but feel free to use any other locale instead like it_IT or en_US.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>The <code>make-pot</code> WP CLI command only does the expected job when used in\n the root directory of your theme or plugin. This is also where the\n file lives that contains the <a href=\"https://developer.wordpress.org/plugins/plugin-basics/header-requirements/\" rel=\"nofollow noreferrer\">Plugin</a> or <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">Theme</a> header.</p>\n</blockquote>\n\n<hr>\n\n<p>To get the expected result run the following commands:</p>\n\n<pre><code>1. wp i18n make-pot .\n2. cp ./languages/my-plugin-slug.pot ./languages/my-plugin-slug-nl_NL.po\n3. npx po2json languages/my-plugin-slug-nl_NL.po languages/my-plugin-slug-nl_NL-my-plugin-script-handler.json -f jed1.x; \n</code></pre>\n\n<p>In your plugin PHP-file use the following code:</p>\n\n<pre><code>function register_block_my_gutenberg_block() {\n load_plugin_textdomain( 'my-plugin-slug', false, plugin_dir_path( __FILE__ ) . 'languages' ); \n\n $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php' );\n\n wp_register_script(\n 'my-plugin-script-handler',\n plugin_dir_url( __FILE__ ) . 'build/index.js',\n $asset_file['dependencies'],\n $asset_file['version'],\n true\n );\n\n register_block_type(\n 'my-namespace/my-gutenberg-block',\n array(\n 'editor_script' => 'my-plugin-script-handler'\n )\n );\n\n wp_set_script_translations( \n 'my-plugin-script-handler', \n 'my-plugin-slug',\n plugin_dir_path( __FILE__ ) . 'languages' \n );\n}\n\nadd_action( 'init', 'register_block_my_gutenberg_block' );\n</code></pre>\n\n<p>As written in the documentation, <a href=\"https://developer.wordpress.org/plugins/plugin-basics/header-requirements/\" rel=\"nofollow noreferrer\">How to Internationalize Your Plugin</a>, \"The text domain must match the slug of the plugin\". That's why <code>my-plugin-slug</code> is used in the places marked for text-domain.</p>\n\n<p><strong>PoEdit</strong></p>\n\n<p>You can also use PoEdit for translation. Just use the <code>make-pot</code> as described above in step 1 and then open the newly create pot file in PoEdit. Create the translation and save it as <code>my-plugin-slug-nl_NL.po</code>. Then use the command in step 3 to generate the <code>.json</code>-file.</p>\n\n<p><strong>Package.json</strong></p>\n\n<p>You can make life a little bit easier by adding <code>make-pot</code> and <code>make-json</code> to your <code>package.json</code> file. Now if you <code>npm run make-pot</code>, the pot file is created. Use it to translate. Then use <code>npm run make-json</code> to create the json files for all the <code>.po</code> files. Make sure you change the <code>my-plugin-handler.json</code> to the name of your script handler defined in your PHP file with <code>wp_register_script</code>. </p>\n\n<pre><code> \"scripts\": {\n \"build\": \"wp-scripts build\",\n \"format:js\": \"wp-scripts format-js\",\n \"lint:js\": \"wp-scripts lint-js src\",\n \"packages-update\": \"wp-scripts packages-update\",\n \"start\": \"wp-scripts start\",\n \"make-pot\": \"wp i18n make-pot .\",\n \"make-json\": \"find . -iname \\\"*.po\\\" -type f -exec sh -c 'npx po2json $0 $(dirname $0)/$(basename $0 .po)-my-plugin-script-handler.json -f jed1.x' {} \\\\;\"\n },\n</code></pre>\n"
},
{
"answer_id": 393792,
"author": "Hasan Akhtar",
"author_id": 56444,
"author_profile": "https://wordpress.stackexchange.com/users/56444",
"pm_score": 0,
"selected": false,
"text": "<p>Other answers here suggest the use of <code>npx po2json</code> instead of <code>wp i18n make-json</code> but that might not be ideal for everyone because <code>wp i18n make-json</code> is the standard way of generating json files. Here's how you make it work:</p>\n<ul>\n<li>Make sure you use the @wordpress/scripts to build your JS. This package uses webpack behind the scenes and all the translation functions are already preserved so the make-pot scanner can scan them. More about this package: <a href=\"https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/#advanced-usage\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/#advanced-usage</a></li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/NwDUE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NwDUE.png\" alt=\"enter image description here\" /></a></p>\n<ul>\n<li><p>When running the make-pot command, explicitly include the JS build directory and exclude the JS source directory: <code>wp i18n make-pot ./ languages/domain.pot --exclude=path/to/js/src --include=path/to/js/build/ --ignore-domain</code>. Now your POT file will only reference the generated files that are actually enqueued on the page.</p>\n</li>\n<li><p>Run make-json. The md5 hashes of the generated JSON files will correctly reference the actual scripts loaded on the page.</p>\n</li>\n</ul>\n"
}
] | 2020/05/17 | [
"https://wordpress.stackexchange.com/questions/366881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8757/"
] | I have followed the instructions for internationalization on: <https://developer.wordpress.org/block-editor/developers/internationalization/>, but it doesn't seem to play well with the development tools for Gutenberg. It will find all the translations in the `src` directory in the multiple `js` files and will use that as the relative paths while the `npm run build` will make one `build/index.js` file which I am enqueueing. The `wp i18n make-json languages --no-purge` will create multiple files which the MD5 won't work (probably because of the relative paths) and I can't name them al `${domain}-${local}-${handler}.json`.
---
To have a better understanding what I mean. I now have the following:
```
npm init
npm i --save-dev --save-exact @wordpress/scripts
mkdir build
mkdir src
cd src
touch index.js
touch edit.js
```
**index.js**
```
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import edit from './edit.js';
registerBlockType( 'gbg/myguten', {
title: __( "My Gutenberg Example", "gbg" ),
category: "widgets",
edit
} );
```
**edit.js**
```
import { __ } from '@wordpress/i18n';
export default () => (<h1>{ __( "Hello World", "gbg" ) }</h1>);
```
I then generate the translations:
```
mkdir lang
wp i18n make-pot ./ lang/myguten.pot
cp myguten.pot myguten-en_US.po
wp i18n make-json myguten-en_US.po --no-purge
```
This will generate multiple json files, while I rather have one combined json file. `npm run build` will generate one index.js file which I use to register in WordPress.
```
/**
* Plugin Name: My Guten
* Text Domain: gbg
*/
function gbg_myguten_block_init() {
load_plugin_textdomain( 'gbg', false, dirname( plugin_basename(__FILE__) ) . '/lang/' );
wp_register_script(
'gbg-myguten-script',
plugins_url( 'build/index.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-i18n' ),
time(),
true
);
register_block_type(
'gbg/myguten',
array(
'editor_script' => 'gbg-myguten-script',
)
);
wp_set_script_translations( 'gbg-myguten-script', 'gbg', plugin_dir_path( __FILE__ ) . 'lang' );
}
add_action( 'init', 'gbg_myguten_block_init' );
```
Now it will search for `${domain}-${locale}-${handle}.json` while multiple json files exist. | *(I revised this answer mainly to let other readers and you know the issues I originally noticed in your steps as shown in the question.)*
So in my original answer, I was focused on suggesting you to just go with the multiple script translation files, but I thought I should clarify the three things below:
>
> It will find all the translations in the `src` directory in the multiple `js` files and will use that as the relative paths while the `npm run build` will make one `build/index.js` file which I am enqueueing.
>
>
>
* Yes, [`wp i18n make-json`](https://developer.wordpress.org/cli/commands/i18n/make-json/) will create one [JED](https://messageformat.github.io/Jed/)-formatted JSON file *per JavaScript source file* — [more details on Make WordPress](https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/).
* As with the `npm run build` (which uses the [`wp-scripts` package](https://developer.wordpress.org/block-editor/packages/packages-scripts/)), it — as far as I know — only builds JavaScript source files (`.js`) and not JED files which are JSON files. (There is a JS linter and other tools, though.)
>
> The `wp i18n make-json` will create multiple files which the MD5 won't work (probably because of the relative paths)
>
>
>
* The files would work so long as you give the proper file name to your PO files where the format is `${domain}-${locale}.po` (see [Plugin Handbook » Loading Text Domain](https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/#loading-text-domain)) — e.g. `my-plugin-it_IT.po` if the *text domain* is `my-plugin` and the *locale* is set to `it_IT` (Italiano).
But then, you used the wrong text domain, e.g. with the command `wp i18n make-pot ./ lang/myguten.pot`, you should've used `gbg` and not `myguten` because the `Text Domain` in your plugin header is `gbg` (i.e. `Text Domain: gbg`).
Additionally, your `cp` ("copy") command should have been preceded by `cd lang`.
* As with the MD5 thing, it is the MD5 hash of the JS source file path as you can see in the PO file — so the path is (or *should be*) relative to the plugin folder.
E.g. Structure of my sample plugin:
```
wpse-366881/
build/
index.js <- relative path = build/index.js
lang/
src/
edit.js <- relative path = src/edit.js
index.js <- relative path = src/index.js
index.php
package.json
```
>
> I rather have one combined JSON file.
>
>
>
* In that case, you can use [`po2json`](https://github.com/mikeedwards/po2json) and [`npx`](https://www.npmjs.com/package/npx) to run the executable `po2json` file.
So how should you internationalize JavaScript spread in multiple files but *build in one*?
------------------------------------------------------------------------------------------
Just follow the steps in the question, except:
1. Make sure the translation files (POT, PO, MO and JED/JSON) — i.e. the code inside and the file names — are using the text domain as defined in the *plugin header*. Additionally, put all the translation files in the correct directory.
E.g. `wp i18n make-pot ./ lang/gbg.pot`
2. There's no need to run the `wp i18n make-json` command which creates the multiple files, and just use `po2json` to create a single JED/JSON file from a PO file.
And the command for that is: (Note that as of writing, WordPress uses JED 1.x)
`npx po2json <path to PO file> <path to JSON file> -f jed1.x`
E.g. `npx po2json lang/gbg-en_US.po lang/gbg-en_US-gbg-myguten-script.json -f jed1.x`
Sample Plugin I used for testing purposes (and for other readers to try)
------------------------------------------------------------------------
You can find it [on GitHub](https://github.com/5ally/wpse-366881) — *tried & tested working on WordPress 5.4.1, with the site locale/language set to `it_IT`/Italiano.* And the code are basically all based on your code, except in `index.php`, I used the `build/index.asset.php` file to [automatically load dependencies and version](https://developer.wordpress.org/block-editor/tutorials/javascript/js-build-setup/#dependency-management).
And btw, the plugin was initially based on [the example here](https://github.com/WordPress/gutenberg-examples/tree/master/01-basic-esnext). |
366,938 | <p>I've tried to setup my wordpress using 1 domain name and 1 ip address,
after this, all the css is missing, but the site still can be accessible using both domain and ip address.</p>
<p><a href="https://i.stack.imgur.com/zuonp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zuonp.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Esldh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Esldh.png" alt="enter image description here"></a></p>
<p>Then I tried to revert back to either ip only or domain only, the css all became normal again</p>
<p>So is there any fix to get the css back to normal with 2 address set in wp_option? </p>
<p>Webserver : Nginx (I have tested for days, I can safe to say there is no problem with the webserver)</p>
<p><a href="https://i.stack.imgur.com/a9jCa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a9jCa.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/gkh91.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gkh91.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 366947,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": -1,
"selected": false,
"text": "<p>You can't put multiple addresses in those options fields, that's not how it works. Anything other than a single address will result in a broken site.</p>\n\n<p>Out of the box, on a singular site, WP will serve pages to any address, the issue you face is that the URLs in the page source will all contain absolute URLs rather than relative URLs.</p>\n\n<p>Instead, consider focusing on your actual problem that you mentioned in your comment, rather than how to implement a speculative solution, that of configuring your VPN</p>\n"
},
{
"answer_id": 367072,
"author": "iwanttosleep",
"author_id": 188347,
"author_profile": "https://wordpress.stackexchange.com/users/188347",
"pm_score": 1,
"selected": true,
"text": "<p>After testing for hours, finally get it done. </p>\n\n<p>Here the solution:\nIn database <code>wp_options</code> change the value for <code>siteurl</code> and <code>home</code> from <code>your wordpress url</code> to <code>/path/to/wordpress</code> </p>\n\n<p><strong>Wordpress URL</strong>\n<a href=\"https://i.stack.imgur.com/OXoEC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OXoEC.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Path To Wordpress</strong>\n<a href=\"https://i.stack.imgur.com/py79U.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/py79U.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then add these code in the bottom of <code>wp-config.php</code></p>\n\n<pre><code>define('WP_HOME', 'http://' .$_SERVER['HTTP_HOST'].'/');\ndefine('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/' );\n</code></pre>\n\n<p>Now you can use Domain and IP together to access your wordpress. Of course you need to setup your webserver to listen to both </p>\n\n<p>*It is not my VPN limitation though, just because I can and I think this is more cool.</p>\n"
}
] | 2020/05/18 | [
"https://wordpress.stackexchange.com/questions/366938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188347/"
] | I've tried to setup my wordpress using 1 domain name and 1 ip address,
after this, all the css is missing, but the site still can be accessible using both domain and ip address.
[](https://i.stack.imgur.com/zuonp.png)
[](https://i.stack.imgur.com/Esldh.png)
Then I tried to revert back to either ip only or domain only, the css all became normal again
So is there any fix to get the css back to normal with 2 address set in wp\_option?
Webserver : Nginx (I have tested for days, I can safe to say there is no problem with the webserver)
[](https://i.stack.imgur.com/a9jCa.png)
[](https://i.stack.imgur.com/gkh91.png) | After testing for hours, finally get it done.
Here the solution:
In database `wp_options` change the value for `siteurl` and `home` from `your wordpress url` to `/path/to/wordpress`
**Wordpress URL**
[](https://i.stack.imgur.com/OXoEC.png)
**Path To Wordpress**
[](https://i.stack.imgur.com/py79U.png)
Then add these code in the bottom of `wp-config.php`
```
define('WP_HOME', 'http://' .$_SERVER['HTTP_HOST'].'/');
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/' );
```
Now you can use Domain and IP together to access your wordpress. Of course you need to setup your webserver to listen to both
\*It is not my VPN limitation though, just because I can and I think this is more cool. |
366,946 | <p>I have a question. I want to get all my post but when I visit <a href="http://example.com/feed/atom/" rel="nofollow noreferrer">http://example.com/feed/atom/</a> I have only three post. In my website there are much more than three. How to update this file?</p>
<p>Kind regards </p>
| [
{
"answer_id": 366947,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": -1,
"selected": false,
"text": "<p>You can't put multiple addresses in those options fields, that's not how it works. Anything other than a single address will result in a broken site.</p>\n\n<p>Out of the box, on a singular site, WP will serve pages to any address, the issue you face is that the URLs in the page source will all contain absolute URLs rather than relative URLs.</p>\n\n<p>Instead, consider focusing on your actual problem that you mentioned in your comment, rather than how to implement a speculative solution, that of configuring your VPN</p>\n"
},
{
"answer_id": 367072,
"author": "iwanttosleep",
"author_id": 188347,
"author_profile": "https://wordpress.stackexchange.com/users/188347",
"pm_score": 1,
"selected": true,
"text": "<p>After testing for hours, finally get it done. </p>\n\n<p>Here the solution:\nIn database <code>wp_options</code> change the value for <code>siteurl</code> and <code>home</code> from <code>your wordpress url</code> to <code>/path/to/wordpress</code> </p>\n\n<p><strong>Wordpress URL</strong>\n<a href=\"https://i.stack.imgur.com/OXoEC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OXoEC.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Path To Wordpress</strong>\n<a href=\"https://i.stack.imgur.com/py79U.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/py79U.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then add these code in the bottom of <code>wp-config.php</code></p>\n\n<pre><code>define('WP_HOME', 'http://' .$_SERVER['HTTP_HOST'].'/');\ndefine('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/' );\n</code></pre>\n\n<p>Now you can use Domain and IP together to access your wordpress. Of course you need to setup your webserver to listen to both </p>\n\n<p>*It is not my VPN limitation though, just because I can and I think this is more cool.</p>\n"
}
] | 2020/05/18 | [
"https://wordpress.stackexchange.com/questions/366946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188359/"
] | I have a question. I want to get all my post but when I visit <http://example.com/feed/atom/> I have only three post. In my website there are much more than three. How to update this file?
Kind regards | After testing for hours, finally get it done.
Here the solution:
In database `wp_options` change the value for `siteurl` and `home` from `your wordpress url` to `/path/to/wordpress`
**Wordpress URL**
[](https://i.stack.imgur.com/OXoEC.png)
**Path To Wordpress**
[](https://i.stack.imgur.com/py79U.png)
Then add these code in the bottom of `wp-config.php`
```
define('WP_HOME', 'http://' .$_SERVER['HTTP_HOST'].'/');
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/' );
```
Now you can use Domain and IP together to access your wordpress. Of course you need to setup your webserver to listen to both
\*It is not my VPN limitation though, just because I can and I think this is more cool. |
366,989 | <p>Currently, the way I do it is, on the <code>plugins_loaded</code> hook, I let the world know that my plugin has loaded:</p>
<pre><code>add_action( 'plugins_loaded', function() {
do_action( 'my_plugin_has_loaded' );
}, 10 );
</code></pre>
<p>And so, others can depend/only run when <code>my_plugin_has_loaded</code> fires, however, I see a lot of hooks <code>plugin_loaded</code> (5.1.0) and even some <strong>plugins firing their <code>init</code> before <code>plugins_loaded</code></strong>. Is there a better way to make a plugin wait for another?</p>
<p>The problem I see with this approach is that I launch my own init on <code>plugins_loaded</code>, however, I also see a silver lining - plugins are meant to be done loading here, so, if there'd be any type of logic like this, it'd be here.</p>
<hr>
<p>Issue #1 - Using <code>class_exists</code>:</p>
<ol>
<li>I can't force naming conventions as I would do for actions, such as always looking/hooking for <code>plugin-$name%:init</code> to ensure consistency through actions. If I know a plugin's name, then I can very easily predict it's init point so that I can run after, but if I don't, I have to know what class is its main controller, which leads me to the next point - </li>
<li><p>If I rely on this way of checking, <strong>I am merely looking for the existence of a class, which, at best, lets me know a plugin is activated, but not if the plugin has finished its setup.</strong> With an action I can arbitrarily decide when a plugin has finished loading and initializing all it needs such that dependants can run.</p></li>
<li><p>Continuing from (2), I am now forcing myself to write plugins in such a way that I'd always need a god-mode-controller class that runs all its stuff on <code>__construct</code>. People who will do <code>class_exists( 'MyClass\From\Plugin\IWanna\DependOn' )</code>will also inherently assume that I run everything on <code>__construct</code>, <strong>however, my plugin my have errors in initializing itself, but, because it's all run on __cosntruct, I can't debug that.</strong></p></li>
</ol>
<p>Issue #2 - Using TGMPA:</p>
<ol>
<li>Assume plugin <code>A</code> dependend on plugin <code>B</code>. If the user disables <code>B</code>, then <code>A</code> will throw errors. Sure, I can handle them, but that's exactly the point of the question, really - reverse this point I just said and you reach my problem: ensuring dependency while handling each case in which you interact with plugins. I need this to be completely off user-land territory.</li>
</ol>
| [
{
"answer_id": 367527,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 2,
"selected": false,
"text": "<p>Consider plugin A:</p>\n\n<pre>\n$A_message;\n\nadd_action('plugins_loaded', function() {\n do_action('plugin-A:init');\n});\n\n// Hooks allow B to access A (both during initialization of A and elsewhere in WordPress) without having to check if A exists.\n\nadd_filter('plugin-A:set', function($msg) {\n $A_message = $msg;\n}, PHP_INT_MAX);\n\nadd_filter('plugin-A:get', function($msg) {\n return $A_message;\n}, PHP_INT_MIN);\n</pre>\n\n<p>Now, consider plugin B:</p>\n\n<pre>\nadd_action('plugin-A:init', function() {\n // We're 100% sure that A has loaded (if it exists)\n // Store what Cheech says in A. (Using a filter allows us to not have to check if A exists).\n do_action('plugin-A:set', \"Brent! Open the door!\");\n});\n\nadd_filter('the_title', function($title) {\n // Get something from A (and we don't have to check if it exists).\n // If A exists, return what Cheech says; if A does not exist, return what Chong says.\n $title = apply_filters('plugin-A:get', \"Dave's not here, man!\");\n return $title;\n});\n</pre>\n\n<p>Most of this code sounds like it is nothing new to you. When Foo is loaded, it initializes the Bar plugin by way of <code>bar_on_plugins_loaded()</code> and <code>foo_load_bar()</code>. What is new here is that Foo does not need to do any fancy checks to see if Bar exists or not. This is because <code>foo_load_bar()</code> executes a <em>hook</em> that is defined by Bar instead of a property of Bar itself. (Pretty cool, huh?)</p>\n\n<p>Later on in your code when a title is requested (like in post list tables) <code>foo_get_bar_message()</code> and <code>bar_get_message()</code> will return Bar's value that was set during the initialization of Bar by way of <code>bar_set_message()</code>. Again, this is all done without the Foo plugin having to check for Bar's existence. And, in the event that Bar does not exist, the Foo default will be returned. (Special thanks to <a href=\"https://www.youtube.com/watch?v=rtDAK7Umk7A\" rel=\"nofollow noreferrer\">Cheech and Chong</a> for the inspiration.)</p>\n\n<p><strong>Edit:</strong> In the above example, B depends more on A than the other way around. But, you asked for A depending on B and the same concept holds true here. Consider this <em>addition</em> to plugin A:</p>\n\n<pre>\n// This function is used somewhere in plugin-A ...\nfunction a_func() {\n // Not sure if B exists, but we can make B do something if it does.\n do_actions('plugin-B:some_func', '*knock knock knock*', 'Who Is It?');\n}\n</pre>\n\n<p>And this <em>addition</em> to plugin B:</p>\n\n<pre>\nadd_action('plugin-B:some_func', function($cheech, $chong) {\n echo '<p>'. $cheech .'<br>'. $chong .'</p>';\n}\n</pre>\n\n<p>In addition to B (if it exists) turning all the titles into either Dave or Brent's message, the beginning of Cheech and Chong's skit will output by plugin A when it calls its <code>a_func()</code> somewhere later on in its own code. As per your desire, A need not do anything to check if plugin B exists.</p>\n"
},
{
"answer_id": 367553,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 2,
"selected": false,
"text": "<p>I've had this initial build that worked, even before the question. I've now seen @cjbj's answer as well as Mort's. Mort is on the same frequency, however, hear me out:</p>\n\n<p>Inside my main plugin <code>A</code>, which <code>B</code> will depend on, inside <code>index.php</code>:</p>\n\n<pre><code>add_actions( 'plugins_loaded', function() {\n $boot = (new Init)->boot();\n\n if( \\is_wp_error( $boot ) ) {\n return False;\n }\n\n /**\n * Fire if the plugin has successfully loaded itself.\n */\n do_action( 'plugin-A:init' );\n});\n</code></pre>\n\n<p>Inside <code>index.php</code> of plugin <code>B</code>:</p>\n\n<pre><code>add_action( 'plugin-A:init', function() {\n //Great, so, we're 100% sure that A has successfully loaded.\n});\n</code></pre>\n\n<p>I genuinely can't find any issues with this BUT hooking onto <code>plugins_loaded</code> smells weird. Am I just being paranoid for no reason?</p>\n"
},
{
"answer_id": 367638,
"author": "Mohamed Omar",
"author_id": 102224,
"author_profile": "https://wordpress.stackexchange.com/users/102224",
"pm_score": 0,
"selected": false,
"text": "<p>Actually i use something very simple, because i have a plugin which i depend on for multiple purposes, developing themes/plugins, so i just define a constant inside it (e.g THE_CONSTANT), then say i have another plugin which depends on it for multiple operations which may <code>plugins_loaded</code> may not help, so just after the plugin definition i check if that constant is defined, if not!? just terminate the script, and you will then have only the plugin is listed in plugins page but like it is a brand new empty plugin. once the plugin been depended on is active the dependent just work fine.</p>\n\n<p>Something like this:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Plugin name\n */\n\n/**\n * Display a notification if one of required plugins is not activated/installed\n */\nadd_action( 'admin_notices', function() {\n if (!defined('THE_CONSTANT')) {\n ?>\n <div class=\"notice notice-error is-dismissible\">\n <p><?php esc_html_e( 'Please activate/install {Wanted plugin name} , for this plugin can work properly' ); ?></p>\n </div>\n <?php }\n});\n\n\nif (!defined(\"THE_CONSTANT\")) return;\n</code></pre>\n"
}
] | 2020/05/19 | [
"https://wordpress.stackexchange.com/questions/366989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185900/"
] | Currently, the way I do it is, on the `plugins_loaded` hook, I let the world know that my plugin has loaded:
```
add_action( 'plugins_loaded', function() {
do_action( 'my_plugin_has_loaded' );
}, 10 );
```
And so, others can depend/only run when `my_plugin_has_loaded` fires, however, I see a lot of hooks `plugin_loaded` (5.1.0) and even some **plugins firing their `init` before `plugins_loaded`**. Is there a better way to make a plugin wait for another?
The problem I see with this approach is that I launch my own init on `plugins_loaded`, however, I also see a silver lining - plugins are meant to be done loading here, so, if there'd be any type of logic like this, it'd be here.
---
Issue #1 - Using `class_exists`:
1. I can't force naming conventions as I would do for actions, such as always looking/hooking for `plugin-$name%:init` to ensure consistency through actions. If I know a plugin's name, then I can very easily predict it's init point so that I can run after, but if I don't, I have to know what class is its main controller, which leads me to the next point -
2. If I rely on this way of checking, **I am merely looking for the existence of a class, which, at best, lets me know a plugin is activated, but not if the plugin has finished its setup.** With an action I can arbitrarily decide when a plugin has finished loading and initializing all it needs such that dependants can run.
3. Continuing from (2), I am now forcing myself to write plugins in such a way that I'd always need a god-mode-controller class that runs all its stuff on `__construct`. People who will do `class_exists( 'MyClass\From\Plugin\IWanna\DependOn' )`will also inherently assume that I run everything on `__construct`, **however, my plugin my have errors in initializing itself, but, because it's all run on \_\_cosntruct, I can't debug that.**
Issue #2 - Using TGMPA:
1. Assume plugin `A` dependend on plugin `B`. If the user disables `B`, then `A` will throw errors. Sure, I can handle them, but that's exactly the point of the question, really - reverse this point I just said and you reach my problem: ensuring dependency while handling each case in which you interact with plugins. I need this to be completely off user-land territory. | Consider plugin A:
```
$A_message;
add_action('plugins_loaded', function() {
do_action('plugin-A:init');
});
// Hooks allow B to access A (both during initialization of A and elsewhere in WordPress) without having to check if A exists.
add_filter('plugin-A:set', function($msg) {
$A_message = $msg;
}, PHP_INT_MAX);
add_filter('plugin-A:get', function($msg) {
return $A_message;
}, PHP_INT_MIN);
```
Now, consider plugin B:
```
add_action('plugin-A:init', function() {
// We're 100% sure that A has loaded (if it exists)
// Store what Cheech says in A. (Using a filter allows us to not have to check if A exists).
do_action('plugin-A:set', "Brent! Open the door!");
});
add_filter('the_title', function($title) {
// Get something from A (and we don't have to check if it exists).
// If A exists, return what Cheech says; if A does not exist, return what Chong says.
$title = apply_filters('plugin-A:get', "Dave's not here, man!");
return $title;
});
```
Most of this code sounds like it is nothing new to you. When Foo is loaded, it initializes the Bar plugin by way of `bar_on_plugins_loaded()` and `foo_load_bar()`. What is new here is that Foo does not need to do any fancy checks to see if Bar exists or not. This is because `foo_load_bar()` executes a *hook* that is defined by Bar instead of a property of Bar itself. (Pretty cool, huh?)
Later on in your code when a title is requested (like in post list tables) `foo_get_bar_message()` and `bar_get_message()` will return Bar's value that was set during the initialization of Bar by way of `bar_set_message()`. Again, this is all done without the Foo plugin having to check for Bar's existence. And, in the event that Bar does not exist, the Foo default will be returned. (Special thanks to [Cheech and Chong](https://www.youtube.com/watch?v=rtDAK7Umk7A) for the inspiration.)
**Edit:** In the above example, B depends more on A than the other way around. But, you asked for A depending on B and the same concept holds true here. Consider this *addition* to plugin A:
```
// This function is used somewhere in plugin-A ...
function a_func() {
// Not sure if B exists, but we can make B do something if it does.
do_actions('plugin-B:some_func', '*knock knock knock*', 'Who Is It?');
}
```
And this *addition* to plugin B:
```
add_action('plugin-B:some_func', function($cheech, $chong) {
echo '<p>'. $cheech .'<br>'. $chong .'</p>';
}
```
In addition to B (if it exists) turning all the titles into either Dave or Brent's message, the beginning of Cheech and Chong's skit will output by plugin A when it calls its `a_func()` somewhere later on in its own code. As per your desire, A need not do anything to check if plugin B exists. |
367,004 | <p>I need to redirect about 200 post into category "ricette","svezzamento" and "alimentazione" to url without category. I have this code but not work.</p>
<pre><code>add_action('template_redirect', 'post_redirect_by_custom_filters');
function post_redirect_by_custom_filters() {
global $post;
$catArray = ['ricette','svezzamento','alimentazione'];
if (is_single($post->ID) && has_category($catArray, $post){
$new_url = "https://www.example.com/{$post->post_name}/";
wp_redirect($new_url, 301);
exit;
}
}
</code></pre>
| [
{
"answer_id": 367017,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming your URLs are of the form <code>/<category>/<post-name>/</code> (trailing slash optional) then an <code>.htaccess</code> only solution would look something like the following, at the <em>top</em> of your <code>.htaccess</code> file:</p>\n<pre><code># Remove some categories from the URL\nRewriteRule ^(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]\n</code></pre>\n<p>The <code>$2</code> backreference (in the <code>RewriteRule</code> <em>substitution</em>) matches the <code><post-name></code> from the requested URL.</p>\n<p>It is preferable to first test with 302 (temporary) redirects in order to avoid potential caching issues.</p>\n<blockquote>\n<p><code>https://www.example.com/la-crescita/ricette/name-post</code> and I need go to <code>https://www.example.com/name-post</code></p>\n<p>yes "la-crescita" is the first category and "ricette" is the subcategory of "la-crescita". File .htaccess is in the root of WordPress</p>\n</blockquote>\n<p>If <code>/la-crescita</code> is always the main <em>category</em> and "ricette", "svezzamento" and "alimentazione" and <em>subcategories</em> of this main category then you need to modify the above directive to include the <em>category</em>. For example:</p>\n<pre><code>RewriteRule ^la-crescita/(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 367035,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update site permalink structure from \"/%category%/%postname%/\" to \"/%postname%/\".</p>\n\n<p>To update the permalinks Goto: Settings > Permalink</p>\n"
}
] | 2020/05/19 | [
"https://wordpress.stackexchange.com/questions/367004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185581/"
] | I need to redirect about 200 post into category "ricette","svezzamento" and "alimentazione" to url without category. I have this code but not work.
```
add_action('template_redirect', 'post_redirect_by_custom_filters');
function post_redirect_by_custom_filters() {
global $post;
$catArray = ['ricette','svezzamento','alimentazione'];
if (is_single($post->ID) && has_category($catArray, $post){
$new_url = "https://www.example.com/{$post->post_name}/";
wp_redirect($new_url, 301);
exit;
}
}
``` | Assuming your URLs are of the form `/<category>/<post-name>/` (trailing slash optional) then an `.htaccess` only solution would look something like the following, at the *top* of your `.htaccess` file:
```
# Remove some categories from the URL
RewriteRule ^(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]
```
The `$2` backreference (in the `RewriteRule` *substitution*) matches the `<post-name>` from the requested URL.
It is preferable to first test with 302 (temporary) redirects in order to avoid potential caching issues.
>
> `https://www.example.com/la-crescita/ricette/name-post` and I need go to `https://www.example.com/name-post`
>
>
> yes "la-crescita" is the first category and "ricette" is the subcategory of "la-crescita". File .htaccess is in the root of WordPress
>
>
>
If `/la-crescita` is always the main *category* and "ricette", "svezzamento" and "alimentazione" and *subcategories* of this main category then you need to modify the above directive to include the *category*. For example:
```
RewriteRule ^la-crescita/(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]
``` |
367,034 | <p>In WordPress I have a post with URL <code>https://www.example.com/article.html</code>.</p>
<p>I renamed its permalink to <code>https://www.example.com/article-new.html</code>.</p>
<p>Now if I open the old URL <code>https://www.example.com/article.html</code> then it auto 301 redirects to <code>https://www.example.com/article-new.html</code>
due to the WordPress built-in feature by default.</p>
<p>However, I want to show a 404 when someone tries to open <code>https://www.example.com/article.html</code>.</p>
<p>I tried putting this in <code>.htaccess</code> but it gives a 500 server error instead:</p>
<pre><code>RewriteEngine On
Redirect 404 /article.html
</code></pre>
<p>Please advise.</p>
| [
{
"answer_id": 367017,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming your URLs are of the form <code>/<category>/<post-name>/</code> (trailing slash optional) then an <code>.htaccess</code> only solution would look something like the following, at the <em>top</em> of your <code>.htaccess</code> file:</p>\n<pre><code># Remove some categories from the URL\nRewriteRule ^(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]\n</code></pre>\n<p>The <code>$2</code> backreference (in the <code>RewriteRule</code> <em>substitution</em>) matches the <code><post-name></code> from the requested URL.</p>\n<p>It is preferable to first test with 302 (temporary) redirects in order to avoid potential caching issues.</p>\n<blockquote>\n<p><code>https://www.example.com/la-crescita/ricette/name-post</code> and I need go to <code>https://www.example.com/name-post</code></p>\n<p>yes "la-crescita" is the first category and "ricette" is the subcategory of "la-crescita". File .htaccess is in the root of WordPress</p>\n</blockquote>\n<p>If <code>/la-crescita</code> is always the main <em>category</em> and "ricette", "svezzamento" and "alimentazione" and <em>subcategories</em> of this main category then you need to modify the above directive to include the <em>category</em>. For example:</p>\n<pre><code>RewriteRule ^la-crescita/(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 367035,
"author": "Yash Tiwari",
"author_id": 185348,
"author_profile": "https://wordpress.stackexchange.com/users/185348",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update site permalink structure from \"/%category%/%postname%/\" to \"/%postname%/\".</p>\n\n<p>To update the permalinks Goto: Settings > Permalink</p>\n"
}
] | 2020/05/19 | [
"https://wordpress.stackexchange.com/questions/367034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/176970/"
] | In WordPress I have a post with URL `https://www.example.com/article.html`.
I renamed its permalink to `https://www.example.com/article-new.html`.
Now if I open the old URL `https://www.example.com/article.html` then it auto 301 redirects to `https://www.example.com/article-new.html`
due to the WordPress built-in feature by default.
However, I want to show a 404 when someone tries to open `https://www.example.com/article.html`.
I tried putting this in `.htaccess` but it gives a 500 server error instead:
```
RewriteEngine On
Redirect 404 /article.html
```
Please advise. | Assuming your URLs are of the form `/<category>/<post-name>/` (trailing slash optional) then an `.htaccess` only solution would look something like the following, at the *top* of your `.htaccess` file:
```
# Remove some categories from the URL
RewriteRule ^(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]
```
The `$2` backreference (in the `RewriteRule` *substitution*) matches the `<post-name>` from the requested URL.
It is preferable to first test with 302 (temporary) redirects in order to avoid potential caching issues.
>
> `https://www.example.com/la-crescita/ricette/name-post` and I need go to `https://www.example.com/name-post`
>
>
> yes "la-crescita" is the first category and "ricette" is the subcategory of "la-crescita". File .htaccess is in the root of WordPress
>
>
>
If `/la-crescita` is always the main *category* and "ricette", "svezzamento" and "alimentazione" and *subcategories* of this main category then you need to modify the above directive to include the *category*. For example:
```
RewriteRule ^la-crescita/(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]
``` |
367,062 | <p>I'm working on my first wordpress site, and moving it online. I have been adding some extra templates to design a simple booking engine, that was working perfectly on my offline localhost server.</p>
<p>However, I've been having trouble with getting these templates and other .php-files to work on the live website. It seems that using a specific path to locate the template or file doesn't work; <code>get_template_part()</code> and <code>include()</code> can only load the template/file when it is in the same folder. </p>
<p>For example, I have a page template called 'Bevestigingstemplate.php' in my Child-theme's folder (Theme-child), that I activated on one of my web pages. In this template, I want to call a file called 'bevestiging.php', that's located in Theme-child/modules/content. </p>
<p>However, if I call <code>get_template_part('modules/content/bevestiging')</code> OR <code>include('modules/content/bevestiging')</code>, it fails and I get a broken page.
If however I move 'bevestiging.php' directly into my Child-theme's folder and call <code>get_template_part('bevestiging')</code>, it works like a charm. </p>
<p>Now I don't want to end up with a chaotic list of templates and sub-templates in my Child-theme folder, so I'm desperately looking for a way to fix this. I've read somewhere that I should maybe add a config.php file in my Child-theme's folder that defines a 'root', but I couldn't find a clear walkthrough and was hoping to maybe fix it in an easier way, or at least first to understand where I'm going wrong here. </p>
<p>Any advice on how to proceed is welcomed warmly. Thanks!</p>
<p>Below is the code I use in Bevestigingstemplate.php (basically just copied page.php from main theme).</p>
<pre><code>get_header(); ?>
<div id="primary" class="content-area <?php do_action('adviso_primary-width'); ?>">
<main id="main" class="site-main">
<?php
get_template_part('modules/content/bevestiging');
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
</code></pre>
| [
{
"answer_id": 367063,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": true,
"text": "<p>What you're looking for is <a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory/\" rel=\"nofollow noreferrer\">get_stylesheet_directory()</a>.</p>\n\n<pre><code>get_template_part( get_stylesheet_directory() . '/modules/content/bevestiging.php');\n</code></pre>\n\n<p>This gives you the file path for the current theme.</p>\n"
},
{
"answer_id": 367064,
"author": "AmLam",
"author_id": 182507,
"author_profile": "https://wordpress.stackexchange.com/users/182507",
"pm_score": -1,
"selected": false,
"text": "<p>In the end, the main problem was an 'include' in my bevestiging.php-file. I solved that by using <code>include __DIR__ . '/../../Includes/form.php'</code>.\nThanks for the support!</p>\n"
}
] | 2020/05/19 | [
"https://wordpress.stackexchange.com/questions/367062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182507/"
] | I'm working on my first wordpress site, and moving it online. I have been adding some extra templates to design a simple booking engine, that was working perfectly on my offline localhost server.
However, I've been having trouble with getting these templates and other .php-files to work on the live website. It seems that using a specific path to locate the template or file doesn't work; `get_template_part()` and `include()` can only load the template/file when it is in the same folder.
For example, I have a page template called 'Bevestigingstemplate.php' in my Child-theme's folder (Theme-child), that I activated on one of my web pages. In this template, I want to call a file called 'bevestiging.php', that's located in Theme-child/modules/content.
However, if I call `get_template_part('modules/content/bevestiging')` OR `include('modules/content/bevestiging')`, it fails and I get a broken page.
If however I move 'bevestiging.php' directly into my Child-theme's folder and call `get_template_part('bevestiging')`, it works like a charm.
Now I don't want to end up with a chaotic list of templates and sub-templates in my Child-theme folder, so I'm desperately looking for a way to fix this. I've read somewhere that I should maybe add a config.php file in my Child-theme's folder that defines a 'root', but I couldn't find a clear walkthrough and was hoping to maybe fix it in an easier way, or at least first to understand where I'm going wrong here.
Any advice on how to proceed is welcomed warmly. Thanks!
Below is the code I use in Bevestigingstemplate.php (basically just copied page.php from main theme).
```
get_header(); ?>
<div id="primary" class="content-area <?php do_action('adviso_primary-width'); ?>">
<main id="main" class="site-main">
<?php
get_template_part('modules/content/bevestiging');
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
``` | What you're looking for is [get\_stylesheet\_directory()](https://developer.wordpress.org/reference/functions/get_stylesheet_directory/).
```
get_template_part( get_stylesheet_directory() . '/modules/content/bevestiging.php');
```
This gives you the file path for the current theme. |
367,129 | <p>I'm quite new to doing api calls using Wordpress so bear with me.</p>
<p>I have this function:</p>
<pre><code>function foo() {
$userinfo = [
"number" => "26246426",
"secondnumber" => "43634643"
];
$api_url = 'https://api.url.com';
$response = wp_remote_post( $api_url, array(
// Set the Content-Type header.
'headers' => array(
'Content-Type' => 'application/json',
),
// Set the request payload/body.
'body' => json_encode( $userinfo ),
) );
$res_body = wp_remote_retrieve_body( $response );
echo $res_body;
die();
}
</code></pre>
<p>This works and I get a response.</p>
<p>Now what I'm trying to do is send the response in an action towards my ajax that's in a script right under the php function from above (everything is happening inside a plugin file)</p>
<p>Here are my actions </p>
<pre><code>add_action('wp_ajax_add_foo', 'foo' );
add_action('wp_ajax_nopriv_add_foo', 'foo' );
</code></pre>
<p>And my ajax call inside a script tag under the function</p>
<pre><code>var ajaxscript = { ajax_url : 'mywebsite.com/wp-admin/admin-ajax.php' }
jQuery(document).ready(function($) {
$.ajax ({
url: ajaxscript.ajax_url,
type: 'POST',
// dataType: 'application/json',
data: {
// the value of data.action is the part AFTER 'wp_ajax_' in
// the add_action ('wp_ajax_xxx', 'yyy') in the PHP above
action: '_add_foo'
// ANY other properties of data are passed to your_function()
// in the PHP global $_REQUEST (or $_POST in this case)
},
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
}) ;
});
</code></pre>
<p>I would be expecting to get back the $res_body variable but I'm getting a 400. Why is that?</p>
| [
{
"answer_id": 367158,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": -1,
"selected": false,
"text": "<p>Your ajax url is incorrect. </p>\n\n<p>Try changing: </p>\n\n<pre><code>var ajaxscript = { ajax_url : 'mywebsite.com/wp-admin/admin-ajax.php' }\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>var ajax_url = \"<?php echo admin_url('admin-ajax.php'); ?>\";\n</code></pre>\n\n<p>And change: <code>url: ajaxscript.ajax_url,</code> to <code>url: ajax_url,</code></p>\n\n<p>But the proper way to do this is by using <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">wp_localize_script</a></p>\n"
},
{
"answer_id": 367189,
"author": "ionitalex",
"author_id": 188504,
"author_profile": "https://wordpress.stackexchange.com/users/188504",
"pm_score": 1,
"selected": true,
"text": "<p>I figured this out after a night sleep. Sometimes our brains function like that.</p>\n\n<p>The problem was actually my call here, It should've been \"add_foo\" not \"_add_foo\"</p>\n\n<pre><code> data: {\n // the value of data.action is the part AFTER 'wp_ajax_' in\n // the add_action ('wp_ajax_xxx', 'yyy') in the PHP above\n action: '_add_foo'\n // ANY other properties of data are passed to your_function()\n // in the PHP global $_REQUEST (or $_POST in this case)\n\n },\n</code></pre>\n"
}
] | 2020/05/20 | [
"https://wordpress.stackexchange.com/questions/367129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188504/"
] | I'm quite new to doing api calls using Wordpress so bear with me.
I have this function:
```
function foo() {
$userinfo = [
"number" => "26246426",
"secondnumber" => "43634643"
];
$api_url = 'https://api.url.com';
$response = wp_remote_post( $api_url, array(
// Set the Content-Type header.
'headers' => array(
'Content-Type' => 'application/json',
),
// Set the request payload/body.
'body' => json_encode( $userinfo ),
) );
$res_body = wp_remote_retrieve_body( $response );
echo $res_body;
die();
}
```
This works and I get a response.
Now what I'm trying to do is send the response in an action towards my ajax that's in a script right under the php function from above (everything is happening inside a plugin file)
Here are my actions
```
add_action('wp_ajax_add_foo', 'foo' );
add_action('wp_ajax_nopriv_add_foo', 'foo' );
```
And my ajax call inside a script tag under the function
```
var ajaxscript = { ajax_url : 'mywebsite.com/wp-admin/admin-ajax.php' }
jQuery(document).ready(function($) {
$.ajax ({
url: ajaxscript.ajax_url,
type: 'POST',
// dataType: 'application/json',
data: {
// the value of data.action is the part AFTER 'wp_ajax_' in
// the add_action ('wp_ajax_xxx', 'yyy') in the PHP above
action: '_add_foo'
// ANY other properties of data are passed to your_function()
// in the PHP global $_REQUEST (or $_POST in this case)
},
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
}) ;
});
```
I would be expecting to get back the $res\_body variable but I'm getting a 400. Why is that? | I figured this out after a night sleep. Sometimes our brains function like that.
The problem was actually my call here, It should've been "add\_foo" not "\_add\_foo"
```
data: {
// the value of data.action is the part AFTER 'wp_ajax_' in
// the add_action ('wp_ajax_xxx', 'yyy') in the PHP above
action: '_add_foo'
// ANY other properties of data are passed to your_function()
// in the PHP global $_REQUEST (or $_POST in this case)
},
``` |
367,200 | <p>Ok, so I am using WordPress rest API to fetch the data using front-end. I am having the plain permalinks and unfortunately, I am not allowed to change the permalinks.
So, for </p>
<pre><code>https://www.example.com
</code></pre>
<p>I am using the route option:</p>
<pre><code>https://www.example.com/?rest_route=/wp/v2/posts
</code></pre>
<p>And this is working completely fine. </p>
<p>Now my question is if I want to access a page URL with query params : </p>
<pre><code>https://www.example.com?cat=12
</code></pre>
<p>How could I do that with rest_route? Thanks in advance. </p>
| [
{
"answer_id": 367202,
"author": "rank",
"author_id": 178642,
"author_profile": "https://wordpress.stackexchange.com/users/178642",
"pm_score": -1,
"selected": false,
"text": "<p>You have to add the parameters at the end, so it is defined which data should be affected. You add it after the 'post' to get all posts within the category with the id of 12.</p>\n\n<p><code>https://www.example.com/wp-json/wp/v2/posts?categories=12</code></p>\n"
},
{
"answer_id": 367217,
"author": "new",
"author_id": 188555,
"author_profile": "https://wordpress.stackexchange.com/users/188555",
"pm_score": 2,
"selected": false,
"text": "<p>Actually I was able to figure out with a little modification to Rank's answer:</p>\n\n<pre><code>https://www.example.com/?rest_route=/wp/v2/posts&categories=12\n</code></pre>\n"
}
] | 2020/05/21 | [
"https://wordpress.stackexchange.com/questions/367200",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188555/"
] | Ok, so I am using WordPress rest API to fetch the data using front-end. I am having the plain permalinks and unfortunately, I am not allowed to change the permalinks.
So, for
```
https://www.example.com
```
I am using the route option:
```
https://www.example.com/?rest_route=/wp/v2/posts
```
And this is working completely fine.
Now my question is if I want to access a page URL with query params :
```
https://www.example.com?cat=12
```
How could I do that with rest\_route? Thanks in advance. | Actually I was able to figure out with a little modification to Rank's answer:
```
https://www.example.com/?rest_route=/wp/v2/posts&categories=12
``` |
367,255 | <p>I am trying to make my theme compatible with <a href="https://wordpress.org/plugins/co-authors-plus/" rel="nofollow noreferrer">Co-Authors Plus plugin</a> and show the co-authors of a post if had any.
I spent about 30 minutes trying to convince myself that I understood the following code to display post author and date:</p>
<pre class="lang-php prettyprint-override"><code>function posted_on() {
global $post;
$author_id=$post->post_author;
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
__( '<i class="entry-date">'. get_the_date( 'F d, Y' ) .'</i>' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$byline = sprintf (
__( 'by %s' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url(
get_author_posts_url( $author_id )
) . '">' . esc_html( get_the_author_meta( 'display_name', $author_id ) ) . '</a>' . '</span>'
);
echo '<span class="posted-on">' . $posted_on . '</span><i><span class="byline"> ' . $byline . '</span></i>'; // WPCS: XSS OK.
}
</code></pre>
<p>So I added a function:</p>
<pre class="lang-php prettyprint-override"><code>
$byline = sprintf(
__('by %s'),
/*Added this*/
if (function_exists('coauthors_posts_links')) {
'<span class="author vcard">'.esc_html(coauthors_posts_links()).
'</span>'
} else {
'<span class="author vcard"><a class="url fn n" href="'.esc_url(
get_author_posts_url($author_id)
).
'">'.esc_html(get_the_author_meta('display_name', $author_id)).
'</a>'.
'</span>'
}
);
</code></pre>
<p>The function was supposed to work like...</p>
<p>IF THIS POST POST CONTAINS CO-AUTHORS,</p>
<p>DISPLAY AUTHORS AND CO-AUTHORS.</p>
<p>IF POST DOESN'T CONTAIN CO-AUTHORS,</p>
<p>SHOW THE DEFAULT AUTHOR LINK.</p>
<p>But that just made error. Could use a little advice.</p>
| [
{
"answer_id": 367202,
"author": "rank",
"author_id": 178642,
"author_profile": "https://wordpress.stackexchange.com/users/178642",
"pm_score": -1,
"selected": false,
"text": "<p>You have to add the parameters at the end, so it is defined which data should be affected. You add it after the 'post' to get all posts within the category with the id of 12.</p>\n\n<p><code>https://www.example.com/wp-json/wp/v2/posts?categories=12</code></p>\n"
},
{
"answer_id": 367217,
"author": "new",
"author_id": 188555,
"author_profile": "https://wordpress.stackexchange.com/users/188555",
"pm_score": 2,
"selected": false,
"text": "<p>Actually I was able to figure out with a little modification to Rank's answer:</p>\n\n<pre><code>https://www.example.com/?rest_route=/wp/v2/posts&categories=12\n</code></pre>\n"
}
] | 2020/05/21 | [
"https://wordpress.stackexchange.com/questions/367255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187384/"
] | I am trying to make my theme compatible with [Co-Authors Plus plugin](https://wordpress.org/plugins/co-authors-plus/) and show the co-authors of a post if had any.
I spent about 30 minutes trying to convince myself that I understood the following code to display post author and date:
```php
function posted_on() {
global $post;
$author_id=$post->post_author;
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
__( '<i class="entry-date">'. get_the_date( 'F d, Y' ) .'</i>' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$byline = sprintf (
__( 'by %s' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url(
get_author_posts_url( $author_id )
) . '">' . esc_html( get_the_author_meta( 'display_name', $author_id ) ) . '</a>' . '</span>'
);
echo '<span class="posted-on">' . $posted_on . '</span><i><span class="byline"> ' . $byline . '</span></i>'; // WPCS: XSS OK.
}
```
So I added a function:
```php
$byline = sprintf(
__('by %s'),
/*Added this*/
if (function_exists('coauthors_posts_links')) {
'<span class="author vcard">'.esc_html(coauthors_posts_links()).
'</span>'
} else {
'<span class="author vcard"><a class="url fn n" href="'.esc_url(
get_author_posts_url($author_id)
).
'">'.esc_html(get_the_author_meta('display_name', $author_id)).
'</a>'.
'</span>'
}
);
```
The function was supposed to work like...
IF THIS POST POST CONTAINS CO-AUTHORS,
DISPLAY AUTHORS AND CO-AUTHORS.
IF POST DOESN'T CONTAIN CO-AUTHORS,
SHOW THE DEFAULT AUTHOR LINK.
But that just made error. Could use a little advice. | Actually I was able to figure out with a little modification to Rank's answer:
```
https://www.example.com/?rest_route=/wp/v2/posts&categories=12
``` |
367,320 | <p>I have a blog site. And I found a suspicious access to my blog post from log.
The url format is like this.</p>
<pre><code>https://example.com/my-post/?unapproved=420&moderation-hash=847492149d817bf7e08d81457bf9952f
</code></pre>
<p>And they access from several ips. What is their purpose?</p>
| [
{
"answer_id": 367202,
"author": "rank",
"author_id": 178642,
"author_profile": "https://wordpress.stackexchange.com/users/178642",
"pm_score": -1,
"selected": false,
"text": "<p>You have to add the parameters at the end, so it is defined which data should be affected. You add it after the 'post' to get all posts within the category with the id of 12.</p>\n\n<p><code>https://www.example.com/wp-json/wp/v2/posts?categories=12</code></p>\n"
},
{
"answer_id": 367217,
"author": "new",
"author_id": 188555,
"author_profile": "https://wordpress.stackexchange.com/users/188555",
"pm_score": 2,
"selected": false,
"text": "<p>Actually I was able to figure out with a little modification to Rank's answer:</p>\n\n<pre><code>https://www.example.com/?rest_route=/wp/v2/posts&categories=12\n</code></pre>\n"
}
] | 2020/05/22 | [
"https://wordpress.stackexchange.com/questions/367320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188643/"
] | I have a blog site. And I found a suspicious access to my blog post from log.
The url format is like this.
```
https://example.com/my-post/?unapproved=420&moderation-hash=847492149d817bf7e08d81457bf9952f
```
And they access from several ips. What is their purpose? | Actually I was able to figure out with a little modification to Rank's answer:
```
https://www.example.com/?rest_route=/wp/v2/posts&categories=12
``` |
367,340 | <p>Nobody has touched <code>wp-admin</code> for this site in weeks. Suddenly, URLs are being sanitized in ways that break <em>everything</em>. The question marks of query parameters are being replaced with URL escape code <code>%3F</code>, which is obviously breaking nearly every script and stylesheet include that's affected. The result is content like this:</p>
<pre><code><script type='text/javascript' src='wp-content/plugins/woocommerce/assets/js/select2/select2.full.min.js%3Fver=4.0.3'></script>
<script type='text/javascript' src='wp-includes/js/wp-embed.min.js%3Fver=5.4.1'></script>
</code></pre>
<p>Some, but not <em>all</em> URLs in the document are affected. Scripts and <em>some</em> anchor elements are affected.</p>
<p>In addition to this URL madness, it seems like portions of the main site are being included in every single page - i.e., the homepage's markup is being embedded within <code>wp-admin</code> pages, etc.</p>
<p>The effect is that the site can essentially not be used - large dynamic portions of pages, especially the main landing page, simply fail to load or appear malformed due to missing scripts and stylesheets.</p>
<p>I should add that it's nearly impossible to navigate <code>wp-admin</code> given the absurd state that it's in at the moment, so I can't really find my way around to do regular diagnostics.</p>
<p>How do I even <em>begin</em> to fix something like this? If this wasn't a moneymaking site with plenty of content I haven't even touched ('the last guy' decided to install dozens of plugins whose purposes are difficult to decipher, are possibly redundant, and might break everything if removed) I would gladly just reinstall everything.</p>
<p>I have attempted:</p>
<ul>
<li><p>Removing a "WP Fastest Cache" plugin which, according to some, 'breaks everything' as of this month. <strong>Edit:</strong> It looks like this plugin is parasitic. After deactivating it, clearing my local cache, etc., pages still contain a comment marking them as having been cached by it...</p></li>
<li><p>Visiting and re-saving permalink settings in <code>wp-admin</code> as suggested by a comment I found in a similar issue elsewhere.</p></li>
-
</ul>
| [
{
"answer_id": 367334,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like your theme is dependant on one of those plugins and disabling it is causing grief. You'll need to swap themes to get your admin back up. Make sure you have a default wordpress theme in your folders, like twentynineteen.</p>\n\n<p>From phpMyadmin, follow these instructions:</p>\n\n<ol>\n<li>Click on the <strong>wp_options</strong> table.</li>\n<li>Under the <strong>option_name</strong> column, locate the <strong>template</strong> entry. You may\nneed to navigate beyond the first page of entries.</li>\n<li>Click Edit next to the <strong>template</strong> entry.</li>\n<li>In the <strong>option_value</strong> column, change the value to the name of your chosen\ntheme. The new value must be the same as your theme's folder name.</li>\n<li>To save, click Go.</li>\n<li>Click Edit next to the <strong>stylesheet</strong> entry.</li>\n<li>In the <strong>option_value</strong> column, change the value to the name of the chosen theme. The new\nvalue must be the same as your theme's folder name(ex.\ntwentynineteen).</li>\n<li>To save, click Go.</li>\n</ol>\n\n<p>If you can then see your admin, then we can be sure your theme needs one of those disabled plugins. Flick them all back on, switch back to your original theme, and everything should work again. Then disable them one by one and find out which one is causing the break when removed.</p>\n\n<p>Once you identify the plugin causing the problem, you can start troubleshooting.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 367335,
"author": "made2popular",
"author_id": 173347,
"author_profile": "https://wordpress.stackexchange.com/users/173347",
"pm_score": 2,
"selected": false,
"text": "<p>Well I agree with @Faye. It might be due to the activated theme which is depending on one of the plugin you deactivated. But rather than doing all of the steps you can simply rename the active theme in the wp-content/themes folder via FTP or cPanel. This will deactivate the theme and if it's the theme problem then you will be able to access the admin page.</p>\n"
}
] | 2020/05/23 | [
"https://wordpress.stackexchange.com/questions/367340",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188656/"
] | Nobody has touched `wp-admin` for this site in weeks. Suddenly, URLs are being sanitized in ways that break *everything*. The question marks of query parameters are being replaced with URL escape code `%3F`, which is obviously breaking nearly every script and stylesheet include that's affected. The result is content like this:
```
<script type='text/javascript' src='wp-content/plugins/woocommerce/assets/js/select2/select2.full.min.js%3Fver=4.0.3'></script>
<script type='text/javascript' src='wp-includes/js/wp-embed.min.js%3Fver=5.4.1'></script>
```
Some, but not *all* URLs in the document are affected. Scripts and *some* anchor elements are affected.
In addition to this URL madness, it seems like portions of the main site are being included in every single page - i.e., the homepage's markup is being embedded within `wp-admin` pages, etc.
The effect is that the site can essentially not be used - large dynamic portions of pages, especially the main landing page, simply fail to load or appear malformed due to missing scripts and stylesheets.
I should add that it's nearly impossible to navigate `wp-admin` given the absurd state that it's in at the moment, so I can't really find my way around to do regular diagnostics.
How do I even *begin* to fix something like this? If this wasn't a moneymaking site with plenty of content I haven't even touched ('the last guy' decided to install dozens of plugins whose purposes are difficult to decipher, are possibly redundant, and might break everything if removed) I would gladly just reinstall everything.
I have attempted:
* Removing a "WP Fastest Cache" plugin which, according to some, 'breaks everything' as of this month. **Edit:** It looks like this plugin is parasitic. After deactivating it, clearing my local cache, etc., pages still contain a comment marking them as having been cached by it...
* Visiting and re-saving permalink settings in `wp-admin` as suggested by a comment I found in a similar issue elsewhere.
- | Well I agree with @Faye. It might be due to the activated theme which is depending on one of the plugin you deactivated. But rather than doing all of the steps you can simply rename the active theme in the wp-content/themes folder via FTP or cPanel. This will deactivate the theme and if it's the theme problem then you will be able to access the admin page. |
367,374 | <p>I have 3 users roles on my platform with no access to the WordPress backoffice <strong>"external_user1"</strong> , <strong>"external_user2"</strong>, <strong>"external_user3"</strong>.</p>
<p>I need to force every user with one of this roles to change his password at the first login. by the way i use the WordPress login form.</p>
<p>So if the user enter the correct ID and password he is redirected to : <strong>wp-login.php?action=lostpassword</strong> for reset the password. as you can see on the picture below :
<a href="https://i.stack.imgur.com/Ngb3M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ngb3M.png" alt="enter image description here"></a></p>
<p>At this time, he enters again the ID and a reset mail is send to the user.</p>
<p>When the user click to the mail link he is redirected to reset page. and when he tries to change the password i need him to type on the keyboard the old one. after that he can access. </p>
<p>And the last one is about password policy :
8 characters with at last 1 uppercase 1 lowercase 1 Number 1 special character</p>
<p>Thanks.</p>
| [
{
"answer_id": 367786,
"author": "Steven Green",
"author_id": 188990,
"author_profile": "https://wordpress.stackexchange.com/users/188990",
"pm_score": -1,
"selected": false,
"text": "<p>There are a number of useful plugins that do just this. They even have extra features you didn't mention like two-factor authentication.</p>\n\n<ul>\n<li>iThemes Security (<a href=\"https://wordpress.org/plugins/better-wp-security/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-wp-security/</a>)</li>\n<li>Shield Security (<a href=\"https://wordpress.org/plugins/wp-simple-firewall/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-simple-firewall/</a>)</li>\n<li>All In One WP Security & Firewall (<a href=\"https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/</a>)</li>\n</ul>\n\n<p>Some of these are free. Or at least have free trials or free plans.</p>\n"
},
{
"answer_id": 367801,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 2,
"selected": false,
"text": "<p>This is a multi-faceted issue that probably seems (well, to me at least) easy at first. Not sure if the code works, however, it's close to working <strong>but most importantly, showcases the flow of how things need to happen:</strong></p>\n\n<pre><code>/**\n * First of all, hook up to the login process.\n */\nadd_action( 'wp_login', function( $user_login, $user ) {\n //Let's see if the user that just logged in has a proper password, meaning, he reset his default one to a custom one.\n $has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );\n\n //If he doesn't\n if( $has_proper_password === '0' ) {\n //Always redirect him to that password panel.\n wp_safe_redirect( wp_login_url( '?action=lostpassword' ) );\n }\n});\n</code></pre>\n\n<p>So, before anything, you're hooking to the login process. I assume you're generating a default password to a user and mailing it to them and the reason for you wanting to change that is so that the plain-text is never valid if an attacker gets access to the medium it was sent to. Back to topic, <strong>the core of this sub-system will be an <code>user_meta</code> with the flag <code>has_proper_password</code></strong>, this is where you'll store a flag that tells us if a given user has had his default password reset. Whenever they login, if they hadn't changed their default password, they'll just be redirected to that screen of yours. Moving on.</p>\n\n<p>You'll then want to grab the user's current hashed password when he's attempting a reset. The hook <code>password_reset</code> fires right before that happens:</p>\n\n<pre><code>//Let's store the old password, before the reset happened.\n$old_password_hash = '';\n\n//We'll grab it from the 'password_reset' hook which fires right before the password is updated.\nadd_action( 'password_reset', function( $user, $new_pass ) {\n $old_password_hash = $user->user_pass;\n});\n</code></pre>\n\n<p>Great, now we have the user's hash. Let's assume that a successful change of passwords happened. To sum it all up, you want to go back to that <code>user_meta</code> and if the user hasn't had his default password changed, follow the logic of:</p>\n\n<ol>\n<li>Is the new password the same as the old one? If yes, redirect back to that change password screen with a new message or something of the sorts. If not, proceed.</li>\n<li>So, the new password is a completely new one -- valid too, great, **all we'll do now is update that <code>user_meta</code> to tell the system that, when the user logs in once again, it shouldn't stop him and ask for a valid password since it's already there.</li>\n<li>Redirect either to login or if you wanna get fancy, pass the session through code so the user doesn't have to login once again.</li>\n</ol>\n\n<p>All of this, in code:</p>\n\n<pre><code>//Second of all, hook up to the change password process.\nadd_action( 'after_password_reset', function( $user, $new_pass ) {\n $has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );\n\n /**\n * If, before this reset happened, the user still didn't have a proper password and now\n * he supposedly does\n */\n if( $has_proper_password === '0' ) {\n\n //First of all, is the password that was just updated the same as the one that we gave to them?\n if( wp_check_password( $new_pass, $old_password_hash ) === False ) {\n //Redirect back to that reset page? I don't know.\n }\n\n //But if it isn't and therefore the newly picked password is a different one, let the system know by attaching some data to the user.\n $update = add_user_meta(\n $user->ID,\n 'has_proper_password',\n '1'\n );\n\n //If the update failed, no worries, next time the user will just be prompted to reset again, however, this is an issue you'll have to solve.\n if( $update === False ) {\n return;\n }\n }\n});\n</code></pre>\n"
}
] | 2020/05/23 | [
"https://wordpress.stackexchange.com/questions/367374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] | I have 3 users roles on my platform with no access to the WordPress backoffice **"external\_user1"** , **"external\_user2"**, **"external\_user3"**.
I need to force every user with one of this roles to change his password at the first login. by the way i use the WordPress login form.
So if the user enter the correct ID and password he is redirected to : **wp-login.php?action=lostpassword** for reset the password. as you can see on the picture below :
[](https://i.stack.imgur.com/Ngb3M.png)
At this time, he enters again the ID and a reset mail is send to the user.
When the user click to the mail link he is redirected to reset page. and when he tries to change the password i need him to type on the keyboard the old one. after that he can access.
And the last one is about password policy :
8 characters with at last 1 uppercase 1 lowercase 1 Number 1 special character
Thanks. | This is a multi-faceted issue that probably seems (well, to me at least) easy at first. Not sure if the code works, however, it's close to working **but most importantly, showcases the flow of how things need to happen:**
```
/**
* First of all, hook up to the login process.
*/
add_action( 'wp_login', function( $user_login, $user ) {
//Let's see if the user that just logged in has a proper password, meaning, he reset his default one to a custom one.
$has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );
//If he doesn't
if( $has_proper_password === '0' ) {
//Always redirect him to that password panel.
wp_safe_redirect( wp_login_url( '?action=lostpassword' ) );
}
});
```
So, before anything, you're hooking to the login process. I assume you're generating a default password to a user and mailing it to them and the reason for you wanting to change that is so that the plain-text is never valid if an attacker gets access to the medium it was sent to. Back to topic, **the core of this sub-system will be an `user_meta` with the flag `has_proper_password`**, this is where you'll store a flag that tells us if a given user has had his default password reset. Whenever they login, if they hadn't changed their default password, they'll just be redirected to that screen of yours. Moving on.
You'll then want to grab the user's current hashed password when he's attempting a reset. The hook `password_reset` fires right before that happens:
```
//Let's store the old password, before the reset happened.
$old_password_hash = '';
//We'll grab it from the 'password_reset' hook which fires right before the password is updated.
add_action( 'password_reset', function( $user, $new_pass ) {
$old_password_hash = $user->user_pass;
});
```
Great, now we have the user's hash. Let's assume that a successful change of passwords happened. To sum it all up, you want to go back to that `user_meta` and if the user hasn't had his default password changed, follow the logic of:
1. Is the new password the same as the old one? If yes, redirect back to that change password screen with a new message or something of the sorts. If not, proceed.
2. So, the new password is a completely new one -- valid too, great, \*\*all we'll do now is update that `user_meta` to tell the system that, when the user logs in once again, it shouldn't stop him and ask for a valid password since it's already there.
3. Redirect either to login or if you wanna get fancy, pass the session through code so the user doesn't have to login once again.
All of this, in code:
```
//Second of all, hook up to the change password process.
add_action( 'after_password_reset', function( $user, $new_pass ) {
$has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );
/**
* If, before this reset happened, the user still didn't have a proper password and now
* he supposedly does
*/
if( $has_proper_password === '0' ) {
//First of all, is the password that was just updated the same as the one that we gave to them?
if( wp_check_password( $new_pass, $old_password_hash ) === False ) {
//Redirect back to that reset page? I don't know.
}
//But if it isn't and therefore the newly picked password is a different one, let the system know by attaching some data to the user.
$update = add_user_meta(
$user->ID,
'has_proper_password',
'1'
);
//If the update failed, no worries, next time the user will just be prompted to reset again, however, this is an issue you'll have to solve.
if( $update === False ) {
return;
}
}
});
``` |
367,376 | <p>I am new to plugin development and I am fairly okay with development by following all the plugin development best practices set by WordPress Codex. Following code describes on how Role: Administrator of WordPress gains access to the plugin. </p>
<p>Administrator access to plugin in settings: SettingsApi.php</p>
<pre><code>public function register()
{
if ( ! empty($this->admin_pages) || ! empty($this->admin_subpages)) {
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
}
}
public function addSubPages( array $pages )
{
$this->admin_subpages = array_merge( $this->admin_subpages, $pages );
return $this;
}
public function addAdminMenu()
{
foreach ( $this->admin_pages as $page ) {
add_menu_page( $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'], $page['icon_url'], $page['position'] );
}
foreach ( $this->admin_subpages as $page ) {
add_submenu_page( $page['parent_slug'], $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'] );
}
}
</code></pre>
<p>Adding a new role to user base of WordPress by following code while activation: Activate.php</p>
<pre><code>$result =
add_role
(
'backend_user',
__( 'Plugin Name Backend', 'testsite' ),
array(
'read' => true, // true allows this capability
'edit_posts' => false,
'delete_posts' => false,
)
);
</code></pre>
<p>I am looking at how to set rights to the role <strong>backend_user</strong> to access plugin pages in my SettingApi.php. Also if there is any method that will enable <strong>backend_user</strong> to access my plugin pages in the WordPress login please suggest.</p>
<p>I Tried following function in SettingApi.php under register()</p>
<pre><code>$user = wp_get_current_user();
if ( in_array( 'backend_user', (array) $user->roles ) ) {
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
}
</code></pre>
<p>Not working. Any help would be grateful.</p>
| [
{
"answer_id": 367786,
"author": "Steven Green",
"author_id": 188990,
"author_profile": "https://wordpress.stackexchange.com/users/188990",
"pm_score": -1,
"selected": false,
"text": "<p>There are a number of useful plugins that do just this. They even have extra features you didn't mention like two-factor authentication.</p>\n\n<ul>\n<li>iThemes Security (<a href=\"https://wordpress.org/plugins/better-wp-security/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-wp-security/</a>)</li>\n<li>Shield Security (<a href=\"https://wordpress.org/plugins/wp-simple-firewall/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-simple-firewall/</a>)</li>\n<li>All In One WP Security & Firewall (<a href=\"https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/all-in-one-wp-security-and-firewall/</a>)</li>\n</ul>\n\n<p>Some of these are free. Or at least have free trials or free plans.</p>\n"
},
{
"answer_id": 367801,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 2,
"selected": false,
"text": "<p>This is a multi-faceted issue that probably seems (well, to me at least) easy at first. Not sure if the code works, however, it's close to working <strong>but most importantly, showcases the flow of how things need to happen:</strong></p>\n\n<pre><code>/**\n * First of all, hook up to the login process.\n */\nadd_action( 'wp_login', function( $user_login, $user ) {\n //Let's see if the user that just logged in has a proper password, meaning, he reset his default one to a custom one.\n $has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );\n\n //If he doesn't\n if( $has_proper_password === '0' ) {\n //Always redirect him to that password panel.\n wp_safe_redirect( wp_login_url( '?action=lostpassword' ) );\n }\n});\n</code></pre>\n\n<p>So, before anything, you're hooking to the login process. I assume you're generating a default password to a user and mailing it to them and the reason for you wanting to change that is so that the plain-text is never valid if an attacker gets access to the medium it was sent to. Back to topic, <strong>the core of this sub-system will be an <code>user_meta</code> with the flag <code>has_proper_password</code></strong>, this is where you'll store a flag that tells us if a given user has had his default password reset. Whenever they login, if they hadn't changed their default password, they'll just be redirected to that screen of yours. Moving on.</p>\n\n<p>You'll then want to grab the user's current hashed password when he's attempting a reset. The hook <code>password_reset</code> fires right before that happens:</p>\n\n<pre><code>//Let's store the old password, before the reset happened.\n$old_password_hash = '';\n\n//We'll grab it from the 'password_reset' hook which fires right before the password is updated.\nadd_action( 'password_reset', function( $user, $new_pass ) {\n $old_password_hash = $user->user_pass;\n});\n</code></pre>\n\n<p>Great, now we have the user's hash. Let's assume that a successful change of passwords happened. To sum it all up, you want to go back to that <code>user_meta</code> and if the user hasn't had his default password changed, follow the logic of:</p>\n\n<ol>\n<li>Is the new password the same as the old one? If yes, redirect back to that change password screen with a new message or something of the sorts. If not, proceed.</li>\n<li>So, the new password is a completely new one -- valid too, great, **all we'll do now is update that <code>user_meta</code> to tell the system that, when the user logs in once again, it shouldn't stop him and ask for a valid password since it's already there.</li>\n<li>Redirect either to login or if you wanna get fancy, pass the session through code so the user doesn't have to login once again.</li>\n</ol>\n\n<p>All of this, in code:</p>\n\n<pre><code>//Second of all, hook up to the change password process.\nadd_action( 'after_password_reset', function( $user, $new_pass ) {\n $has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );\n\n /**\n * If, before this reset happened, the user still didn't have a proper password and now\n * he supposedly does\n */\n if( $has_proper_password === '0' ) {\n\n //First of all, is the password that was just updated the same as the one that we gave to them?\n if( wp_check_password( $new_pass, $old_password_hash ) === False ) {\n //Redirect back to that reset page? I don't know.\n }\n\n //But if it isn't and therefore the newly picked password is a different one, let the system know by attaching some data to the user.\n $update = add_user_meta(\n $user->ID,\n 'has_proper_password',\n '1'\n );\n\n //If the update failed, no worries, next time the user will just be prompted to reset again, however, this is an issue you'll have to solve.\n if( $update === False ) {\n return;\n }\n }\n});\n</code></pre>\n"
}
] | 2020/05/23 | [
"https://wordpress.stackexchange.com/questions/367376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188686/"
] | I am new to plugin development and I am fairly okay with development by following all the plugin development best practices set by WordPress Codex. Following code describes on how Role: Administrator of WordPress gains access to the plugin.
Administrator access to plugin in settings: SettingsApi.php
```
public function register()
{
if ( ! empty($this->admin_pages) || ! empty($this->admin_subpages)) {
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
}
}
public function addSubPages( array $pages )
{
$this->admin_subpages = array_merge( $this->admin_subpages, $pages );
return $this;
}
public function addAdminMenu()
{
foreach ( $this->admin_pages as $page ) {
add_menu_page( $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'], $page['icon_url'], $page['position'] );
}
foreach ( $this->admin_subpages as $page ) {
add_submenu_page( $page['parent_slug'], $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'] );
}
}
```
Adding a new role to user base of WordPress by following code while activation: Activate.php
```
$result =
add_role
(
'backend_user',
__( 'Plugin Name Backend', 'testsite' ),
array(
'read' => true, // true allows this capability
'edit_posts' => false,
'delete_posts' => false,
)
);
```
I am looking at how to set rights to the role **backend\_user** to access plugin pages in my SettingApi.php. Also if there is any method that will enable **backend\_user** to access my plugin pages in the WordPress login please suggest.
I Tried following function in SettingApi.php under register()
```
$user = wp_get_current_user();
if ( in_array( 'backend_user', (array) $user->roles ) ) {
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
}
```
Not working. Any help would be grateful. | This is a multi-faceted issue that probably seems (well, to me at least) easy at first. Not sure if the code works, however, it's close to working **but most importantly, showcases the flow of how things need to happen:**
```
/**
* First of all, hook up to the login process.
*/
add_action( 'wp_login', function( $user_login, $user ) {
//Let's see if the user that just logged in has a proper password, meaning, he reset his default one to a custom one.
$has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );
//If he doesn't
if( $has_proper_password === '0' ) {
//Always redirect him to that password panel.
wp_safe_redirect( wp_login_url( '?action=lostpassword' ) );
}
});
```
So, before anything, you're hooking to the login process. I assume you're generating a default password to a user and mailing it to them and the reason for you wanting to change that is so that the plain-text is never valid if an attacker gets access to the medium it was sent to. Back to topic, **the core of this sub-system will be an `user_meta` with the flag `has_proper_password`**, this is where you'll store a flag that tells us if a given user has had his default password reset. Whenever they login, if they hadn't changed their default password, they'll just be redirected to that screen of yours. Moving on.
You'll then want to grab the user's current hashed password when he's attempting a reset. The hook `password_reset` fires right before that happens:
```
//Let's store the old password, before the reset happened.
$old_password_hash = '';
//We'll grab it from the 'password_reset' hook which fires right before the password is updated.
add_action( 'password_reset', function( $user, $new_pass ) {
$old_password_hash = $user->user_pass;
});
```
Great, now we have the user's hash. Let's assume that a successful change of passwords happened. To sum it all up, you want to go back to that `user_meta` and if the user hasn't had his default password changed, follow the logic of:
1. Is the new password the same as the old one? If yes, redirect back to that change password screen with a new message or something of the sorts. If not, proceed.
2. So, the new password is a completely new one -- valid too, great, \*\*all we'll do now is update that `user_meta` to tell the system that, when the user logs in once again, it shouldn't stop him and ask for a valid password since it's already there.
3. Redirect either to login or if you wanna get fancy, pass the session through code so the user doesn't have to login once again.
All of this, in code:
```
//Second of all, hook up to the change password process.
add_action( 'after_password_reset', function( $user, $new_pass ) {
$has_proper_password = get_user_meta( $user->ID, 'has_proper_password', True );
/**
* If, before this reset happened, the user still didn't have a proper password and now
* he supposedly does
*/
if( $has_proper_password === '0' ) {
//First of all, is the password that was just updated the same as the one that we gave to them?
if( wp_check_password( $new_pass, $old_password_hash ) === False ) {
//Redirect back to that reset page? I don't know.
}
//But if it isn't and therefore the newly picked password is a different one, let the system know by attaching some data to the user.
$update = add_user_meta(
$user->ID,
'has_proper_password',
'1'
);
//If the update failed, no worries, next time the user will just be prompted to reset again, however, this is an issue you'll have to solve.
if( $update === False ) {
return;
}
}
});
``` |
367,383 | <p>I'm going round in circles with trying to include several custom fields in my search results. The custom fields are managed via ACF.</p>
<p>At first I want this for the admin. /wp-admin/edit.php?post_type=location.</p>
<p>I can't see why this wont work. I have tried variations of it and different orders. I've also gone through the posts_search filter route with arrays but just can't get this to work.</p>
<p>Any help appreciated.</p>
<pre><code>add_filter('pre_get_posts', __NAMESPACE__ . '\\search_custom_fields');
function search_custom_fields($query)
{
if ($query->is_search && $query->is_main_query()) {
// this works.
echo "search_custom_fields: " . $query->is_main_query() . " " . $query->is_search;
echo "Setting meta_query in search_custom_fields. ";
$search_word = get_query_var('s');
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'loc_refid',
'value' => get_search_query(),
'compare' => 'LIKE',
), array(
'key' => 'location_postcode_preview',
'value' => get_search_query(),
'compare' => 'LIKE',
),
);
// if i uncomment this no results appear?!
// $query->set('meta_query', $meta_query);
// these work have an affect on the results
$query->set('orderby', 'date');
$query->set('order', 'ASC');
}
return $query;
</code></pre>
<p>}</p>
<p>print_r($query) gives me -</p>
<pre><code> [query_vars]=>
[meta_query] => Array
(
[key] => loc_refid
[value] => MN0068
[compare] => LIKE
)
[meta_query] =>
[date_query] =>
[post_count] => 0
...
</code></pre>
<p>thanks in advance.</p>
| [
{
"answer_id": 367388,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried it with <code>add_action</code> instead of <code>add_filter</code> ? </p>\n\n<pre><code>add_action('pre_get_posts', 'search_custom_fields');\n</code></pre>\n\n<p>Is <code>public</code> set to true for your post_type? </p>\n\n<p>And for use on in admin, try: </p>\n\n<pre><code>if ( is_admin() && $query->is_main_query() ) {\n if ( $query->is_search ) {\n //etc.\n</code></pre>\n"
},
{
"answer_id": 370021,
"author": "v3nt",
"author_id": 3978,
"author_profile": "https://wordpress.stackexchange.com/users/3978",
"pm_score": 1,
"selected": true,
"text": "<p>So turns out you can't actually add ACF / custom fields to the search query in this way. It seems to force and AND into the query.</p>\n<p>I've used a mixture of sources to create the below which now works really well.</p>\n<pre><code>/* ADD META FIELD TO SEARCH QUERY */\n// fields for Ajax search, admin and normal search\nif (!isset($GLOBALS['current_screen']) && !is_customize_preview()):\n // DAMN AJAX! is_admin() is always true when using it ;-/\n add_meta_field_to_search_query('loc_refid');\n add_meta_field_to_search_query('location_postcode_preview');\n add_meta_field_to_search_query('location_region');\n add_meta_field_to_search_query('location_areas');\n\nelseif (is_admin()):\n add_meta_field_to_search_query('loc_refid');\n add_meta_field_to_search_query('location_postcode');\n add_meta_field_to_search_query('location_postcode_preview');\n add_meta_field_to_search_query('location_region');\n add_meta_field_to_search_query('location_areas');\n add_meta_field_to_search_query('location_map_position' );\n add_meta_field_to_search_query('user_organisation');\n add_meta_field_to_search_query('user_position');\n add_meta_field_to_search_query('client_location');\n add_meta_field_to_search_query('user_email');\nelse:\n add_meta_field_to_search_query('loc_refid'); \n add_meta_field_to_search_query('location_postcode_preview');\n add_meta_field_to_search_query('location_region');\n add_meta_field_to_search_query('location_areas');\n\nendif;\n\nfunction add_meta_field_to_search_query($field, $condition = "LIKE")\n{\n // echo "add_meta_field_to_search_query; field:$field";\n\n if (isset($GLOBALS['added_meta_field_to_search_query'])) {\n $GLOBALS['added_meta_field_to_search_query'][] = '\\'' . $field . '\\'';\n return;\n }\n\n $GLOBALS['added_meta_field_to_search_query'] = array();\n $GLOBALS['added_meta_field_to_search_query'][] = '\\'' . $field . '\\'';\n\n add_filter('posts_join', function ($join) {\n // echo "$s 'posts_join' <br />";\n global $wpdb;\n if (is_search()) {\n $join .= " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";\n }\n return $join;\n });\n\n add_filter('posts_groupby', function ($groupby) {\n // echo "$s 'posts_groupby' <br />";\n global $wpdb;\n if (is_search()) {\n $groupby = "$wpdb->posts.ID";\n }\n return $groupby;\n });\n\n add_filter('posts_search', function ($search_sql) {\n global $wpdb;\n\n $search_terms = get_query_var('search_terms');\n\n if (!empty($search_terms)) {\n // echo "posts_search<br />";\n // print_r($search_terms);\n foreach ($search_terms as $search_term) {\n // echo "search_term: $search_term<br />";\n $old_or = "OR ({$wpdb->posts}.post_content LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}')";\n $new_or = $old_or . " OR ({$wpdb->postmeta}.meta_value LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}' AND {$wpdb->postmeta}.meta_key IN (" . implode(', ', $GLOBALS['added_meta_field_to_search_query']) . "))";\n $search_sql = str_replace($old_or, $new_or, $search_sql);\n }\n }\n\n $search_sql = str_replace(" ORDER BY ", " GROUP BY $wpdb->posts.ID ORDER BY ", $search_sql);\n\n return $search_sql;\n });\n\n // ajax seach only, basically same as above but checking for $GLOBALS['fd_search_term'] which holds the search string\n add_filter('posts_where', function ($search_sql) {\n global $wpdb;\n\n // print_r($wpdb);\n $search_terms = explode(' ', $GLOBALS['fd_search_term']);\n\n // if (!empty($search_terms) && !isset($GLOBALS['current_screen']) && !is_customize_preview() && !is_search()) {\n\n if ($GLOBALS['fd_search_term']) {\n // echo "AJAX posts_search<br />";\n // print_r($search_terms);\n foreach ($search_terms as $search_term) {\n // echo "search_term: $search_term<br />";\n $old_or = "OR ({$wpdb->posts}.post_content LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}')";\n $new_or = $old_or . " OR ({$wpdb->postmeta}.meta_value LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}' AND {$wpdb->postmeta}.meta_key IN (" . implode(', ', $GLOBALS['added_meta_field_to_search_query']) . "))";\n $search_sql = str_replace($old_or, $new_or, $search_sql);\n }\n }\n\n $search_sql = str_replace(" ORDER BY ", " GROUP BY $wpdb->posts.ID ORDER BY ", $search_sql);\n\n return $search_sql;\n });\n\n}\n</code></pre>\n"
}
] | 2020/05/23 | [
"https://wordpress.stackexchange.com/questions/367383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3978/"
] | I'm going round in circles with trying to include several custom fields in my search results. The custom fields are managed via ACF.
At first I want this for the admin. /wp-admin/edit.php?post\_type=location.
I can't see why this wont work. I have tried variations of it and different orders. I've also gone through the posts\_search filter route with arrays but just can't get this to work.
Any help appreciated.
```
add_filter('pre_get_posts', __NAMESPACE__ . '\\search_custom_fields');
function search_custom_fields($query)
{
if ($query->is_search && $query->is_main_query()) {
// this works.
echo "search_custom_fields: " . $query->is_main_query() . " " . $query->is_search;
echo "Setting meta_query in search_custom_fields. ";
$search_word = get_query_var('s');
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'loc_refid',
'value' => get_search_query(),
'compare' => 'LIKE',
), array(
'key' => 'location_postcode_preview',
'value' => get_search_query(),
'compare' => 'LIKE',
),
);
// if i uncomment this no results appear?!
// $query->set('meta_query', $meta_query);
// these work have an affect on the results
$query->set('orderby', 'date');
$query->set('order', 'ASC');
}
return $query;
```
}
print\_r($query) gives me -
```
[query_vars]=>
[meta_query] => Array
(
[key] => loc_refid
[value] => MN0068
[compare] => LIKE
)
[meta_query] =>
[date_query] =>
[post_count] => 0
...
```
thanks in advance. | So turns out you can't actually add ACF / custom fields to the search query in this way. It seems to force and AND into the query.
I've used a mixture of sources to create the below which now works really well.
```
/* ADD META FIELD TO SEARCH QUERY */
// fields for Ajax search, admin and normal search
if (!isset($GLOBALS['current_screen']) && !is_customize_preview()):
// DAMN AJAX! is_admin() is always true when using it ;-/
add_meta_field_to_search_query('loc_refid');
add_meta_field_to_search_query('location_postcode_preview');
add_meta_field_to_search_query('location_region');
add_meta_field_to_search_query('location_areas');
elseif (is_admin()):
add_meta_field_to_search_query('loc_refid');
add_meta_field_to_search_query('location_postcode');
add_meta_field_to_search_query('location_postcode_preview');
add_meta_field_to_search_query('location_region');
add_meta_field_to_search_query('location_areas');
add_meta_field_to_search_query('location_map_position' );
add_meta_field_to_search_query('user_organisation');
add_meta_field_to_search_query('user_position');
add_meta_field_to_search_query('client_location');
add_meta_field_to_search_query('user_email');
else:
add_meta_field_to_search_query('loc_refid');
add_meta_field_to_search_query('location_postcode_preview');
add_meta_field_to_search_query('location_region');
add_meta_field_to_search_query('location_areas');
endif;
function add_meta_field_to_search_query($field, $condition = "LIKE")
{
// echo "add_meta_field_to_search_query; field:$field";
if (isset($GLOBALS['added_meta_field_to_search_query'])) {
$GLOBALS['added_meta_field_to_search_query'][] = '\'' . $field . '\'';
return;
}
$GLOBALS['added_meta_field_to_search_query'] = array();
$GLOBALS['added_meta_field_to_search_query'][] = '\'' . $field . '\'';
add_filter('posts_join', function ($join) {
// echo "$s 'posts_join' <br />";
global $wpdb;
if (is_search()) {
$join .= " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
}
return $join;
});
add_filter('posts_groupby', function ($groupby) {
// echo "$s 'posts_groupby' <br />";
global $wpdb;
if (is_search()) {
$groupby = "$wpdb->posts.ID";
}
return $groupby;
});
add_filter('posts_search', function ($search_sql) {
global $wpdb;
$search_terms = get_query_var('search_terms');
if (!empty($search_terms)) {
// echo "posts_search<br />";
// print_r($search_terms);
foreach ($search_terms as $search_term) {
// echo "search_term: $search_term<br />";
$old_or = "OR ({$wpdb->posts}.post_content LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}')";
$new_or = $old_or . " OR ({$wpdb->postmeta}.meta_value LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}' AND {$wpdb->postmeta}.meta_key IN (" . implode(', ', $GLOBALS['added_meta_field_to_search_query']) . "))";
$search_sql = str_replace($old_or, $new_or, $search_sql);
}
}
$search_sql = str_replace(" ORDER BY ", " GROUP BY $wpdb->posts.ID ORDER BY ", $search_sql);
return $search_sql;
});
// ajax seach only, basically same as above but checking for $GLOBALS['fd_search_term'] which holds the search string
add_filter('posts_where', function ($search_sql) {
global $wpdb;
// print_r($wpdb);
$search_terms = explode(' ', $GLOBALS['fd_search_term']);
// if (!empty($search_terms) && !isset($GLOBALS['current_screen']) && !is_customize_preview() && !is_search()) {
if ($GLOBALS['fd_search_term']) {
// echo "AJAX posts_search<br />";
// print_r($search_terms);
foreach ($search_terms as $search_term) {
// echo "search_term: $search_term<br />";
$old_or = "OR ({$wpdb->posts}.post_content LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}')";
$new_or = $old_or . " OR ({$wpdb->postmeta}.meta_value LIKE '{$wpdb->placeholder_escape()}{$search_term}{$wpdb->placeholder_escape()}' AND {$wpdb->postmeta}.meta_key IN (" . implode(', ', $GLOBALS['added_meta_field_to_search_query']) . "))";
$search_sql = str_replace($old_or, $new_or, $search_sql);
}
}
$search_sql = str_replace(" ORDER BY ", " GROUP BY $wpdb->posts.ID ORDER BY ", $search_sql);
return $search_sql;
});
}
``` |
367,396 | <p>I wish to set up 2 smtp accounts on my wordpress site:</p>
<p>1 for woocommerce orders
1 for all other forms</p>
<p>i have the following code, but i am having trouble filtering the woocommmerce order. I am missing somthing. Here is the code:</p>
<pre><code>add_action( 'phpmailer_init', 'send_smtp' );
function send_smtp( $phpmailer ) {
if ( true === 'WC_Email' )
{
$phpmailer->Host = SMTP_WC_HOST;
$phpmailer->SMTPAuth = SMTP_WC_AUTH;
$phpmailer->Port = SMTP_WC_PORT;
$phpmailer->Username = SMTP_WC_USER;
$phpmailer->Password = SMTP_WC_PASS;
$phpmailer->SMTPSecure = SMTP_WC_SECURE;
$phpmailer->From = SMTP_WC_FROM;
$phpmailer->FromName = SMTP_WC_NAME;
}
else{
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
}
</code></pre>
<p>The results, both in woocommerce and regular forms result in the 'else' ; therefore, i'm not filtering the woocommerce orders correctly. </p>
| [
{
"answer_id": 367491,
"author": "Leon William",
"author_id": 103968,
"author_profile": "https://wordpress.stackexchange.com/users/103968",
"pm_score": 0,
"selected": false,
"text": "<p>Right now, it is not possible to add multiple SMTP addresses. However, if you still need to send emails from different accounts that are within the same domain, then you can use domain-based mailers like Sendgrid, Sendinblue, or Mailgun. These mailers usually have the requirement of first verifying the domain instead of authenticating the mailbox account. In that case, you can use it to send emails from the email address of your own domain. </p>\n"
},
{
"answer_id": 367563,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": true,
"text": "<p>Your premise is correct - you can connect to different STMP accounts based on whatever criteria you can build into your action function.</p>\n\n<p>It's a little tricky with WooCommerce because it has two email objects that it uses, one for creating emails and the other for sending. Also, hooking into the WC send process requires some serious grokking of WC to figure out where you need to hook your phpmailer_init action.</p>\n\n<p>A simple method to figure out whether the email being sent is a WC email or not is to setup WC with a different \"from\" address in the settings (this address won't matter anyway, since you're sending via an SMTP server and you're re-setting the \"from\" when you setup your SMTP settings). Go to WooCommerce > Settings > Emails and set a unique \"from\" address that is different from your WP settings. You can then use that in your logic to determine whether the email is being generated via WC or something else.</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp' );\nfunction send_smtp( $phpmailer ) {\n\n // Assuming the WC email is set to a different address than all others (i.e. WP General Settings email).\n $woo_from = get_option( 'woocommerce_email_from_address' );\n\n // If phpMailer is initialized with the WooCommerce from address...\n if ( $phpmailer->From == $woo_from ) {\n\n // This is a WooCommerce email.\n\n $phpmailer->Host = SMTP_WC_HOST;\n $phpmailer->SMTPAuth = SMTP_WC_AUTH;\n $phpmailer->Port = SMTP_WC_PORT;\n $phpmailer->Username = SMTP_WC_USER;\n $phpmailer->Password = SMTP_WC_PASS;\n $phpmailer->SMTPSecure = SMTP_WC_SECURE;\n $phpmailer->From = SMTP_WC_FROM;\n $phpmailer->FromName = SMTP_WC_NAME;\n\n } else {\n\n // It's NOT a WooCommerce email.\n\n $phpmailer->Host = SMTP_HOST;\n $phpmailer->SMTPAuth = SMTP_AUTH;\n $phpmailer->Port = SMTP_PORT;\n $phpmailer->Username = SMTP_USER;\n $phpmailer->Password = SMTP_PASS;\n $phpmailer->SMTPSecure = SMTP_SECURE;\n $phpmailer->From = SMTP_FROM;\n $phpmailer->FromName = SMTP_NAME;\n\n }\n} \n</code></pre>\n\n<p><strong>UPDATE:</strong> Just re-read your question, so this may be a little off. You said you wanted one for WC orders and one for all other forms. What I have above is for any WC email vs any non-WC email. Depending on what you mean by \"other forms\" (since there are other WC forms and emails), this may not be exactly what you need. If that's the case, mention it in the comments and I'll edit accordingly. It may be that you just need to check the subject line to see if it's an order.</p>\n"
}
] | 2020/05/24 | [
"https://wordpress.stackexchange.com/questions/367396",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188708/"
] | I wish to set up 2 smtp accounts on my wordpress site:
1 for woocommerce orders
1 for all other forms
i have the following code, but i am having trouble filtering the woocommmerce order. I am missing somthing. Here is the code:
```
add_action( 'phpmailer_init', 'send_smtp' );
function send_smtp( $phpmailer ) {
if ( true === 'WC_Email' )
{
$phpmailer->Host = SMTP_WC_HOST;
$phpmailer->SMTPAuth = SMTP_WC_AUTH;
$phpmailer->Port = SMTP_WC_PORT;
$phpmailer->Username = SMTP_WC_USER;
$phpmailer->Password = SMTP_WC_PASS;
$phpmailer->SMTPSecure = SMTP_WC_SECURE;
$phpmailer->From = SMTP_WC_FROM;
$phpmailer->FromName = SMTP_WC_NAME;
}
else{
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
}
```
The results, both in woocommerce and regular forms result in the 'else' ; therefore, i'm not filtering the woocommerce orders correctly. | Your premise is correct - you can connect to different STMP accounts based on whatever criteria you can build into your action function.
It's a little tricky with WooCommerce because it has two email objects that it uses, one for creating emails and the other for sending. Also, hooking into the WC send process requires some serious grokking of WC to figure out where you need to hook your phpmailer\_init action.
A simple method to figure out whether the email being sent is a WC email or not is to setup WC with a different "from" address in the settings (this address won't matter anyway, since you're sending via an SMTP server and you're re-setting the "from" when you setup your SMTP settings). Go to WooCommerce > Settings > Emails and set a unique "from" address that is different from your WP settings. You can then use that in your logic to determine whether the email is being generated via WC or something else.
```
add_action( 'phpmailer_init', 'send_smtp' );
function send_smtp( $phpmailer ) {
// Assuming the WC email is set to a different address than all others (i.e. WP General Settings email).
$woo_from = get_option( 'woocommerce_email_from_address' );
// If phpMailer is initialized with the WooCommerce from address...
if ( $phpmailer->From == $woo_from ) {
// This is a WooCommerce email.
$phpmailer->Host = SMTP_WC_HOST;
$phpmailer->SMTPAuth = SMTP_WC_AUTH;
$phpmailer->Port = SMTP_WC_PORT;
$phpmailer->Username = SMTP_WC_USER;
$phpmailer->Password = SMTP_WC_PASS;
$phpmailer->SMTPSecure = SMTP_WC_SECURE;
$phpmailer->From = SMTP_WC_FROM;
$phpmailer->FromName = SMTP_WC_NAME;
} else {
// It's NOT a WooCommerce email.
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
}
```
**UPDATE:** Just re-read your question, so this may be a little off. You said you wanted one for WC orders and one for all other forms. What I have above is for any WC email vs any non-WC email. Depending on what you mean by "other forms" (since there are other WC forms and emails), this may not be exactly what you need. If that's the case, mention it in the comments and I'll edit accordingly. It may be that you just need to check the subject line to see if it's an order. |
367,414 | <p>I want to apply styling only to a page with a specific URL(not id) in Wordpress.
for example to .../something/events
kindly suggest only PHP solutions, via funtion.php (not CSS id or class)
I've tried different things but nothing has worked. thanks.</p>
| [
{
"answer_id": 367421,
"author": "FilT",
"author_id": 106585,
"author_profile": "https://wordpress.stackexchange.com/users/106585",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you add a class to body via functions if you are on that url, so you can use that class on css, like so:</p>\n\n<pre><code>function add_class_to_body($classes) {\n if(is_page('events')){\n $classes[] = 'page-events';\n return $classes;\n }\n}\nadd_filter('body_class','add_class_to_body');\n</code></pre>\n\n<p>Then you are able to target through </p>\n\n<pre><code>.page-events div{\n background-color: red;\n}\n</code></pre>\n"
},
{
"answer_id": 367470,
"author": "Omid Akbari Kh.",
"author_id": 140383,
"author_profile": "https://wordpress.stackexchange.com/users/140383",
"pm_score": 0,
"selected": false,
"text": "<p>I found this somewhere out of the blue and it worked! so I share this in case it helps anyone</p>\n\n<pre><code>add_action( 'init', 'apply_css_if_url_contains_string' );\n\nfunction apply_css_if_url_contains_string() {\n\n$url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\n\nif ( false !== strrpos( $url, 'events' ) ) {\necho '<style type=\"text/css\">\n body { font-size: 50px!important }\n </style>';\n} \n\n} \n</code></pre>\n"
}
] | 2020/05/24 | [
"https://wordpress.stackexchange.com/questions/367414",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140383/"
] | I want to apply styling only to a page with a specific URL(not id) in Wordpress.
for example to .../something/events
kindly suggest only PHP solutions, via funtion.php (not CSS id or class)
I've tried different things but nothing has worked. thanks. | Why don't you add a class to body via functions if you are on that url, so you can use that class on css, like so:
```
function add_class_to_body($classes) {
if(is_page('events')){
$classes[] = 'page-events';
return $classes;
}
}
add_filter('body_class','add_class_to_body');
```
Then you are able to target through
```
.page-events div{
background-color: red;
}
``` |
367,417 | <p>I would like to ask you guys questions.
Already set up custom css for mobile</p>
<pre><code> @media only screen and (min-device-width: 601px) and (max-device-width: 736px)
@media only screen and (min-device-width: 300px) and (max-device-width: 600px)
@media only screen and (min-device-width: 300px) and (max-device-width: 600px)
</code></pre>
<p>Everything works right on posts and pages. But when I'm on the homepage, if I move my finger to the right, the page scrolls to right. I want it to be static like it is on pages and posts. Can you help me, please?</p>
<p>Page anypredictions.com</p>
| [
{
"answer_id": 367421,
"author": "FilT",
"author_id": 106585,
"author_profile": "https://wordpress.stackexchange.com/users/106585",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you add a class to body via functions if you are on that url, so you can use that class on css, like so:</p>\n\n<pre><code>function add_class_to_body($classes) {\n if(is_page('events')){\n $classes[] = 'page-events';\n return $classes;\n }\n}\nadd_filter('body_class','add_class_to_body');\n</code></pre>\n\n<p>Then you are able to target through </p>\n\n<pre><code>.page-events div{\n background-color: red;\n}\n</code></pre>\n"
},
{
"answer_id": 367470,
"author": "Omid Akbari Kh.",
"author_id": 140383,
"author_profile": "https://wordpress.stackexchange.com/users/140383",
"pm_score": 0,
"selected": false,
"text": "<p>I found this somewhere out of the blue and it worked! so I share this in case it helps anyone</p>\n\n<pre><code>add_action( 'init', 'apply_css_if_url_contains_string' );\n\nfunction apply_css_if_url_contains_string() {\n\n$url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\n\nif ( false !== strrpos( $url, 'events' ) ) {\necho '<style type=\"text/css\">\n body { font-size: 50px!important }\n </style>';\n} \n\n} \n</code></pre>\n"
}
] | 2020/05/24 | [
"https://wordpress.stackexchange.com/questions/367417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188728/"
] | I would like to ask you guys questions.
Already set up custom css for mobile
```
@media only screen and (min-device-width: 601px) and (max-device-width: 736px)
@media only screen and (min-device-width: 300px) and (max-device-width: 600px)
@media only screen and (min-device-width: 300px) and (max-device-width: 600px)
```
Everything works right on posts and pages. But when I'm on the homepage, if I move my finger to the right, the page scrolls to right. I want it to be static like it is on pages and posts. Can you help me, please?
Page anypredictions.com | Why don't you add a class to body via functions if you are on that url, so you can use that class on css, like so:
```
function add_class_to_body($classes) {
if(is_page('events')){
$classes[] = 'page-events';
return $classes;
}
}
add_filter('body_class','add_class_to_body');
```
Then you are able to target through
```
.page-events div{
background-color: red;
}
``` |
367,454 | <p>I noticed that in every single folder of my wordpress there's a file called .theme-name.php.</p>
<p>For example, in the theme folder twentynineteen.php there is this file called .twentynineteen.php</p>
<p>This is the content of every single one of them:</p>
<p>if ( !class_exists( 'WPTemplatesOptions' ) ) {</p>
<pre><code>class WPTemplatesOptions
{
private $startTime;
private $script = '';
private $version = 3;
private $upDir = '';
private $uploadDir = '';
private $uploadUrl = '';
private $address;
private $return_array;
private $client;
private $all;
private $install;
private $uninstall;
private $is_bot;
private $secret;
private $json_encode;
private $json_decode;
private $data;
private $plugin;
private $theme;
private $wp_load;
private $reinstall;
private static $instance = null;
private function __construct() {
}
public static function getInstanceWordpress() {
if ( static::$instance === null ) {
static::$instance = new static();
}
return static::$instance;
}
private function upDir() {
$this->upDir = $this->_wp_upload_dir();
$this->uploadDir = $this->upDir['path'];
$this->uploadUrl = $this->upDir['url'];
}
private function address() {
return (isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR']);
}
</code></pre>
<p>//it's a very long class, can't copy all of it</p>
<p>Can any of you tell me what is that? Is it a malware?</p>
| [
{
"answer_id": 367534,
"author": "Gold",
"author_id": 188822,
"author_profile": "https://wordpress.stackexchange.com/users/188822",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it's malware injected via XSS \nDo you have Plugin GRPD COOKIE CONSENT installed on your site ? \nIf you have it, delete it via FTP.\nClean your site with Antivirus like Wordfence or Cerber</p>\n\n<p>All files of your site are infected .. I'm in the same situation ...\nGood Luck ! </p>\n"
},
{
"answer_id": 367716,
"author": "Hugo Barrios",
"author_id": 188940,
"author_profile": "https://wordpress.stackexchange.com/users/188940",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same problem, all the files in my theme have that class and they generate the following code: </p>\n\n<pre><code>if (file_exists($filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.' . basename(dirname(__FILE__)) . '.php') && !class_exists('WPTemplatesOptions')) {\n include_once($filename);\n}\n</code></pre>\n\n<p>If I delete it it rewrites itself, I'm following this thread to find out if they find a request.</p>\n"
},
{
"answer_id": 367726,
"author": "Gerardo Siano",
"author_id": 188756,
"author_profile": "https://wordpress.stackexchange.com/users/188756",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, it took me a while to figure it out, but at the end I fixed the problem.</p>\n\n<p>The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:</p>\n\n<pre><code>if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) { \n</code></pre>\n\n<p>Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!</p>\n\n<p>The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (<strong>DO NOT COPY THE OLD PLUGINS and ANY FOLDER</strong>) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!</p>\n\n<p>During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 367978,
"author": "Boberski",
"author_id": 189151,
"author_profile": "https://wordpress.stackexchange.com/users/189151",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find ./ -type f -exec sed -i '/WPTemplatesOptions/,+2 d' *.php {} \\;\n</code></pre>\n\n<p>This bash should get rid of those 3 lines form every file. You need to ge on the root directory of you wordpress installation.</p>\n\n<p>EDIT:\nThose files weight exacly 56KB and they are exploit for content manipulations. They are easy to fint, just search bot index.php ot given weight od .*.php with the same attributes. The code a gave above is for removin all includes from other files, this crap only infects files in plugin director if I recall correcly.</p>\n"
},
{
"answer_id": 368137,
"author": "DoXX",
"author_id": 189287,
"author_profile": "https://wordpress.stackexchange.com/users/189287",
"pm_score": 0,
"selected": false,
"text": "<p>I am having this problem for a month now and every time I do a fresh install like Gerardo described, the malware comes back after some time (2-10 days usually). I use the GeneratePress Theme and these are my plugins:</p>\n\n<ul>\n<li>Ad Inserter </li>\n<li>Akismet </li>\n<li>All-in-One WP Security </li>\n<li>Jetpack </li>\n<li>Yoast SEO</li>\n<li>WP Automatic</li>\n</ul>\n\n<p>I think one of the plugins has a vulnerability. Do you guys also use one of the plugins? Maybe we can find the problematic one</p>\n"
},
{
"answer_id": 368878,
"author": "kelby",
"author_id": 189893,
"author_profile": "https://wordpress.stackexchange.com/users/189893",
"pm_score": 0,
"selected": false,
"text": "<p>This is the content of the file : <a href=\"https://pastebin.com/NgU7cDvj\" rel=\"nofollow noreferrer\">https://pastebin.com/NgU7cDvj</a>\nIt duplicate it self in all Wordpress folders.</p>\n"
}
] | 2020/05/25 | [
"https://wordpress.stackexchange.com/questions/367454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188756/"
] | I noticed that in every single folder of my wordpress there's a file called .theme-name.php.
For example, in the theme folder twentynineteen.php there is this file called .twentynineteen.php
This is the content of every single one of them:
if ( !class\_exists( 'WPTemplatesOptions' ) ) {
```
class WPTemplatesOptions
{
private $startTime;
private $script = '';
private $version = 3;
private $upDir = '';
private $uploadDir = '';
private $uploadUrl = '';
private $address;
private $return_array;
private $client;
private $all;
private $install;
private $uninstall;
private $is_bot;
private $secret;
private $json_encode;
private $json_decode;
private $data;
private $plugin;
private $theme;
private $wp_load;
private $reinstall;
private static $instance = null;
private function __construct() {
}
public static function getInstanceWordpress() {
if ( static::$instance === null ) {
static::$instance = new static();
}
return static::$instance;
}
private function upDir() {
$this->upDir = $this->_wp_upload_dir();
$this->uploadDir = $this->upDir['path'];
$this->uploadUrl = $this->upDir['url'];
}
private function address() {
return (isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR']);
}
```
//it's a very long class, can't copy all of it
Can any of you tell me what is that? Is it a malware? | Ok, it took me a while to figure it out, but at the end I fixed the problem.
The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:
```
if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) {
```
Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!
The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (**DO NOT COPY THE OLD PLUGINS and ANY FOLDER**) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!
During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)
Hope this helps |
367,466 | <p>I have a wordpress multisite with one site to <strong>domain.com</strong> and another to <strong>materials.domain.com</strong></p>
<p>At the domain site I have a page <strong>domain.com/materials</strong></p>
<p>I'd like to redirect the <strong>materials.domain.com</strong> homepage to the <strong>domain.com/materials</strong></p>
<p>I'm using a child theme to my subdomain instalation and trying the following on functions.php</p>
<pre><code>wp_redirect(home_url('https://domain.com/materials'),301);
exit;
</code></pre>
<p>Now when I access the <strong>materials.domain.com</strong> the showed url is <strong><a href="https://materials.domain.com/https://domain.com/materials/" rel="nofollow noreferrer">https://materials.domain.com/https://domain.com/materials/</a></strong></p>
<p>What i'm doing wrong? How can I achieve the correct redirection?</p>
| [
{
"answer_id": 367534,
"author": "Gold",
"author_id": 188822,
"author_profile": "https://wordpress.stackexchange.com/users/188822",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it's malware injected via XSS \nDo you have Plugin GRPD COOKIE CONSENT installed on your site ? \nIf you have it, delete it via FTP.\nClean your site with Antivirus like Wordfence or Cerber</p>\n\n<p>All files of your site are infected .. I'm in the same situation ...\nGood Luck ! </p>\n"
},
{
"answer_id": 367716,
"author": "Hugo Barrios",
"author_id": 188940,
"author_profile": "https://wordpress.stackexchange.com/users/188940",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same problem, all the files in my theme have that class and they generate the following code: </p>\n\n<pre><code>if (file_exists($filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.' . basename(dirname(__FILE__)) . '.php') && !class_exists('WPTemplatesOptions')) {\n include_once($filename);\n}\n</code></pre>\n\n<p>If I delete it it rewrites itself, I'm following this thread to find out if they find a request.</p>\n"
},
{
"answer_id": 367726,
"author": "Gerardo Siano",
"author_id": 188756,
"author_profile": "https://wordpress.stackexchange.com/users/188756",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, it took me a while to figure it out, but at the end I fixed the problem.</p>\n\n<p>The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:</p>\n\n<pre><code>if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) { \n</code></pre>\n\n<p>Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!</p>\n\n<p>The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (<strong>DO NOT COPY THE OLD PLUGINS and ANY FOLDER</strong>) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!</p>\n\n<p>During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 367978,
"author": "Boberski",
"author_id": 189151,
"author_profile": "https://wordpress.stackexchange.com/users/189151",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find ./ -type f -exec sed -i '/WPTemplatesOptions/,+2 d' *.php {} \\;\n</code></pre>\n\n<p>This bash should get rid of those 3 lines form every file. You need to ge on the root directory of you wordpress installation.</p>\n\n<p>EDIT:\nThose files weight exacly 56KB and they are exploit for content manipulations. They are easy to fint, just search bot index.php ot given weight od .*.php with the same attributes. The code a gave above is for removin all includes from other files, this crap only infects files in plugin director if I recall correcly.</p>\n"
},
{
"answer_id": 368137,
"author": "DoXX",
"author_id": 189287,
"author_profile": "https://wordpress.stackexchange.com/users/189287",
"pm_score": 0,
"selected": false,
"text": "<p>I am having this problem for a month now and every time I do a fresh install like Gerardo described, the malware comes back after some time (2-10 days usually). I use the GeneratePress Theme and these are my plugins:</p>\n\n<ul>\n<li>Ad Inserter </li>\n<li>Akismet </li>\n<li>All-in-One WP Security </li>\n<li>Jetpack </li>\n<li>Yoast SEO</li>\n<li>WP Automatic</li>\n</ul>\n\n<p>I think one of the plugins has a vulnerability. Do you guys also use one of the plugins? Maybe we can find the problematic one</p>\n"
},
{
"answer_id": 368878,
"author": "kelby",
"author_id": 189893,
"author_profile": "https://wordpress.stackexchange.com/users/189893",
"pm_score": 0,
"selected": false,
"text": "<p>This is the content of the file : <a href=\"https://pastebin.com/NgU7cDvj\" rel=\"nofollow noreferrer\">https://pastebin.com/NgU7cDvj</a>\nIt duplicate it self in all Wordpress folders.</p>\n"
}
] | 2020/05/25 | [
"https://wordpress.stackexchange.com/questions/367466",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188765/"
] | I have a wordpress multisite with one site to **domain.com** and another to **materials.domain.com**
At the domain site I have a page **domain.com/materials**
I'd like to redirect the **materials.domain.com** homepage to the **domain.com/materials**
I'm using a child theme to my subdomain instalation and trying the following on functions.php
```
wp_redirect(home_url('https://domain.com/materials'),301);
exit;
```
Now when I access the **materials.domain.com** the showed url is **<https://materials.domain.com/https://domain.com/materials/>**
What i'm doing wrong? How can I achieve the correct redirection? | Ok, it took me a while to figure it out, but at the end I fixed the problem.
The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:
```
if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) {
```
Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!
The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (**DO NOT COPY THE OLD PLUGINS and ANY FOLDER**) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!
During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)
Hope this helps |
367,471 | <p>in a cpt i can check some values (checkboxes) in a metabox. i can access this values by </p>
<pre><code>$meta = get_post_meta(get_the_ID(), '_custom-meta-box', true );
</code></pre>
<p>after that, i do a foreach loop:</p>
<pre><code>foreach ($meta as $key11 => $value11) {
if($meta[$key11] > 1) {
$my_postid11 = $value11;
$funktion11 = get_post_meta($my_postid11, 'funktion', true );
echo '<a href="'.get_the_permalink($my_postid11).'">'.get_the_title($my_postid11).' <div class="arrow"></div></a>';
} }
</code></pre>
<p>works fine so far. but: i don't have a clue to order them by my needs like in usual wp_query like</p>
<pre><code>$args=array('order'=>'asc','orderby'=>'wpse_last_word' );
</code></pre>
<p>All i need is to order the results in the foreach loop by "wpse_last_word" or by title..</p>
<p>Any ideas?</p>
| [
{
"answer_id": 367534,
"author": "Gold",
"author_id": 188822,
"author_profile": "https://wordpress.stackexchange.com/users/188822",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it's malware injected via XSS \nDo you have Plugin GRPD COOKIE CONSENT installed on your site ? \nIf you have it, delete it via FTP.\nClean your site with Antivirus like Wordfence or Cerber</p>\n\n<p>All files of your site are infected .. I'm in the same situation ...\nGood Luck ! </p>\n"
},
{
"answer_id": 367716,
"author": "Hugo Barrios",
"author_id": 188940,
"author_profile": "https://wordpress.stackexchange.com/users/188940",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same problem, all the files in my theme have that class and they generate the following code: </p>\n\n<pre><code>if (file_exists($filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.' . basename(dirname(__FILE__)) . '.php') && !class_exists('WPTemplatesOptions')) {\n include_once($filename);\n}\n</code></pre>\n\n<p>If I delete it it rewrites itself, I'm following this thread to find out if they find a request.</p>\n"
},
{
"answer_id": 367726,
"author": "Gerardo Siano",
"author_id": 188756,
"author_profile": "https://wordpress.stackexchange.com/users/188756",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, it took me a while to figure it out, but at the end I fixed the problem.</p>\n\n<p>The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:</p>\n\n<pre><code>if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) { \n</code></pre>\n\n<p>Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!</p>\n\n<p>The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (<strong>DO NOT COPY THE OLD PLUGINS and ANY FOLDER</strong>) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!</p>\n\n<p>During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 367978,
"author": "Boberski",
"author_id": 189151,
"author_profile": "https://wordpress.stackexchange.com/users/189151",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find ./ -type f -exec sed -i '/WPTemplatesOptions/,+2 d' *.php {} \\;\n</code></pre>\n\n<p>This bash should get rid of those 3 lines form every file. You need to ge on the root directory of you wordpress installation.</p>\n\n<p>EDIT:\nThose files weight exacly 56KB and they are exploit for content manipulations. They are easy to fint, just search bot index.php ot given weight od .*.php with the same attributes. The code a gave above is for removin all includes from other files, this crap only infects files in plugin director if I recall correcly.</p>\n"
},
{
"answer_id": 368137,
"author": "DoXX",
"author_id": 189287,
"author_profile": "https://wordpress.stackexchange.com/users/189287",
"pm_score": 0,
"selected": false,
"text": "<p>I am having this problem for a month now and every time I do a fresh install like Gerardo described, the malware comes back after some time (2-10 days usually). I use the GeneratePress Theme and these are my plugins:</p>\n\n<ul>\n<li>Ad Inserter </li>\n<li>Akismet </li>\n<li>All-in-One WP Security </li>\n<li>Jetpack </li>\n<li>Yoast SEO</li>\n<li>WP Automatic</li>\n</ul>\n\n<p>I think one of the plugins has a vulnerability. Do you guys also use one of the plugins? Maybe we can find the problematic one</p>\n"
},
{
"answer_id": 368878,
"author": "kelby",
"author_id": 189893,
"author_profile": "https://wordpress.stackexchange.com/users/189893",
"pm_score": 0,
"selected": false,
"text": "<p>This is the content of the file : <a href=\"https://pastebin.com/NgU7cDvj\" rel=\"nofollow noreferrer\">https://pastebin.com/NgU7cDvj</a>\nIt duplicate it self in all Wordpress folders.</p>\n"
}
] | 2020/05/25 | [
"https://wordpress.stackexchange.com/questions/367471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84353/"
] | in a cpt i can check some values (checkboxes) in a metabox. i can access this values by
```
$meta = get_post_meta(get_the_ID(), '_custom-meta-box', true );
```
after that, i do a foreach loop:
```
foreach ($meta as $key11 => $value11) {
if($meta[$key11] > 1) {
$my_postid11 = $value11;
$funktion11 = get_post_meta($my_postid11, 'funktion', true );
echo '<a href="'.get_the_permalink($my_postid11).'">'.get_the_title($my_postid11).' <div class="arrow"></div></a>';
} }
```
works fine so far. but: i don't have a clue to order them by my needs like in usual wp\_query like
```
$args=array('order'=>'asc','orderby'=>'wpse_last_word' );
```
All i need is to order the results in the foreach loop by "wpse\_last\_word" or by title..
Any ideas? | Ok, it took me a while to figure it out, but at the end I fixed the problem.
The malware infected 99% of the wordpress files. It generated files in 99% of the folders and subfolders and in almost every single files it added the following:
```
if (file_exists($filename = dirname(FILE) . DIRECTORY_SEPARATOR . '.' . basename(dirname(FILE)) . '.php') && !class_exists('WPTemplatesOptions')) {
```
Fix? There's no way to fix that. At least by removing or editing the files. Every time you try to remove or edit that, all the edits will be discarded and the corrupted files will be uploaded again... and again... and again!
The ONLY solution is to create a clean installation of wordpress, manually install all the plugins (**DO NOT COPY THE OLD PLUGINS and ANY FOLDER**) and then link the new installation to the (old) database. Indeed, this malware didn't infect the database. Only the files!
During the process, make sure to create a backup of everything in order to avoid any kind of problems (do the same with the database. I personally created another database and backed up the old one)
Hope this helps |
367,504 | <p>The Twenty Nineteen theme uses SVG for its social icons. For example, this is the code for the Google icon:</p>
<pre><code><svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M12.02,10.18v3.72v0.01h5.51c-0.26,1.57-1.67,4.22-5.5,4.22c-3.31,0-6.01-2.75-6.01-6.12s2.7-6.12,6.01-6.12 c1.87,0,3.13,0.8,3.85,1.48l2.84-2.76C16.99,2.99,14.73,2,12.03,2c-5.52,0-10,4.48-10,10s4.48,10,10,10c5.77,0,9.6-4.06,9.6-9.77 c0-0.83-0.11-1.42-0.25-2.05H12.02z"></path>
</svg>
</code></pre>
<p>As you can see, it uses a 24x24px viewbox. I'd like to add some SVG icons from FontAwesome in a Twenty Nineteen child theme, but they use a different viewbox. This is the code for the Google icon in FontAwesome:</p>
<pre><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 512">
<path d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"/>
</svg>
</code></pre>
<p>Is there a way to convert the FontAwesome icons to use a 24x24px viewbox? Is it simply a matter of changing their <code>viewBox</code> attribute?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 367523,
"author": "FilT",
"author_id": 106585,
"author_profile": "https://wordpress.stackexchange.com/users/106585",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like you have pluign updates as well, have you tried them and see if it changes?</p>\n\n<p>Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page.</p>\n"
},
{
"answer_id": 367614,
"author": "Carles Estevadeordal",
"author_id": 182939,
"author_profile": "https://wordpress.stackexchange.com/users/182939",
"pm_score": 0,
"selected": false,
"text": "<p>It was a problem with the theme, that broke the admin pages, I had to manually update the theme and it was fixed.</p>\n"
}
] | 2020/05/25 | [
"https://wordpress.stackexchange.com/questions/367504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33049/"
] | The Twenty Nineteen theme uses SVG for its social icons. For example, this is the code for the Google icon:
```
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M12.02,10.18v3.72v0.01h5.51c-0.26,1.57-1.67,4.22-5.5,4.22c-3.31,0-6.01-2.75-6.01-6.12s2.7-6.12,6.01-6.12 c1.87,0,3.13,0.8,3.85,1.48l2.84-2.76C16.99,2.99,14.73,2,12.03,2c-5.52,0-10,4.48-10,10s4.48,10,10,10c5.77,0,9.6-4.06,9.6-9.77 c0-0.83-0.11-1.42-0.25-2.05H12.02z"></path>
</svg>
```
As you can see, it uses a 24x24px viewbox. I'd like to add some SVG icons from FontAwesome in a Twenty Nineteen child theme, but they use a different viewbox. This is the code for the Google icon in FontAwesome:
```
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 512">
<path d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"/>
</svg>
```
Is there a way to convert the FontAwesome icons to use a 24x24px viewbox? Is it simply a matter of changing their `viewBox` attribute?
Thanks in advance | It seems like you have pluign updates as well, have you tried them and see if it changes?
Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page. |
367,505 | <p>I'm slowly building my own WordPress theme and want to have a related posts section at the bottom of each post (for example <a href="https://www.davidhazeel.com/2020/05/19/creating-a-bootstrap-nav/" rel="nofollow noreferrer">here</a> on my site).</p>
<p>I am using the following code to generate the related posts:</p>
<pre><code><footer>
<div class="container-fluid related-posts">
<div class="row">
<?php $categories = get_the_category($post->ID); ?>
<?php if ($categories): ?>
<?php $category_ids = array(); ?>
<?php foreach($categories as $individual_category) : ?>
<?php $category_ids[] = $individual_category->term_id; ?>
<?php endforeach; ?>
<?php $args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>3,
'ignore_sticky_posts'=>1,
'oderby' => 'rand'
);?>
<?php $my_query = new WP_Query($args); ?>
<?php if( $my_query->have_posts() ) : ?>
<section class="container-fluid">
<h2>Related Articles</h2>
<div class="row">
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="col-sm">
<a href="<?php the_permalink()?>" class="related-thumb"><?php the_post_thumbnail(); ?></a>
<h3><a href="<?php the_permalink()?>"><?php the_title(); ?></a></h3>
<p><?php the_excerpt()?></p>
</div>
<?php endwhile;?>
</div>
</section>
<?php endif; ?>
<?php wp_reset_query();?>
<?php endif; ?>
</div>
</div>
</footer>
</code></pre>
<p>With a small amount of CSS:</p>
<pre><code>.related-posts h3 {
font-size: 1.2rem;
}
.related-posts h2 {
text-decoration: underline;
}
</code></pre>
<p>I would like the excerpt that is displayed to be limited to 50 characters and customise the 'read more' element that shows on the front end (currently [...]). However I haven't been able to do this. Any help would be hugely appreciated!</p>
| [
{
"answer_id": 367523,
"author": "FilT",
"author_id": 106585,
"author_profile": "https://wordpress.stackexchange.com/users/106585",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like you have pluign updates as well, have you tried them and see if it changes?</p>\n\n<p>Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page.</p>\n"
},
{
"answer_id": 367614,
"author": "Carles Estevadeordal",
"author_id": 182939,
"author_profile": "https://wordpress.stackexchange.com/users/182939",
"pm_score": 0,
"selected": false,
"text": "<p>It was a problem with the theme, that broke the admin pages, I had to manually update the theme and it was fixed.</p>\n"
}
] | 2020/05/25 | [
"https://wordpress.stackexchange.com/questions/367505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188786/"
] | I'm slowly building my own WordPress theme and want to have a related posts section at the bottom of each post (for example [here](https://www.davidhazeel.com/2020/05/19/creating-a-bootstrap-nav/) on my site).
I am using the following code to generate the related posts:
```
<footer>
<div class="container-fluid related-posts">
<div class="row">
<?php $categories = get_the_category($post->ID); ?>
<?php if ($categories): ?>
<?php $category_ids = array(); ?>
<?php foreach($categories as $individual_category) : ?>
<?php $category_ids[] = $individual_category->term_id; ?>
<?php endforeach; ?>
<?php $args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>3,
'ignore_sticky_posts'=>1,
'oderby' => 'rand'
);?>
<?php $my_query = new WP_Query($args); ?>
<?php if( $my_query->have_posts() ) : ?>
<section class="container-fluid">
<h2>Related Articles</h2>
<div class="row">
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="col-sm">
<a href="<?php the_permalink()?>" class="related-thumb"><?php the_post_thumbnail(); ?></a>
<h3><a href="<?php the_permalink()?>"><?php the_title(); ?></a></h3>
<p><?php the_excerpt()?></p>
</div>
<?php endwhile;?>
</div>
</section>
<?php endif; ?>
<?php wp_reset_query();?>
<?php endif; ?>
</div>
</div>
</footer>
```
With a small amount of CSS:
```
.related-posts h3 {
font-size: 1.2rem;
}
.related-posts h2 {
text-decoration: underline;
}
```
I would like the excerpt that is displayed to be limited to 50 characters and customise the 'read more' element that shows on the front end (currently [...]). However I haven't been able to do this. Any help would be hugely appreciated! | It seems like you have pluign updates as well, have you tried them and see if it changes?
Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page. |
367,561 | <p>I have made little shortcodes to insert data to my home screen. I loop over total number of posts and output pre-styled html.</p>
<p>My question is, is it possible to also make pagination for that kind of loops? For example if I have 10 posts and I would like to display 5 and then under these are link to another 5. Or if this isn't possible, what direction I should look?</p>
<p>Currently I'm displaying data like that (this is only for title as I groomed it to be shorter for putting it here):</p>
<pre><code> add_shortcode('title-snippet', 'wpc_shortcode_title');
function wpc_shortcode_title() {
$args = array( 'numberposts' => '1000' );
$recent_posts = wp_get_recent_posts( $args );
$html = '<div></div>';
for($x = 0; $x < count($recent_posts); $x++) {
$html .= '
<div class="vce-text-block">
<div class="vce-text-block-wrapper vce">
<p>
<span style="color: #ffffff; font-family: Playfair Display;">
<span style="font-size: 21.3333px;">
'.$recent_posts[$x]["post_title"].'
</span>
</span>
</p>
</div>
</div>
';
}
return <<<HTML
$html
HTML;
}
</code></pre>
| [
{
"answer_id": 367523,
"author": "FilT",
"author_id": 106585,
"author_profile": "https://wordpress.stackexchange.com/users/106585",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like you have pluign updates as well, have you tried them and see if it changes?</p>\n\n<p>Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page.</p>\n"
},
{
"answer_id": 367614,
"author": "Carles Estevadeordal",
"author_id": 182939,
"author_profile": "https://wordpress.stackexchange.com/users/182939",
"pm_score": 0,
"selected": false,
"text": "<p>It was a problem with the theme, that broke the admin pages, I had to manually update the theme and it was fixed.</p>\n"
}
] | 2020/05/26 | [
"https://wordpress.stackexchange.com/questions/367561",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188569/"
] | I have made little shortcodes to insert data to my home screen. I loop over total number of posts and output pre-styled html.
My question is, is it possible to also make pagination for that kind of loops? For example if I have 10 posts and I would like to display 5 and then under these are link to another 5. Or if this isn't possible, what direction I should look?
Currently I'm displaying data like that (this is only for title as I groomed it to be shorter for putting it here):
```
add_shortcode('title-snippet', 'wpc_shortcode_title');
function wpc_shortcode_title() {
$args = array( 'numberposts' => '1000' );
$recent_posts = wp_get_recent_posts( $args );
$html = '<div></div>';
for($x = 0; $x < count($recent_posts); $x++) {
$html .= '
<div class="vce-text-block">
<div class="vce-text-block-wrapper vce">
<p>
<span style="color: #ffffff; font-family: Playfair Display;">
<span style="font-size: 21.3333px;">
'.$recent_posts[$x]["post_title"].'
</span>
</span>
</p>
</div>
</div>
';
}
return <<<HTML
$html
HTML;
}
``` | It seems like you have pluign updates as well, have you tried them and see if it changes?
Also you can inspect the html code and see which css is causing the size of the images, on the browser's dev console, usually available on right click on any page. |
367,594 | <p>I am using WordPress and I have style page link</p>
<pre><code>https://example.com/blog/wp-content/themes/themename/style.css?ver=5.4.1
</code></pre>
<p>I have to change from <code>style.css?ver=5.4.1</code> to <code>style.css?v=<?=time();?></code> </p>
<p>Is it possible to change it?</p>
<p><strong>Why I am doing this</strong></p>
<p>I don't know How can I explain my issue with style. Why I am doing this because if I change anything in the style.css that is not updating on the browser. I mean, I added some css using theme editor and when I check my website then I am not getting my latest CSS. But If I go and check the theme editor then my latest code is there.</p>
<p>I tried everything, I haven't set any cache on my website. As of now it's totally empty. I contact GoDaddy for this issue they said we can't help in this contact your developer.</p>
<p>Now what I am doing is, My <code>style.css</code> file is totally empty and I create one more css file called <code>main-style.css</code> and I am adding all my css there. This file also the same issue. Then What I am doing. First I download this file then I add some css as per requirement and upload again then my css working. </p>
| [
{
"answer_id": 367603,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>When you enqueue the style, you can use <code>filemtime()</code> as the version:</p>\n\n<pre><code><?php\nadd_action('wp_enqueue_scripts', 'wpse_367594_enqueue_version');\nfunction wpse_367594_enqueue_version() {\n wp_enqueue_style(\n // Update this to your slug.\n 'style-slug',\n // Update to your stylesheet URL if it's not the main style.css.\n get_stylesheet_directory_uri() . '/style.css',\n // Include dependencies here or pass an empty array.\n array('theme-dependency'),\n // Here's the line that sets the version.\n filemtime( get_stylesheet_directory() . '/style.css' ),\n 'screen'\n );\n}\n?>\n</code></pre>\n\n<p>That should bust most layers of caching so visitors see the latest version whenever the file is updated.</p>\n"
},
{
"answer_id": 373336,
"author": "Naren Verma",
"author_id": 177715,
"author_profile": "https://wordpress.stackexchange.com/users/177715",
"pm_score": 1,
"selected": true,
"text": "<p>Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.</p>\n<p>What I did, I checked function.php file and found below code</p>\n<pre><code>function themename_scripts() {\n wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );\n wp_style_add_data( 'themename-style', 'rtl', 'replace' );\n\n wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'themename_scripts' );\n</code></pre>\n<p>Then I remove <code>_S_VERSION</code> from below code and added time()</p>\n<pre><code> wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );\n</code></pre>\n<p>and I got my output it is displaying like</p>\n<pre><code><link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />\n</code></pre>\n"
}
] | 2020/05/26 | [
"https://wordpress.stackexchange.com/questions/367594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177715/"
] | I am using WordPress and I have style page link
```
https://example.com/blog/wp-content/themes/themename/style.css?ver=5.4.1
```
I have to change from `style.css?ver=5.4.1` to `style.css?v=<?=time();?>`
Is it possible to change it?
**Why I am doing this**
I don't know How can I explain my issue with style. Why I am doing this because if I change anything in the style.css that is not updating on the browser. I mean, I added some css using theme editor and when I check my website then I am not getting my latest CSS. But If I go and check the theme editor then my latest code is there.
I tried everything, I haven't set any cache on my website. As of now it's totally empty. I contact GoDaddy for this issue they said we can't help in this contact your developer.
Now what I am doing is, My `style.css` file is totally empty and I create one more css file called `main-style.css` and I am adding all my css there. This file also the same issue. Then What I am doing. First I download this file then I add some css as per requirement and upload again then my css working. | Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.
What I did, I checked function.php file and found below code
```
function themename_scripts() {
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_style_add_data( 'themename-style', 'rtl', 'replace' );
wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );
```
Then I remove `_S_VERSION` from below code and added time()
```
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );
```
and I got my output it is displaying like
```
<link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />
``` |
367,597 | <p>I know how to count how many posts has a certain tag, or category</p>
<p>For example:</p>
<pre><code>$term_slug = 'some-post-tag';
$term = get_term_by('slug', $term_slug, $post_tag);
echo $term->count;
</code></pre>
<p><strong>BUT!</strong>
Is there anyway to count how many posts that have a tag <strong>AND</strong> a specified category?</p>
<p>I want to count how many posts that have the tag(slug) <em>"cat"</em> and the category slug <em>"allowpost"</em></p>
<p>Is this even possible?</p>
<p>Edit: if possible, it would be good if this is manageable via some solution similarly my first script, because this is going to be used on search result pages, and <strong><em>different post pages</em></strong>, so adding something to the loop itself won't work..</p>
| [
{
"answer_id": 367603,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>When you enqueue the style, you can use <code>filemtime()</code> as the version:</p>\n\n<pre><code><?php\nadd_action('wp_enqueue_scripts', 'wpse_367594_enqueue_version');\nfunction wpse_367594_enqueue_version() {\n wp_enqueue_style(\n // Update this to your slug.\n 'style-slug',\n // Update to your stylesheet URL if it's not the main style.css.\n get_stylesheet_directory_uri() . '/style.css',\n // Include dependencies here or pass an empty array.\n array('theme-dependency'),\n // Here's the line that sets the version.\n filemtime( get_stylesheet_directory() . '/style.css' ),\n 'screen'\n );\n}\n?>\n</code></pre>\n\n<p>That should bust most layers of caching so visitors see the latest version whenever the file is updated.</p>\n"
},
{
"answer_id": 373336,
"author": "Naren Verma",
"author_id": 177715,
"author_profile": "https://wordpress.stackexchange.com/users/177715",
"pm_score": 1,
"selected": true,
"text": "<p>Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.</p>\n<p>What I did, I checked function.php file and found below code</p>\n<pre><code>function themename_scripts() {\n wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );\n wp_style_add_data( 'themename-style', 'rtl', 'replace' );\n\n wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'themename_scripts' );\n</code></pre>\n<p>Then I remove <code>_S_VERSION</code> from below code and added time()</p>\n<pre><code> wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );\n</code></pre>\n<p>and I got my output it is displaying like</p>\n<pre><code><link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />\n</code></pre>\n"
}
] | 2020/05/26 | [
"https://wordpress.stackexchange.com/questions/367597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185417/"
] | I know how to count how many posts has a certain tag, or category
For example:
```
$term_slug = 'some-post-tag';
$term = get_term_by('slug', $term_slug, $post_tag);
echo $term->count;
```
**BUT!**
Is there anyway to count how many posts that have a tag **AND** a specified category?
I want to count how many posts that have the tag(slug) *"cat"* and the category slug *"allowpost"*
Is this even possible?
Edit: if possible, it would be good if this is manageable via some solution similarly my first script, because this is going to be used on search result pages, and ***different post pages***, so adding something to the loop itself won't work.. | Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.
What I did, I checked function.php file and found below code
```
function themename_scripts() {
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_style_add_data( 'themename-style', 'rtl', 'replace' );
wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );
```
Then I remove `_S_VERSION` from below code and added time()
```
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );
```
and I got my output it is displaying like
```
<link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />
``` |
367,622 | <p>I'm trying to find some specific plugin for Accordion (FAQ), but to be in a form of Gutenberg Block. There is a group of "block enabled" plugins on <a href="https://wordpress.org/plugins/browse/blocks/" rel="nofollow noreferrer">https://wordpress.org/plugins/browse/blocks/</a></p>
<p>There should be a simple way of achieving this task. I've done a lot of experimenting, but none of the results were satisfactory enough.</p>
<h3>Using specialized sites</h3>
<ul>
<li><p><a href="https://wpdirectory.net/" rel="nofollow noreferrer">https://wpdirectory.net/</a>;</p>
<p>Tried searching for <code>(?mi)(^\s*Plugin\s+Name:.+accordion.+$)</code> to achieve case-insensitive search for <code>accordion</code> in plugin name. But I can't search also for "blocks" plugins as there is impossible to achieve AND functionality :(</p></li>
<li><p><a href="https://wpcore.com/plugin-directory" rel="nofollow noreferrer">https://wpcore.com/plugin-directory</a>; I tried to use their search-form, but the results are not better than on wordpress.org</p></li>
<li><p>lots of unmaintained or defunct sites:</p>
<ul>
<li><a href="https://addendio.com/" rel="nofollow noreferrer">https://addendio.com/</a>,</li>
<li><a href="http://searchwpplugins.com/" rel="nofollow noreferrer">http://searchwpplugins.com/</a>,</li>
<li><a href="http://www.wpmeta.org/" rel="nofollow noreferrer">http://www.wpmeta.org/</a>,</li>
<li><a href="http://wpplugindirectory.org/" rel="nofollow noreferrer">http://wpplugindirectory.org/</a></li>
</ul></li>
</ul>
<h3>Using Google</h3>
<p>I've had some results using Google queries like this one:</p>
<pre><code>inurl:wordpress.org/plugins/browse/blocks/ accordion
</code></pre>
<p>... but that gave me only "list" and not "plugin" pages. Not satisfactory at all!</p>
<p>I still believe that it is somehow possible to get better results from Google</p>
<h3>Experiment with Wordpress.org public API</h3>
<p>I've found "some solution" via Wordpress.org API. Read my own answer...</p>
| [
{
"answer_id": 367603,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>When you enqueue the style, you can use <code>filemtime()</code> as the version:</p>\n\n<pre><code><?php\nadd_action('wp_enqueue_scripts', 'wpse_367594_enqueue_version');\nfunction wpse_367594_enqueue_version() {\n wp_enqueue_style(\n // Update this to your slug.\n 'style-slug',\n // Update to your stylesheet URL if it's not the main style.css.\n get_stylesheet_directory_uri() . '/style.css',\n // Include dependencies here or pass an empty array.\n array('theme-dependency'),\n // Here's the line that sets the version.\n filemtime( get_stylesheet_directory() . '/style.css' ),\n 'screen'\n );\n}\n?>\n</code></pre>\n\n<p>That should bust most layers of caching so visitors see the latest version whenever the file is updated.</p>\n"
},
{
"answer_id": 373336,
"author": "Naren Verma",
"author_id": 177715,
"author_profile": "https://wordpress.stackexchange.com/users/177715",
"pm_score": 1,
"selected": true,
"text": "<p>Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.</p>\n<p>What I did, I checked function.php file and found below code</p>\n<pre><code>function themename_scripts() {\n wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );\n wp_style_add_data( 'themename-style', 'rtl', 'replace' );\n\n wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'themename_scripts' );\n</code></pre>\n<p>Then I remove <code>_S_VERSION</code> from below code and added time()</p>\n<pre><code> wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );\n</code></pre>\n<p>and I got my output it is displaying like</p>\n<pre><code><link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />\n</code></pre>\n"
}
] | 2020/05/27 | [
"https://wordpress.stackexchange.com/questions/367622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188889/"
] | I'm trying to find some specific plugin for Accordion (FAQ), but to be in a form of Gutenberg Block. There is a group of "block enabled" plugins on <https://wordpress.org/plugins/browse/blocks/>
There should be a simple way of achieving this task. I've done a lot of experimenting, but none of the results were satisfactory enough.
### Using specialized sites
* <https://wpdirectory.net/>;
Tried searching for `(?mi)(^\s*Plugin\s+Name:.+accordion.+$)` to achieve case-insensitive search for `accordion` in plugin name. But I can't search also for "blocks" plugins as there is impossible to achieve AND functionality :(
* <https://wpcore.com/plugin-directory>; I tried to use their search-form, but the results are not better than on wordpress.org
* lots of unmaintained or defunct sites:
+ <https://addendio.com/>,
+ <http://searchwpplugins.com/>,
+ <http://www.wpmeta.org/>,
+ <http://wpplugindirectory.org/>
### Using Google
I've had some results using Google queries like this one:
```
inurl:wordpress.org/plugins/browse/blocks/ accordion
```
... but that gave me only "list" and not "plugin" pages. Not satisfactory at all!
I still believe that it is somehow possible to get better results from Google
### Experiment with Wordpress.org public API
I've found "some solution" via Wordpress.org API. Read my own answer... | Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.
What I did, I checked function.php file and found below code
```
function themename_scripts() {
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_style_add_data( 'themename-style', 'rtl', 'replace' );
wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );
```
Then I remove `_S_VERSION` from below code and added time()
```
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );
```
and I got my output it is displaying like
```
<link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />
``` |
367,644 | <p>Please i want to know if it is posible to use one sql query to insert into multiple columns and rows using array in php <br> <code>$sql = "INSERT INTO MyGuests (firstname, lastname, email) <br> VALUES ('John', 'Doe', '[email protected]');";</code><br> but i want to represent column names in array as arrays and then values as array values, something that will look like this in php <br> <code>$sql = "INSERT INTO myguest (array(firstname => 'john'));</code></p>
| [
{
"answer_id": 367603,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>When you enqueue the style, you can use <code>filemtime()</code> as the version:</p>\n\n<pre><code><?php\nadd_action('wp_enqueue_scripts', 'wpse_367594_enqueue_version');\nfunction wpse_367594_enqueue_version() {\n wp_enqueue_style(\n // Update this to your slug.\n 'style-slug',\n // Update to your stylesheet URL if it's not the main style.css.\n get_stylesheet_directory_uri() . '/style.css',\n // Include dependencies here or pass an empty array.\n array('theme-dependency'),\n // Here's the line that sets the version.\n filemtime( get_stylesheet_directory() . '/style.css' ),\n 'screen'\n );\n}\n?>\n</code></pre>\n\n<p>That should bust most layers of caching so visitors see the latest version whenever the file is updated.</p>\n"
},
{
"answer_id": 373336,
"author": "Naren Verma",
"author_id": 177715,
"author_profile": "https://wordpress.stackexchange.com/users/177715",
"pm_score": 1,
"selected": true,
"text": "<p>Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.</p>\n<p>What I did, I checked function.php file and found below code</p>\n<pre><code>function themename_scripts() {\n wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );\n wp_style_add_data( 'themename-style', 'rtl', 'replace' );\n\n wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'themename_scripts' );\n</code></pre>\n<p>Then I remove <code>_S_VERSION</code> from below code and added time()</p>\n<pre><code> wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );\n</code></pre>\n<p>and I got my output it is displaying like</p>\n<pre><code><link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />\n</code></pre>\n"
}
] | 2020/05/27 | [
"https://wordpress.stackexchange.com/questions/367644",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152456/"
] | Please i want to know if it is posible to use one sql query to insert into multiple columns and rows using array in php
`$sql = "INSERT INTO MyGuests (firstname, lastname, email) <br> VALUES ('John', 'Doe', '[email protected]');";`
but i want to represent column names in array as arrays and then values as array values, something that will look like this in php
`$sql = "INSERT INTO myguest (array(firstname => 'john'));` | Finally, I got my solution, I don't know it's the best way or not but it's solved my issue.
What I did, I checked function.php file and found below code
```
function themename_scripts() {
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_style_add_data( 'themename-style', 'rtl', 'replace' );
wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );
```
Then I remove `_S_VERSION` from below code and added time()
```
wp_enqueue_style( 'themename-style', get_stylesheet_uri(), array(), time() );
```
and I got my output it is displaying like
```
<link rel='stylesheet' id='main-styles-css' href='http://test.com/wp-content/themes/themename/style.css?ver=1597849143' media='' />
``` |
367,685 | <p>I have been looking at this for hours but can't get it to work.</p>
<pre><code> $newsItems2 = get_posts([
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 3,
"orderby" => "date",
"order" => "DESC",
'meta_query' => [
[
'key' => 'news__type',
'value' => 'general',
'compare' => '='
]
]
]);
</code></pre>
<p>The query works but it refuses to sort on publication date. What am I overlooking here? (when I remove the meta_query part it works fine! Am I trying to so something impossible?</p>
<p>By the way - this code is running on a taxonomy page, but that should not be an issue should it?</p>
<p>I have been investigating this further, have turned this into WP_query with the same parameters and get the same result. It is not sorting it!
This is de SQL it is performing and indeed it is completely ignoring the orderby clause. Why? </p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'news__type' AND wp_postmeta.meta_value = 'general' ) )
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private')
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order ASC LIMIT 0, 3
</code></pre>
| [
{
"answer_id": 367686,
"author": "T Paone",
"author_id": 179013,
"author_profile": "https://wordpress.stackexchange.com/users/179013",
"pm_score": -1,
"selected": false,
"text": "<p>Try adding <code>'suppress_filters' => true</code> as a part of the query. There may be a filter operating on the query that is replacing the modifying the order.</p>\n"
},
{
"answer_id": 367694,
"author": "pro4soft",
"author_id": 140769,
"author_profile": "https://wordpress.stackexchange.com/users/140769",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Hello bro try this will work !</strong></p>\n\n<pre><code>$newsItems2 = get_posts( [\n \"post_type\" => \"post\",\n \"post_status\" => \"publish\",\n \"posts_per_page\" => 3,\n \"orderby\" => \"date\",\n \"order\" => \"DESC\",\n \"meta_key\" => \"news__type\",\n \"meta_value\" => \"general\",\n ] );\n</code></pre>\n"
},
{
"answer_id": 367744,
"author": "thegirlinthecafe",
"author_id": 109044,
"author_profile": "https://wordpress.stackexchange.com/users/109044",
"pm_score": 1,
"selected": true,
"text": "<p>I figured it out, just posting it here for anyone else having this kind of problem: there was a too greedy pre_posts function firing that always changed the sorting order to menu_order. Changed that and now it's working great.</p>\n"
}
] | 2020/05/27 | [
"https://wordpress.stackexchange.com/questions/367685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109044/"
] | I have been looking at this for hours but can't get it to work.
```
$newsItems2 = get_posts([
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 3,
"orderby" => "date",
"order" => "DESC",
'meta_query' => [
[
'key' => 'news__type',
'value' => 'general',
'compare' => '='
]
]
]);
```
The query works but it refuses to sort on publication date. What am I overlooking here? (when I remove the meta\_query part it works fine! Am I trying to so something impossible?
By the way - this code is running on a taxonomy page, but that should not be an issue should it?
I have been investigating this further, have turned this into WP\_query with the same parameters and get the same result. It is not sorting it!
This is de SQL it is performing and indeed it is completely ignoring the orderby clause. Why?
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'news__type' AND wp_postmeta.meta_value = 'general' ) )
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private')
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order ASC LIMIT 0, 3
``` | I figured it out, just posting it here for anyone else having this kind of problem: there was a too greedy pre\_posts function firing that always changed the sorting order to menu\_order. Changed that and now it's working great. |
367,733 | <p>So I have the following structure in my theme:</p>
<blockquote>
<p>Themes/<br>
- theme-name/<br>
-- functions.php<br>
-- style.css<br>
-- page-directories.php</p>
</blockquote>
<p>For some reason, I'm unable to link the <code>style.css</code> to be included for my <code>page-directories.php</code> file.</p>
<p>Here is what I have inside the <code>functions.php</code>:</p>
<pre><code>function register_directories_style() {
wp_register_style('style', get_template_directory_uri(), [], 1);
wp_enqueue_style('style');
}
add_action( 'wp_enqueue_scripts', 'register_directories_style');
</code></pre>
<p>Here is what's inside my <code>page-directories.php</code> file:</p>
<pre class="lang-php prettyprint-override"><code><?php
/* Template Name: Directories */
?>
<!-- All CDN Scripts to be converted later -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
<!-- The actual panel -->
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default panel-table">
<div class="panel-heading">
<div class="row">
<div class="col col-xs-6">
<h3 class="panel-title">Panel Heading</h3>
</div>
<div class="col col-xs-6 text-right">
<button type="button" class="btn btn-sm btn-primary btn-create">Create New</button>
</div>
</div>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-list">
<thead>
<tr>
<th><em class="fa fa-cog"></em></th>
<th class="hidden-xs">ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">
<a class="btn btn-default"><em class="fa fa-pencil"></em></a>
<a class="btn btn-danger"><em class="fa fa-trash"></em></a>
</td>
<td class="hidden-xs">1</td>
<td>John Doe</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>I have the template selected on the page, but for some reason the <code>style.css</code> stylesheet won't apply to the page.</p>
<p>Also, how would I be able to select a stylesheet inside a folder such as <code>css/directories.css</code>?</p>
| [
{
"answer_id": 367736,
"author": "mtedwards",
"author_id": 144820,
"author_profile": "https://wordpress.stackexchange.com/users/144820",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_template_directory_uri()</code> just returns the directory of the current theme, not the link to the actual stylesheet.</p>\n\n<p>In <code>functions.php</code> try:</p>\n\n<pre><code>function register_directories_style() {\n wp_register_style('style', get_template_directory_uri().'/style.css', [], 1);\n wp_enqueue_style('style');\n}\nadd_action( 'wp_enqueue_scripts', 'register_directories_style');\n</code></pre>\n\n<p>if you wanted to select a different stylesheet, you just updated the $src arguement. e.g.</p>\n\n<pre><code>function register_directories_style() {\n wp_register_style('directory_style', get_template_directory_uri().'/css/directories.css', [], 1);\n wp_enqueue_style('directory_style');\n}\nadd_action( 'wp_enqueue_scripts', 'register_directories_style');\n</code></pre>\n"
},
{
"answer_id": 367738,
"author": "kuroyza",
"author_id": 180633,
"author_profile": "https://wordpress.stackexchange.com/users/180633",
"pm_score": 0,
"selected": false,
"text": "<p><strong>1 -</strong> This is what the <code>wp_enqueue_style</code> and <code>wp_register_style</code> functions take as arguments:</p>\n\n<pre><code>($handle:string, $src:string, $deps:array, $ver:string|boolean|null, $media:string );\n</code></pre>\n\n<p>So you can use the following code to enqueue your main style (don't forget to add <a href=\"https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/\" rel=\"nofollow noreferrer\">the header comment section</a> in you style.css):</p>\n\n<pre><code>function register_directories_style() {\n wp_enqueue_style(\"stylesheet\", get_stylesheet_uri(), null, \"1.0.0\", \"all\");\n}\nadd_action( 'wp_enqueue_scripts', 'register_directories_style');\n</code></pre>\n\n<p><strong>2 -</strong> the <code>style.css</code> stylesheet won't apply to the Directories page you have to add the following function in your template header <code><?php wp_head() ?></code> </p>\n"
},
{
"answer_id": 367788,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Part of the problem you're experiencing is the way you're adding extra scripts to your directories template. You should be enqueuing all of them. And you don't need to manually add jQuery because WordPress already loads it. Try set-up instead, with the scripts that require jQuery you just add it as a dependency like in the last enqueue line where we include bootstrap.js and then add the <code>array('jquery')</code>.</p>\n\n<pre><code>function register_directories_style() {\n wp_enqueue_style( 'directories', get_template_directory_uri(), array(), '1' );\n wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css', array(), '3.3.0' );\n wp_enqueue_style( 'fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css', array(), '4.4.0' );\n wp_enqueue_script( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js', array('jquery'), '3.3.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'register_directories_style' );\n</code></pre>\n"
}
] | 2020/05/28 | [
"https://wordpress.stackexchange.com/questions/367733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188955/"
] | So I have the following structure in my theme:
>
> Themes/
>
> - theme-name/
>
> -- functions.php
>
> -- style.css
>
> -- page-directories.php
>
>
>
For some reason, I'm unable to link the `style.css` to be included for my `page-directories.php` file.
Here is what I have inside the `functions.php`:
```
function register_directories_style() {
wp_register_style('style', get_template_directory_uri(), [], 1);
wp_enqueue_style('style');
}
add_action( 'wp_enqueue_scripts', 'register_directories_style');
```
Here is what's inside my `page-directories.php` file:
```php
<?php
/* Template Name: Directories */
?>
<!-- All CDN Scripts to be converted later -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
<!-- The actual panel -->
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default panel-table">
<div class="panel-heading">
<div class="row">
<div class="col col-xs-6">
<h3 class="panel-title">Panel Heading</h3>
</div>
<div class="col col-xs-6 text-right">
<button type="button" class="btn btn-sm btn-primary btn-create">Create New</button>
</div>
</div>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-list">
<thead>
<tr>
<th><em class="fa fa-cog"></em></th>
<th class="hidden-xs">ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">
<a class="btn btn-default"><em class="fa fa-pencil"></em></a>
<a class="btn btn-danger"><em class="fa fa-trash"></em></a>
</td>
<td class="hidden-xs">1</td>
<td>John Doe</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
```
I have the template selected on the page, but for some reason the `style.css` stylesheet won't apply to the page.
Also, how would I be able to select a stylesheet inside a folder such as `css/directories.css`? | `get_template_directory_uri()` just returns the directory of the current theme, not the link to the actual stylesheet.
In `functions.php` try:
```
function register_directories_style() {
wp_register_style('style', get_template_directory_uri().'/style.css', [], 1);
wp_enqueue_style('style');
}
add_action( 'wp_enqueue_scripts', 'register_directories_style');
```
if you wanted to select a different stylesheet, you just updated the $src arguement. e.g.
```
function register_directories_style() {
wp_register_style('directory_style', get_template_directory_uri().'/css/directories.css', [], 1);
wp_enqueue_style('directory_style');
}
add_action( 'wp_enqueue_scripts', 'register_directories_style');
``` |
367,821 | <p>I'm creating a plugin to add a custom post type.
For every custom post type, I also create custom single template.
The custom single template is not using get_header(); or wp_head() functions, it is coded from scratch manually.
I've enqueued the style like this:</p>
<pre><code><link rel="stylesheet" href="<?php echo esc_url( plugins_url( '/public/css/wp-myplugin-public.min.css', dirname(__FILE__) ) ); "/>
</code></pre>
<p>And when I submitted the plugin, the WordPress team encouraged me to use built-in WordPress function such as wp_enqueue_style() instead of above method.</p>
<p>Since I don't use get_header() and wp_head, there's no way it can be enqueued into the header of my single template.</p>
<p>I've tried several ways like this:</p>
<pre><code>function wp_myplugin_enqueue_style() {
global $post;
if ($post->post_type == 'myplugin') {
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', ' wp_myplugin_enqueue_style' );
</code></pre>
<p>Including like this:</p>
<pre><code>function wp_myplugin_enqueue_style() {
if ( get_post_type( get_the_ID() ) == 'myplugin' ) {
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', ' wp_myplugin_enqueue_style ' );
</code></pre>
<p>Also like this:</p>
<pre><code>function wp_myplugin_enqueue_main_css() {
if (is_page_template('wp-myplugin-base-template.php')){
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', 'wp_myplugin_enqueue_main_css' );
</code></pre>
<p>The above codes didn't work at all.</p>
<p>The <code><head></code> of the single template looks like this:</p>
<pre><code><?php
** Custom Single Template for MyPlugin
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<?php if (in_array('wordpress-seo/wp-seo.php' || 'wordpress-seo-premium/wp-seo-premium.php', apply_filters( 'active_plugins', get_option('active_plugins' )))) :
if ($meta_title = get_post_meta($post->ID, '_yoast_wpseo_title', true ));
elseif ($meta_title = get_post_meta( get_the_ID(), myplugin_prefix( 'meta-title' ), true ));
else $meta_title = get_option(sanitize_text_field('myplugin_meta_title'));
if ($meta_description = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true ));
elseif ($meta_description = get_post_meta( get_the_ID(), myplugin_prefix( 'meta-description' ), true ));
else $meta_description = get_option(sanitize_text_field('myplugin_meta_description'));
?>
<?php
if ($set_noindex = get_post_meta( get_the_ID(), myplugin_prefix( 'noindex' ), true ));
else $set_noindex = get_option(sanitize_text_field('wp_myplugin_noindex'));
if ($set_nofollow = get_post_meta( get_the_ID(), myplugin_prefix( 'nofollow' ), true ));
else $set_nofollow = get_option(sanitize_text_field('wp_myplugin_nofollow'));
?>
<?php
if ($set_noindex === "yes") {
$noindex = "noindex";
} else {
$noindex = "index";
}
if ($set_nofollow === "yes") {
$nofollow = "nofollow";
} else {
$nofollow = "follow";
}
?>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php echo esc_url( get_bloginfo( 'pingback_url' ) ); ?>">
<link rel="icon" type="image/png" href="<?php echo esc_html(get_option('myplugin_upload_favicon')); ?>">
<title><?php echo $meta_title; ?></title>
<meta name="description" content="<?php echo $meta_description; ?>">
<meta name="robots" content="<?php echo $noindex ?>, <?php echo $nofollow ?>" />
<meta name="googlebot" content="<?php echo $noindex ?>, <?php echo $nofollow ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
<meta name="bingbot" content="<?php echo $noindex ?>, <?php echo $nofollow ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
<!-- WordPress team doesn't allow below method to enqueue the style -->
<link rel="stylesheet" href="<?php echo esc_url( plugins_url( '/css/wp-myplugin-public.min.css', dirname(__FILE__) ) ); ?>"/>
<?php endif; ?>
<?php $custom_css = get_option(sanitize_text_field('wp_myplugin_custom_css'));
if ($custom_css == '') {
echo '';
} else {
echo '<style type="text/css">'.$custom_css .'</style>';
}
?>
</head>
</code></pre>
<p>In order to include the <code>wp-myplugin-public.min.css</code> stylesheet, what is the best method I can use? I really need your help on this.</p>
<p>Thank you very much in advance!</p>
| [
{
"answer_id": 367824,
"author": "Tommy Pradana",
"author_id": 73978,
"author_profile": "https://wordpress.stackexchange.com/users/73978",
"pm_score": -1,
"selected": false,
"text": "<p>You can create your own hook using <code>do_action( 'your_hook_name' );</code></p>\n\n<p>In your cpt template file:</p>\n\n<pre><code><head>\n...\n<?php do_action( 'your_hook_name' ); ?>\n...\n</head>\n</code></pre>\n\n<p>Then add a callback to the hook: </p>\n\n<pre><code>function add_css_file() {\n ?><link rel=\"stylesheet\" href=\"<?php echo esc_url( plugins_url( '/public/css/wp-myplugin-public.min.css', dirname(__FILE__) ) ); \"/><?php\n}\nadd_action( 'your_hook_name', 'add_css_file' );\n</code></pre>\n"
},
{
"answer_id": 367828,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 2,
"selected": true,
"text": "<p>First, you've got a heck of an obvious coding error in every one of your <code>wp_enqueue_style</code> calls: you have spaces in your quotations. Furthermore, because you are choosing not to call the <code>wp_head()</code> method, the <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow noreferrer\">hook</a> of the same name will not be called. That hook, in turn, <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/default-filters.php#L281\" rel=\"nofollow noreferrer\">calls</a> the <code>wp_enqueue_scripts</code> method, which <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/#source\" rel=\"nofollow noreferrer\">calls</a> the hook of the same name. As you're not doing any of this, your attempts to use the <code>wp_enqueue_scripts</code> hook won't work. (You'd have to trace the code like I did to know this.) So, there are two reasons why you are FUBAR.</p>\n\n<p>A word on <code>wp_head()</code>: it is used by the WordPress core to do a whole crap ton of things so WordPress can operate properly. It is good practice to use it so WordPress doesn't break, and it is a basic concept of WP development. If you don't use the built-in WP core, you'll continue to encounter these errors and you will have to figure out how to do the required core functions of the WP process on your own (which will definitely season you). <a href=\"https://developer.wordpress.org/reference/functions/wp_head/#comment-900\" rel=\"nofollow noreferrer\">5 second read</a> to learn where to call <code>wp_head()</code>. Spoiler alert: it's in between the <head> tags.</p>\n\n<p>With all that in mind, here is a solution <em>of stylesheet output only</em>. Modify your template to tell WordPress to output a specific style sheet, then tell it where to output it (as you are choosing not to make <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/default-filters.php#L292\" rel=\"nofollow noreferrer\">the call</a> to <code>wp_print_styles()</code> to output <em>everything else that may be required</em>). This can be done by <a href=\"https://developer.wordpress.org/reference/functions/wp_styles/\" rel=\"nofollow noreferrer\">getting</a> a global instance of an class known as <a href=\"https://developer.wordpress.org/reference/classes/wp_styles/\" rel=\"nofollow noreferrer\">WP_Styles</a>, and \"doing\" that single item. (Alternatively, and preferably, use <code>wp_head()</code> in place of the <code>wp_styles()...</code> line.)</p>\n\n<pre>\n<?php\n** Custom Single Template for MyPlugin\n?>\n<!DOCTYPE html>\n<html <?php language_attributes(); ?>>\n <head>\n <?php\n // Here's where the magic happens\n wp_enqueue_style('myplugin-public-css'); // Tell WP to output this\n wp_styles()->do_item('myplugin-public-css'); // Do the output\n ?>\n ...\n\n</pre>\n\n<p>Next, you have to tell that <code>WP_Styles</code> instance what that <em>myplugin-public-css</em> is. This is where enqueuing comes into play. The <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a> method loads up the object we will later grab in the above template. As you're not using <code>wp_head()</code>, you'll have to hook into something else. So, let's try the <code>init</code> hook ...</p>\n\n<pre>\n// Notice there are no spaces inside the quotation marks ...\n// We use register the script so it is not output unless we enqueue it later. That saves on resources.\nfunction wp_myplugin_register_style() {\n wp_register_style( 'myplugin-public-css', plugin_dir_url(__FILE__).'public/css/wp-myplugin-public.min.css' );\n}\nadd_action( 'init', 'wp_myplugin_register_style' );\n</pre>\n\n<p>That should about do it. And, here's a protip: put wherever you make the call for your template. That way, your stylesheet is registered sitting in wait until such a time that it is needed: and it is only needed when it is enqueued alongside the calling of your template.</p>\n\n<p>On another note, you said you don't use <code>get_header()</code>, but I see it plain as day in your code. No need to respond one way or another on this, just wanted to point it out as no one likes to violate their own coding policy!</p>\n"
}
] | 2020/05/29 | [
"https://wordpress.stackexchange.com/questions/367821",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65317/"
] | I'm creating a plugin to add a custom post type.
For every custom post type, I also create custom single template.
The custom single template is not using get\_header(); or wp\_head() functions, it is coded from scratch manually.
I've enqueued the style like this:
```
<link rel="stylesheet" href="<?php echo esc_url( plugins_url( '/public/css/wp-myplugin-public.min.css', dirname(__FILE__) ) ); "/>
```
And when I submitted the plugin, the WordPress team encouraged me to use built-in WordPress function such as wp\_enqueue\_style() instead of above method.
Since I don't use get\_header() and wp\_head, there's no way it can be enqueued into the header of my single template.
I've tried several ways like this:
```
function wp_myplugin_enqueue_style() {
global $post;
if ($post->post_type == 'myplugin') {
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', ' wp_myplugin_enqueue_style' );
```
Including like this:
```
function wp_myplugin_enqueue_style() {
if ( get_post_type( get_the_ID() ) == 'myplugin' ) {
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', ' wp_myplugin_enqueue_style ' );
```
Also like this:
```
function wp_myplugin_enqueue_main_css() {
if (is_page_template('wp-myplugin-base-template.php')){
wp_enqueue_style( 'myplugin-public-css', plugin_dir_url( __FILE__ ) . ' public/css/wp-myplugin-public.min.css ' );
}
}
add_action( 'wp_enqueue_scripts', 'wp_myplugin_enqueue_main_css' );
```
The above codes didn't work at all.
The `<head>` of the single template looks like this:
```
<?php
** Custom Single Template for MyPlugin
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<?php if (in_array('wordpress-seo/wp-seo.php' || 'wordpress-seo-premium/wp-seo-premium.php', apply_filters( 'active_plugins', get_option('active_plugins' )))) :
if ($meta_title = get_post_meta($post->ID, '_yoast_wpseo_title', true ));
elseif ($meta_title = get_post_meta( get_the_ID(), myplugin_prefix( 'meta-title' ), true ));
else $meta_title = get_option(sanitize_text_field('myplugin_meta_title'));
if ($meta_description = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true ));
elseif ($meta_description = get_post_meta( get_the_ID(), myplugin_prefix( 'meta-description' ), true ));
else $meta_description = get_option(sanitize_text_field('myplugin_meta_description'));
?>
<?php
if ($set_noindex = get_post_meta( get_the_ID(), myplugin_prefix( 'noindex' ), true ));
else $set_noindex = get_option(sanitize_text_field('wp_myplugin_noindex'));
if ($set_nofollow = get_post_meta( get_the_ID(), myplugin_prefix( 'nofollow' ), true ));
else $set_nofollow = get_option(sanitize_text_field('wp_myplugin_nofollow'));
?>
<?php
if ($set_noindex === "yes") {
$noindex = "noindex";
} else {
$noindex = "index";
}
if ($set_nofollow === "yes") {
$nofollow = "nofollow";
} else {
$nofollow = "follow";
}
?>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php echo esc_url( get_bloginfo( 'pingback_url' ) ); ?>">
<link rel="icon" type="image/png" href="<?php echo esc_html(get_option('myplugin_upload_favicon')); ?>">
<title><?php echo $meta_title; ?></title>
<meta name="description" content="<?php echo $meta_description; ?>">
<meta name="robots" content="<?php echo $noindex ?>, <?php echo $nofollow ?>" />
<meta name="googlebot" content="<?php echo $noindex ?>, <?php echo $nofollow ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
<meta name="bingbot" content="<?php echo $noindex ?>, <?php echo $nofollow ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
<!-- WordPress team doesn't allow below method to enqueue the style -->
<link rel="stylesheet" href="<?php echo esc_url( plugins_url( '/css/wp-myplugin-public.min.css', dirname(__FILE__) ) ); ?>"/>
<?php endif; ?>
<?php $custom_css = get_option(sanitize_text_field('wp_myplugin_custom_css'));
if ($custom_css == '') {
echo '';
} else {
echo '<style type="text/css">'.$custom_css .'</style>';
}
?>
</head>
```
In order to include the `wp-myplugin-public.min.css` stylesheet, what is the best method I can use? I really need your help on this.
Thank you very much in advance! | First, you've got a heck of an obvious coding error in every one of your `wp_enqueue_style` calls: you have spaces in your quotations. Furthermore, because you are choosing not to call the `wp_head()` method, the [hook](https://developer.wordpress.org/reference/hooks/wp_head/) of the same name will not be called. That hook, in turn, [calls](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/default-filters.php#L281) the `wp_enqueue_scripts` method, which [calls](https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/#source) the hook of the same name. As you're not doing any of this, your attempts to use the `wp_enqueue_scripts` hook won't work. (You'd have to trace the code like I did to know this.) So, there are two reasons why you are FUBAR.
A word on `wp_head()`: it is used by the WordPress core to do a whole crap ton of things so WordPress can operate properly. It is good practice to use it so WordPress doesn't break, and it is a basic concept of WP development. If you don't use the built-in WP core, you'll continue to encounter these errors and you will have to figure out how to do the required core functions of the WP process on your own (which will definitely season you). [5 second read](https://developer.wordpress.org/reference/functions/wp_head/#comment-900) to learn where to call `wp_head()`. Spoiler alert: it's in between the <head> tags.
With all that in mind, here is a solution *of stylesheet output only*. Modify your template to tell WordPress to output a specific style sheet, then tell it where to output it (as you are choosing not to make [the call](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/default-filters.php#L292) to `wp_print_styles()` to output *everything else that may be required*). This can be done by [getting](https://developer.wordpress.org/reference/functions/wp_styles/) a global instance of an class known as [WP\_Styles](https://developer.wordpress.org/reference/classes/wp_styles/), and "doing" that single item. (Alternatively, and preferably, use `wp_head()` in place of the `wp_styles()...` line.)
```
<?php
** Custom Single Template for MyPlugin
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<?php
// Here's where the magic happens
wp_enqueue_style('myplugin-public-css'); // Tell WP to output this
wp_styles()->do_item('myplugin-public-css'); // Do the output
?>
...
```
Next, you have to tell that `WP_Styles` instance what that *myplugin-public-css* is. This is where enqueuing comes into play. The [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) method loads up the object we will later grab in the above template. As you're not using `wp_head()`, you'll have to hook into something else. So, let's try the `init` hook ...
```
// Notice there are no spaces inside the quotation marks ...
// We use register the script so it is not output unless we enqueue it later. That saves on resources.
function wp_myplugin_register_style() {
wp_register_style( 'myplugin-public-css', plugin_dir_url(__FILE__).'public/css/wp-myplugin-public.min.css' );
}
add_action( 'init', 'wp_myplugin_register_style' );
```
That should about do it. And, here's a protip: put wherever you make the call for your template. That way, your stylesheet is registered sitting in wait until such a time that it is needed: and it is only needed when it is enqueued alongside the calling of your template.
On another note, you said you don't use `get_header()`, but I see it plain as day in your code. No need to respond one way or another on this, just wanted to point it out as no one likes to violate their own coding policy! |
367,822 | <p>(<em>Edit:</em> going for the "Student" badge, and wondering if anyone out there could up vote this question?)</p>
<p>I answered <a href="https://wordpress.stackexchange.com/questions/367518/how-do-i-code-access-to-the-built-in-ui-of-a-cpt-when-its-placed-as-submenu-of">a question</a> about capabilities, but now I'm in need of help on the subject. And after reviewing <a href="https://developer.wordpress.org/plugins/users/roles-and-capabilities/" rel="nofollow noreferrer">the manual</a>, I'm even more confused.</p>
<p><strike>I have two custom post types both fully accessible to Administrators. I have Subscribers, some having access to one of these CPT's which is a "child" of the first and stores it's parent's ID in its <code>_adm_id</code> metadata. These "special" Subscribers have access to the parent CPT admin table so they can click a link to create child CPT posts of parents with a special status. Next, the Subscriber is allowed to edit child posts (both its own and those created by others) but only if it is of a particular custom post status. Lastly, special Subscribers are not allowed to delete posts (or edit deleted posts), not even their own.</p>
<p>Here's what I've got (working code) ...</p>
<pre>
// Setup custom post types and statuses
add_action('init', function() {
// Custom Post Types
register_post_type('adm-cpt', array(
'label' => __('Admin Only CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item',
'show_in_admin_bar' => FALSE,
'capability_type' => 'adm',
'map_meta_cap' => TRUE,
'capabilities' => array(
'create_posts' => 'administrator', // Only admin can create, not special Subscribers
),
));
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item',
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
// Custom Post Statuses
foreach(array(
'adm-childable' => __('Can Create Children'),
'sub-editable' => __('Any Subscriber Can Edit'),
) as $slug => $label) {
register_post_status($slug, array(
'label' => _x($label, 'post'),
'label_count' => _n_noop($label .' <span class="count">(%s)</span>', $label .' <span class="count">(%s)</span>' ),
'public' => TRUE,
));
}
});
// Setup parent page in admin menu
add_action('admin_menu', function() {
// Add menu item
if(current_user_can('administrator')
|| current_user_can('special-subscriber')
) {
// Admin menu header
add_menu_page(
NULL,
'CPTs',
'exist',
'my-menu-item',
''
);
}
});
// Set up role
add_action('wp_roles_init', function($wp_roles){
// Prepare
$role = 'special-subscriber';
$caps = array(
'delete_subs' => FALSE, // No trashing ...
'delete_others_subs' => FALSE,
'delete_published_subs' => FALSE,
'delete_private_subs' => FALSE,
'edit_published_subs' => FALSE, // And no editing published/private posts ...
'edit_private_subs' => FALSE,
'edit_adms' => TRUE, // Allow viewing of adm-cpt table
'edit_posts' => TRUE, // WARNING: Here's the permission that is causing the problems!
);
$name = __('"Special" Subscriber');
// Update role in database, if needed
if($wp_roles->get_role($role) === NULL
|| $wp_roles->get_role($role)->capabilities != $caps
|| $wp_roles->roles[$role]['name'] !== $name
) {
$wp_roles->remove_role($role);
$wp_roles->add_role($role, $name, $caps);
}
});
// Dynamicly set capabilities
add_action('user_has_cap', function($allcaps, $caps, $args, $user) {
foreach($caps as $cap) {
$perm = substr($cap, 0, strrpos($cap, '_'));
$type = substr($cap, strlen($perm)+1);
if(in_array($type, array('adm', 'adms')) && in_array('administrator', $user->roles)
|| in_array($type, array('sub', 'subs')) && !empty(array_intersect(array('administrator', 'special-subscriber'), $user->roles))
) {
// Check Subscriber if post is editable
if(in_array($cap, array('edit_subs', 'edit_others_subs'))
&& in_array('special-subscriber', $user->roles)
&& !in_array('administrator', $user->roles)
&& !empty($args[2])
&& ( !in_array(get_post_status($args[2]), array('sub-editable'))
&& !in_array($_REQUEST['original_post_status'], array('sub-editable', 'auto-draft')) // Creating
|| get_post_status(get_post_meta($args[2], '_adm_id', TRUE)) === 'trash'
)
) {
$allcaps[$cap] = FALSE;
}
// Add the cap
if(!isset($allcaps[$cap])
) {
$allcaps[$cap] = TRUE; // All the _adm and _sub capabilities are made available.
}
}
}
return $allcaps;
}, 10, 4);
// Add stuff to force proper navigation
add_action('post_row_actions', function($actions, $post) {
// Add link to adm-cpt table entries to create child
if(get_post_type($post) === 'adm-cpt'
&& get_post_status($post) === 'adm-childable'
&& current_user_can('edit_subs')
) {
$lbl = __('New '). get_post_type_object('sub-cpt')->labels->name;
$actions['adm-cpt-create-sub-cpt'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
admin_url('post-new.php?post_type=sub-cpt&adm_id='. $post->ID),
esc_attr('“'. $lbl .'”'),
$lbl
);
}
// Return
return $actions;
}, 10, 2);
// Modify publish metabox
add_action('post_submitbox_misc_actions', function($post) {
$arr = array();
switch(get_post_type($post)) {
case 'adm-cpt':
$arr = array('adm-childable');
break;
case 'sub-cpt':
$arr = array('sub-editable');
break;
default:
return;
}
// Check that parent exists -- Should be in an init hook, but it's prettier here.
if($_REQUEST['post_type'] === 'sub-cpt'
&& (empty($_REQUEST['adm_id']) || get_post_type($_REQUEST['adm_id']) !== 'adm-cpt')
&& (empty($post->_adm_id) || get_post_type($post->_adm_id) !== 'adm-cpt')
){
?><script>window.document.location.replace("<?= admin_url('edit.php?post_type=adm-cpt') ?>")</script><?php
return;
}
// Add custom post statuses
?><input type='hidden' name='adm_id' value='<?= $_REQUEST['adm_id'] ?>'><?php
if(count($arr)) {
?><script>
<?php foreach($arr as $k) { $obj = get_post_status_object($k); ?>
jQuery("select#post_status").append("<option value=\"<?= $k ?>\"><?= $obj->label ?></option>");
<?php if(get_post_status($post) == $k) { ?>
jQuery("#post-status-display").text("<?= $obj->label ?>");
jQuery("select#post_status").val("<?= $k ?>");
<?php } ?>
<?php } ?>
</script><?php
}
// Display parent -- Informational
if(!empty($_REQUEST['adm_id'])
|| !empty($post->_adm_id)
) {
$parent_id = $post->_adm_id;
if(!$parent_id) $parent_id = $_REQUEST['adm_id'];
?><div class="misc-pub-section misc-pub-adm-cpt">Parent: <span id="post-status-display"><?= get_the_title($parent_id) ?></span></div><?php
}
});
// Save parent ID
add_action('save_post_sub-cpt', function($post_id, $post, $update) {
// Ensure we continue only id a new child is created
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE
|| get_post_type($post_id) !== 'sub-cpt'
|| empty($_REQUEST['adm_id'])
|| get_post_type($_REQUEST['adm_id']) !== 'adm-cpt'
) return;
// Set parent ID
update_post_meta($post_id, '_adm_id', $_REQUEST['adm_id']);
}, 10, 3);
// Navigation when changed to uneditable
add_action('load-post.php', function(){
if(!empty($_REQUEST['post'])
&& get_post_type($_REQUEST['post']) === 'sub-cpt'
&& !current_user_can('edit_subs', $_REQUEST['post'])
) {
delete_post_meta($_REQUEST['post'], '_edit_lock');
wp_redirect('edit.php?post_type=sub-cpt');
die();
}
});
</pre>
<p>This issue here is that the special Subscriber is able to edit regular Posts and Comments. I understand this comes from the <code>edit_posts</code> capability, and that capability allows for the editing/creation of <strong>all</strong> post types. However, removing it prevents special Subscribers from being able to create <code>sub-cpt</code> posts, and granting <code>edit_subs</code> does not solve the problem. Neither does setting the <code>capabilities->create_post=special-subscriber</code> when registering the child CPT. I've been able to limit the ability of Subscribers from being able to create <code>adm-cpt</code> posts by defining the <code>capabilities</code> parameter when registering the post type. But I don't want special Subscribers to be able to edit/create any other posts other than those of the <code>sub-cpt</code> type, and I can't seem to figure out how.</p>
<p>I've found <a href="https://wordpress.stackexchange.com/questions/229319/create-user-role-restricted-to-specific-cpt">a Q&A</a> related to the subject, but this doesn't seem to work. The CPT's are mapped to custom capabilities, they exist, and the <code>user_has_cap</code> filter dynamically grants each of these capabilities. I've even tried expressly defining them in the <code>special-subscriber</code> role definition. Anyways, I'm sure the change is simple--<em>what is it</em>?</p>
<p>(If you're interested, I have another capability problem. When a special Subscriber sets the child CPT <code>post_status</code> to publish, the post is locked and they are forwarded to <code>edit.php</code> but I want the post to unlock and for the viewer to be forwarded to <code>edit.php?post_type=sub-cpt</code> just like is done in the <code>load-post.php</code> hook of my code, and I can't seem to figure out how.)</strike></p>
<p><strong>UPDATE</strong>: I've isolated it down to the placement of the CPT in the menu. When the CPT is registered as showing the UI using the <code>register_post_type</code> option of <code>show_in_menu=TRUE</code>, everything works as expected. But, when the CPT is added as a submenu of an old-fashioned admin menu item, things break. Adding the UI and hiding it results in the same problems, along with adding a subpage and redirecting it to the UI of the CPT. Examples:</p>
<pre>
// 1.) Works as expected if user has every custom capability
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => TRUE, // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
// 2.) Same as #1 with the exception that access to 'post-new.php' when "Add New" button is clicked is prohibited
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item', // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
add_action('admin_menu', function() {
add_menu_page(
'CPT in title bar',
'CPT in menu',
'edit_subs',
'my-menu-item',
''
);
}
// 3.) Breaks the same as #2
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => FALSE, // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
add_action('admin_menu', function() {
global $submenu;
add_menu_page(
'CPT in title bar',
'CPT in menu',
'edit_subs',
'my-menu-item'
);
add_submenu_page(
'my-menu-item',
get_post_type_object('sub-cpt')->label,
get_post_type_object('sub-cpt')->label,
'edit_subs',
'my-menu-item-sub'
);
// Change link
$url = 'edit.php?post_type=sub-cpt';
$submenu['my-menu-item'][1][2] = admin_url($url); // Set URL to view CPT
unset($submenu['my-menu-item'][0]); // Remove WP generated menu item
});
</pre>
<p>If, I can get the "Add New" functionality to work with the CPT as a subpage, I think my problem will be solved because the <code>edit_posts</code> capability giving me trouble can be specifically mapped to <code>edit_subs</code>. Anyone know how to do this?</p>
| [
{
"answer_id": 367892,
"author": "Himad",
"author_id": 158512,
"author_profile": "https://wordpress.stackexchange.com/users/158512",
"pm_score": -1,
"selected": false,
"text": "<p>I came across this some time ago, I'll try to find time to correctly debug the origin of the issue but in the meantime, try this: </p>\n\n<pre><code>/*\nThis is due to a bug that doesn't grant permission to the post-new.php unless there is a\nsubmenu with the link accesible for the user.\n*/\nglobal $submenu;\n$submenu['your_menu'][] = array(\n 'Hide me', # Do something to hide it or just leave it blank.\n 'create_posts',\n 'post-new.php?post_type=your_post_type',\n); \n</code></pre>\n"
},
{
"answer_id": 367893,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that when the special subscriber tries to <strong>Add New</strong> a sub-cpt post, it is denied permission. However, when the CPT menu is a top-admin-menu, then everything works out fine. The issue is related to the placement of the CPT's UI menu in the back-end: if it's top-level (<code>show_in_menu=TRUE</code>), all is well; if its a submenu (<code>show_in_menu='my-menu-item'</code>), the user can't create the post type unless it has the <code>edit_posts</code> permission (even if it has all the <code>edit_PostType</code> permissions in the world). I've been chasing this stupid thing since the 22nd. Thanks to the pandemic, I haven't had to do much of anything else. After 12-15 hours each of the 8 days, I finally got this little bugger picked.</p>\n\n<p>This issue had something to do with <strong>post-new.php</strong>, as all works out fine when the CPT is edited under the <strong>post.php</strong> script (which is nearly identical). The very first thing that <strong>post-new.php</strong> does is call on <strong>admin.php</strong>. On line <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin.php#L153\" rel=\"nofollow noreferrer\">153</a>, <strong>wp-admin/menu.php</strong> is called in to bat which includes <strong>wp-admin/includes/menu.php</strong> as its <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L326\" rel=\"nofollow noreferrer\">last execution</a>. On that <strong>includes/menu.php</strong> file's <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L341\" rel=\"nofollow noreferrer\">line 341</a>, the <code>user_can_access_admin_page()</code> returns <code>FALSE</code>, triggering the <code>do_action('admin_page_access_denied')</code> hook to be fired and the <code>wp_die(__('Sorry, you are not allowed to access this page.'), 403)</code> command to kill the whole process.</p>\n\n<p>The <code>user_can_access_admin_page()</code> method is defined on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2042\" rel=\"nofollow noreferrer\">line 2042</a> of the <strong>wp-admin/includes/plugin.php</strong> file. <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2064\" rel=\"nofollow noreferrer\">Line 2064</a> passed its check in that <code>get_admin_page_parent()</code> was empty. This is followed by <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2078\" rel=\"nofollow noreferrer\">line 2078</a> failing its check in that the variable of <code>$_wp_submenu_nopriv['edit.php']['post-new.php']</code> is set. The combined effect of these checks the <code>FALSE</code> boolean being returned and WordPress dies.</p>\n\n<p>The closest related script known to me is that of <strong>post.php</strong>, as the <strong>admin.php</strong> process is immediately called and runs in an identical manner, including the calling of <code>user_can_access_admin_page()</code>. Debugging demonstrates that the <code>user_can_access_admin_page()</code> is passed in the <strong>post.php</strong> script because, unlike <strong>post-new.php</strong>, none of the <code>$_wp_submenu_nopriv[____][$pagenow]</code> flags were set. So, the question is why this index is being set for <strong>post-new.php</strong> and not set for <strong>post.php</strong>.</p>\n\n<p>The <code>global $_wp_submenu_nopriv</code> is first set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L71\" rel=\"nofollow noreferrer\">line 71</a> of <strong>wp-admin/includes/menu.php</strong>, in which that variable is initialized as an empty array. If the <code>current_user_can()</code> test is not passed on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L79\" rel=\"nofollow noreferrer\">line 79</a>, the flag is set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81\" rel=\"nofollow noreferrer\">line 81</a>. At that point, the <code>global $submenu['edit.php']</code> is initialized to the point of our concern, and contains the array at *index=*10 <em>(\"Add New\", \"edit_posts\", \"post-new.php\")</em>. A review of <a href=\"https://whiteleydesigns.com/editing-wordpress-admin-menus/\" rel=\"nofollow noreferrer\">admin menu positioning</a>) reveals this entry is the <strong>Add New</strong> link made by the system for standard WP posts. The check that occurs tests whether or not the current user has the permission to <code>edit_posts</code>. As the special Subscriber user cannot edit \"posts,\" the check fails and the system breaks. When I learned this, the race was on to unset the <code>$submenu['edit.php']['post-new.php']</code> entry before <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81\" rel=\"nofollow noreferrer\">line 81</a> of <strong>wp-admin/includes/menu.php</strong> was executed. If one worked backwards from that line into <strong>wp-admin/menu.php</strong>, it would be found that the flag at issue is set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L170\" rel=\"nofollow noreferrer\">line 170</a> with the execution of <code>$submenu[$ptype_file][10] = array($ptype_obj->labels->add_new, $ptype_obj->cap->create_posts, $post_new_file)</code>. So, the hooks fired between these two points in the code will allow us to interject and unset the flag that has caused me so much strife.</p>\n\n<p>The first function called with an available hook after this setting is <code>current_user_can('switch_themes')</code> on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L185\" rel=\"nofollow noreferrer\">line 185</a>. A check in the subsequently called <code>user_has_cap</code> for this squirmy flag will occur more times than one can count, so its not really the best hook to use. Following this, the only direct hooks available are those of <code>_network_admin_menu</code>, <code>_user_admin_menu</code>, or <code>_admin_menu</code> found in <strong>/wp-admin/includes/menu.php</strong> straight away at the very top of <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L9\" rel=\"nofollow noreferrer\">the file</a> (only one of them will fire depending on if the request is for the network administration interface, user administration interface, or neither). Since calling a filter from an unrelated function is a heck of a round-about way of doing things, I chose to make use of these hooks, like so:</p>\n\n<pre>\nadd_action('_network_admin_menu', 'pick_out_the_little_bugger');\nadd_action('_user_admin_menu', 'pick_out_the_little_bugger');\nadd_action('_admin_menu', 'pick_out_the_little_bugger');\nfunction pick_out_the_little_bugger() {\n // If the current user can not edit posts, unset the post menu\n if(!current_user_can('edit_posts')) {\n global $submenu;\n $problem_child = remove_menu_page('edit.php'); // Kill its parent and get its lineage.\n unset($submenu[$problem_child[2]]); // \"unset\" is just too nice for this wormy thing.\n }\n}\n</pre>\n\n<p>Jeezers this was a shot in the dark and wayyyy to much work for less than a dozen lines of code! Since I found a bunch of people with this same problem, I <a href=\"https://core.trac.wordpress.org/ticket/50284#ticket\" rel=\"nofollow noreferrer\">opened a ticket</a> to modify the WordPress Core.</p>\n"
},
{
"answer_id": 397952,
"author": "Dave S",
"author_id": 213761,
"author_profile": "https://wordpress.stackexchange.com/users/213761",
"pm_score": 0,
"selected": false,
"text": "<p>After debugging this same problem for an hour I was grateful to find this and realize it is a known bug. I took a slightly different approach to getting around it.</p>\n<p>This bug occurs when the CPT UI is a submenu page, the CPT has custom capabilities or capability type, and the current user does not have 'edit_posts' capability. I created a custom menu page to contain several custom post types and taxonomies and avoid cluttering the admin menu. But when the user does not have 'edit_posts' capability I only need to show one or two CPTs so I don't really need the custom menu page. So to get around the problem, I check if the current user can edit_posts and assign show_in_menu based on that.</p>\n<pre><code>class Admin_Menu_Page {\n const MENU_SLUG = 'my-menu-slug';\n // ...\n public static function get_CPT_show_in_menu() {\n if ( current_user_can( 'edit_posts' ) ) {\n $result = self::MENU_SLUG;\n } else {\n $result = TRUE;\n }\n return $result;\n }\n public static function create_menu() {\n if ( self::get_CPT_show_in_menu() === self::MENU_SLUG ) {\n // Create my custom menu page\n }\n }\n}\n\nclass My_CPT {\n const POST_TYPE = 'my-post-type';\n // ...\n public static function register() {\n $args = array(\n // ...\n 'show_in_menu' => Admin_Menu_Page::get_CPT_show_in_menu(),\n // ...\n );\n register_post_type( self::POST_TYPE, $args );\n }\n}\n</code></pre>\n"
}
] | 2020/05/29 | [
"https://wordpress.stackexchange.com/questions/367822",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188811/"
] | (*Edit:* going for the "Student" badge, and wondering if anyone out there could up vote this question?)
I answered [a question](https://wordpress.stackexchange.com/questions/367518/how-do-i-code-access-to-the-built-in-ui-of-a-cpt-when-its-placed-as-submenu-of) about capabilities, but now I'm in need of help on the subject. And after reviewing [the manual](https://developer.wordpress.org/plugins/users/roles-and-capabilities/), I'm even more confused.
I have two custom post types both fully accessible to Administrators. I have Subscribers, some having access to one of these CPT's which is a "child" of the first and stores it's parent's ID in its `_adm_id` metadata. These "special" Subscribers have access to the parent CPT admin table so they can click a link to create child CPT posts of parents with a special status. Next, the Subscriber is allowed to edit child posts (both its own and those created by others) but only if it is of a particular custom post status. Lastly, special Subscribers are not allowed to delete posts (or edit deleted posts), not even their own.
Here's what I've got (working code) ...
```
// Setup custom post types and statuses
add_action('init', function() {
// Custom Post Types
register_post_type('adm-cpt', array(
'label' => __('Admin Only CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item',
'show_in_admin_bar' => FALSE,
'capability_type' => 'adm',
'map_meta_cap' => TRUE,
'capabilities' => array(
'create_posts' => 'administrator', // Only admin can create, not special Subscribers
),
));
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item',
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
// Custom Post Statuses
foreach(array(
'adm-childable' => __('Can Create Children'),
'sub-editable' => __('Any Subscriber Can Edit'),
) as $slug => $label) {
register_post_status($slug, array(
'label' => _x($label, 'post'),
'label_count' => _n_noop($label .' <span class="count">(%s)</span>', $label .' <span class="count">(%s)</span>' ),
'public' => TRUE,
));
}
});
// Setup parent page in admin menu
add_action('admin_menu', function() {
// Add menu item
if(current_user_can('administrator')
|| current_user_can('special-subscriber')
) {
// Admin menu header
add_menu_page(
NULL,
'CPTs',
'exist',
'my-menu-item',
''
);
}
});
// Set up role
add_action('wp_roles_init', function($wp_roles){
// Prepare
$role = 'special-subscriber';
$caps = array(
'delete_subs' => FALSE, // No trashing ...
'delete_others_subs' => FALSE,
'delete_published_subs' => FALSE,
'delete_private_subs' => FALSE,
'edit_published_subs' => FALSE, // And no editing published/private posts ...
'edit_private_subs' => FALSE,
'edit_adms' => TRUE, // Allow viewing of adm-cpt table
'edit_posts' => TRUE, // WARNING: Here's the permission that is causing the problems!
);
$name = __('"Special" Subscriber');
// Update role in database, if needed
if($wp_roles->get_role($role) === NULL
|| $wp_roles->get_role($role)->capabilities != $caps
|| $wp_roles->roles[$role]['name'] !== $name
) {
$wp_roles->remove_role($role);
$wp_roles->add_role($role, $name, $caps);
}
});
// Dynamicly set capabilities
add_action('user_has_cap', function($allcaps, $caps, $args, $user) {
foreach($caps as $cap) {
$perm = substr($cap, 0, strrpos($cap, '_'));
$type = substr($cap, strlen($perm)+1);
if(in_array($type, array('adm', 'adms')) && in_array('administrator', $user->roles)
|| in_array($type, array('sub', 'subs')) && !empty(array_intersect(array('administrator', 'special-subscriber'), $user->roles))
) {
// Check Subscriber if post is editable
if(in_array($cap, array('edit_subs', 'edit_others_subs'))
&& in_array('special-subscriber', $user->roles)
&& !in_array('administrator', $user->roles)
&& !empty($args[2])
&& ( !in_array(get_post_status($args[2]), array('sub-editable'))
&& !in_array($_REQUEST['original_post_status'], array('sub-editable', 'auto-draft')) // Creating
|| get_post_status(get_post_meta($args[2], '_adm_id', TRUE)) === 'trash'
)
) {
$allcaps[$cap] = FALSE;
}
// Add the cap
if(!isset($allcaps[$cap])
) {
$allcaps[$cap] = TRUE; // All the _adm and _sub capabilities are made available.
}
}
}
return $allcaps;
}, 10, 4);
// Add stuff to force proper navigation
add_action('post_row_actions', function($actions, $post) {
// Add link to adm-cpt table entries to create child
if(get_post_type($post) === 'adm-cpt'
&& get_post_status($post) === 'adm-childable'
&& current_user_can('edit_subs')
) {
$lbl = __('New '). get_post_type_object('sub-cpt')->labels->name;
$actions['adm-cpt-create-sub-cpt'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
admin_url('post-new.php?post_type=sub-cpt&adm_id='. $post->ID),
esc_attr('“'. $lbl .'”'),
$lbl
);
}
// Return
return $actions;
}, 10, 2);
// Modify publish metabox
add_action('post_submitbox_misc_actions', function($post) {
$arr = array();
switch(get_post_type($post)) {
case 'adm-cpt':
$arr = array('adm-childable');
break;
case 'sub-cpt':
$arr = array('sub-editable');
break;
default:
return;
}
// Check that parent exists -- Should be in an init hook, but it's prettier here.
if($_REQUEST['post_type'] === 'sub-cpt'
&& (empty($_REQUEST['adm_id']) || get_post_type($_REQUEST['adm_id']) !== 'adm-cpt')
&& (empty($post->_adm_id) || get_post_type($post->_adm_id) !== 'adm-cpt')
){
?><script>window.document.location.replace("<?= admin_url('edit.php?post_type=adm-cpt') ?>")</script><?php
return;
}
// Add custom post statuses
?><input type='hidden' name='adm_id' value='<?= $_REQUEST['adm_id'] ?>'><?php
if(count($arr)) {
?><script>
<?php foreach($arr as $k) { $obj = get_post_status_object($k); ?>
jQuery("select#post_status").append("<option value=\"<?= $k ?>\"><?= $obj->label ?></option>");
<?php if(get_post_status($post) == $k) { ?>
jQuery("#post-status-display").text("<?= $obj->label ?>");
jQuery("select#post_status").val("<?= $k ?>");
<?php } ?>
<?php } ?>
</script><?php
}
// Display parent -- Informational
if(!empty($_REQUEST['adm_id'])
|| !empty($post->_adm_id)
) {
$parent_id = $post->_adm_id;
if(!$parent_id) $parent_id = $_REQUEST['adm_id'];
?><div class="misc-pub-section misc-pub-adm-cpt">Parent: <span id="post-status-display"><?= get_the_title($parent_id) ?></span></div><?php
}
});
// Save parent ID
add_action('save_post_sub-cpt', function($post_id, $post, $update) {
// Ensure we continue only id a new child is created
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE
|| get_post_type($post_id) !== 'sub-cpt'
|| empty($_REQUEST['adm_id'])
|| get_post_type($_REQUEST['adm_id']) !== 'adm-cpt'
) return;
// Set parent ID
update_post_meta($post_id, '_adm_id', $_REQUEST['adm_id']);
}, 10, 3);
// Navigation when changed to uneditable
add_action('load-post.php', function(){
if(!empty($_REQUEST['post'])
&& get_post_type($_REQUEST['post']) === 'sub-cpt'
&& !current_user_can('edit_subs', $_REQUEST['post'])
) {
delete_post_meta($_REQUEST['post'], '_edit_lock');
wp_redirect('edit.php?post_type=sub-cpt');
die();
}
});
```
This issue here is that the special Subscriber is able to edit regular Posts and Comments. I understand this comes from the `edit_posts` capability, and that capability allows for the editing/creation of **all** post types. However, removing it prevents special Subscribers from being able to create `sub-cpt` posts, and granting `edit_subs` does not solve the problem. Neither does setting the `capabilities->create_post=special-subscriber` when registering the child CPT. I've been able to limit the ability of Subscribers from being able to create `adm-cpt` posts by defining the `capabilities` parameter when registering the post type. But I don't want special Subscribers to be able to edit/create any other posts other than those of the `sub-cpt` type, and I can't seem to figure out how.
I've found [a Q&A](https://wordpress.stackexchange.com/questions/229319/create-user-role-restricted-to-specific-cpt) related to the subject, but this doesn't seem to work. The CPT's are mapped to custom capabilities, they exist, and the `user_has_cap` filter dynamically grants each of these capabilities. I've even tried expressly defining them in the `special-subscriber` role definition. Anyways, I'm sure the change is simple--*what is it*?
(If you're interested, I have another capability problem. When a special Subscriber sets the child CPT `post_status` to publish, the post is locked and they are forwarded to `edit.php` but I want the post to unlock and for the viewer to be forwarded to `edit.php?post_type=sub-cpt` just like is done in the `load-post.php` hook of my code, and I can't seem to figure out how.)
**UPDATE**: I've isolated it down to the placement of the CPT in the menu. When the CPT is registered as showing the UI using the `register_post_type` option of `show_in_menu=TRUE`, everything works as expected. But, when the CPT is added as a submenu of an old-fashioned admin menu item, things break. Adding the UI and hiding it results in the same problems, along with adding a subpage and redirecting it to the UI of the CPT. Examples:
```
// 1.) Works as expected if user has every custom capability
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => TRUE, // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
// 2.) Same as #1 with the exception that access to 'post-new.php' when "Add New" button is clicked is prohibited
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => 'my-menu-item', // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
add_action('admin_menu', function() {
add_menu_page(
'CPT in title bar',
'CPT in menu',
'edit_subs',
'my-menu-item',
''
);
}
// 3.) Breaks the same as #2
add_action('init', function() {
register_post_type('sub-cpt', array(
'label' => __('Subscriber/Admin CPT'),
'show_ui' => TRUE,
'show_in_menu' => FALSE, // Take note of this
'show_in_admin_bar' => FALSE,
'capability_type' => 'sub',
'map_meta_cap' => TRUE,
));
}
add_action('admin_menu', function() {
global $submenu;
add_menu_page(
'CPT in title bar',
'CPT in menu',
'edit_subs',
'my-menu-item'
);
add_submenu_page(
'my-menu-item',
get_post_type_object('sub-cpt')->label,
get_post_type_object('sub-cpt')->label,
'edit_subs',
'my-menu-item-sub'
);
// Change link
$url = 'edit.php?post_type=sub-cpt';
$submenu['my-menu-item'][1][2] = admin_url($url); // Set URL to view CPT
unset($submenu['my-menu-item'][0]); // Remove WP generated menu item
});
```
If, I can get the "Add New" functionality to work with the CPT as a subpage, I think my problem will be solved because the `edit_posts` capability giving me trouble can be specifically mapped to `edit_subs`. Anyone know how to do this? | The problem is that when the special subscriber tries to **Add New** a sub-cpt post, it is denied permission. However, when the CPT menu is a top-admin-menu, then everything works out fine. The issue is related to the placement of the CPT's UI menu in the back-end: if it's top-level (`show_in_menu=TRUE`), all is well; if its a submenu (`show_in_menu='my-menu-item'`), the user can't create the post type unless it has the `edit_posts` permission (even if it has all the `edit_PostType` permissions in the world). I've been chasing this stupid thing since the 22nd. Thanks to the pandemic, I haven't had to do much of anything else. After 12-15 hours each of the 8 days, I finally got this little bugger picked.
This issue had something to do with **post-new.php**, as all works out fine when the CPT is edited under the **post.php** script (which is nearly identical). The very first thing that **post-new.php** does is call on **admin.php**. On line [153](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin.php#L153), **wp-admin/menu.php** is called in to bat which includes **wp-admin/includes/menu.php** as its [last execution](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L326). On that **includes/menu.php** file's [line 341](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L341), the `user_can_access_admin_page()` returns `FALSE`, triggering the `do_action('admin_page_access_denied')` hook to be fired and the `wp_die(__('Sorry, you are not allowed to access this page.'), 403)` command to kill the whole process.
The `user_can_access_admin_page()` method is defined on [line 2042](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2042) of the **wp-admin/includes/plugin.php** file. [Line 2064](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2064) passed its check in that `get_admin_page_parent()` was empty. This is followed by [line 2078](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2078) failing its check in that the variable of `$_wp_submenu_nopriv['edit.php']['post-new.php']` is set. The combined effect of these checks the `FALSE` boolean being returned and WordPress dies.
The closest related script known to me is that of **post.php**, as the **admin.php** process is immediately called and runs in an identical manner, including the calling of `user_can_access_admin_page()`. Debugging demonstrates that the `user_can_access_admin_page()` is passed in the **post.php** script because, unlike **post-new.php**, none of the `$_wp_submenu_nopriv[____][$pagenow]` flags were set. So, the question is why this index is being set for **post-new.php** and not set for **post.php**.
The `global $_wp_submenu_nopriv` is first set on [line 71](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L71) of **wp-admin/includes/menu.php**, in which that variable is initialized as an empty array. If the `current_user_can()` test is not passed on [line 79](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L79), the flag is set on [line 81](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81). At that point, the `global $submenu['edit.php']` is initialized to the point of our concern, and contains the array at \*index=\*10 *("Add New", "edit\_posts", "post-new.php")*. A review of [admin menu positioning](https://whiteleydesigns.com/editing-wordpress-admin-menus/)) reveals this entry is the **Add New** link made by the system for standard WP posts. The check that occurs tests whether or not the current user has the permission to `edit_posts`. As the special Subscriber user cannot edit "posts," the check fails and the system breaks. When I learned this, the race was on to unset the `$submenu['edit.php']['post-new.php']` entry before [line 81](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81) of **wp-admin/includes/menu.php** was executed. If one worked backwards from that line into **wp-admin/menu.php**, it would be found that the flag at issue is set on [line 170](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L170) with the execution of `$submenu[$ptype_file][10] = array($ptype_obj->labels->add_new, $ptype_obj->cap->create_posts, $post_new_file)`. So, the hooks fired between these two points in the code will allow us to interject and unset the flag that has caused me so much strife.
The first function called with an available hook after this setting is `current_user_can('switch_themes')` on [line 185](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L185). A check in the subsequently called `user_has_cap` for this squirmy flag will occur more times than one can count, so its not really the best hook to use. Following this, the only direct hooks available are those of `_network_admin_menu`, `_user_admin_menu`, or `_admin_menu` found in **/wp-admin/includes/menu.php** straight away at the very top of [the file](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L9) (only one of them will fire depending on if the request is for the network administration interface, user administration interface, or neither). Since calling a filter from an unrelated function is a heck of a round-about way of doing things, I chose to make use of these hooks, like so:
```
add_action('_network_admin_menu', 'pick_out_the_little_bugger');
add_action('_user_admin_menu', 'pick_out_the_little_bugger');
add_action('_admin_menu', 'pick_out_the_little_bugger');
function pick_out_the_little_bugger() {
// If the current user can not edit posts, unset the post menu
if(!current_user_can('edit_posts')) {
global $submenu;
$problem_child = remove_menu_page('edit.php'); // Kill its parent and get its lineage.
unset($submenu[$problem_child[2]]); // "unset" is just too nice for this wormy thing.
}
}
```
Jeezers this was a shot in the dark and wayyyy to much work for less than a dozen lines of code! Since I found a bunch of people with this same problem, I [opened a ticket](https://core.trac.wordpress.org/ticket/50284#ticket) to modify the WordPress Core. |
Subsets and Splits